text:
Arduino library redeclaration error
This is my first time here and I hope someone can be of help!
I'll try to keep it as concise as possible.
So I have two sensors/modules, 1 is an LCD screen from elecrow and another is the DS1307. Both are connected through analog 4 and 5. I tried hooking them up with the help of my breadboard but I've stumbled upon the following issue with the libraries (I don't even know if what I'm trying to achieve is possible but I'm trying nevertheless(and failing horribly while at it))
In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:22:0:

    C:\Users\c\Documents\Arduino\libraries\RTClib/RTClib.h:79:31: error: redeclaration of 'OFF'

     enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

                                   ^
In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:21:0:

    C:\Users\c\Documents\Arduino\libraries\I2C_LCD/I2C_LCD.h:457:5: note: previous declaration 'LCD_SwitchState OFF'
         OFF=0x00,

         ^
    In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:22:0:

    C:\Users\c\Documents\Arduino\libraries\RTClib/RTClib.h:79:42: error: redeclaration of 'ON'

     enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

                                              ^
In file included from C:\Users\c\Documents\Arduino\Sketches\IC2_Checker\BME280_LCD_Time\BME280_LCD_Time.ino:21:0:

    C:\Users\c\Documents\Arduino\libraries\I2C_LCD/I2C_LCD.h:458:5: note: previous declaration 'LCD_SwitchState ON'

         ON=0x01

         ^

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

What I make out of this, is that the libraries are conflicting with each other on the following:

OFF = 0x00
ON = 0x80
ON= 0x01

Is there anyway to fix this? I know that I have to edit the .h libraries but I don't know what to change and to what it should be changed, here's the library code on the module itself:
// RTC based on the DS1307 chip connected via I2C and the Wire library
enum Ds1307SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

class RTC_DS1307 {
public:
   boolean begin(void);
   static void adjust(const DateTime& dt);
   uint8_t isrunning(void);
   static DateTime now();
   static Ds1307SqwPinMode readSqwPinMode();
   static void writeSqwPinMode(Ds1307SqwPinMode mode);
   uint8_t readnvram(uint8_t address);
   void readnvram(uint8_t* buf, uint8_t size, uint8_t address);
   void writenvram(uint8_t address, uint8_t data);
   void writenvram(uint8_t address, uint8_t* buf, uint8_t size);
};

Thank you for your help!
C.C
EDIT:
I think that I might have come a bit closer. I tried implementing one of the answers and that made me get the following error:
    C:\Users\c\Documents\Arduino\libraries\RTClib\RTClib.cpp:284:1: error: 'Ds1307SqwPinMode' does not name a type

 Ds1307SqwPinMode RTC_DS1307::readSqwPinMode() {

 ^

exit status 1
Error compiling for board Arduino/Genuino Uno.

That's a whole lot less than before. I will keep this updated!
EDIT 2:
Meanwhile, I tried something entirely else like changing the name of OFF and ON Throughout the RTClib concerning only the DS1307 module. That however gives me an entirely new line of errors such as:
error: 'enum Ds1307SqwPinMode' is not a class or a namespace

  RTC_DS1307 Ds1307SqwPinMode::readSqwPinMode() {

                                              ^

and:
error: could not convert '(Ds1307SqwPinMode)mode' from 'Ds1307SqwPinMode' to 'RTC_DS1307'

   return static_cast<Ds1307SqwPinMode>(mode);

                                            ^

These errors in particular only take place in the .cpp library
This is where I am stuck now at the moment

Hint#1: You could for instance move the enum into the context of the class (and reduce the enum name, Ds1307SqwPinMode => SqwPinMode).

@MikaelPatel as example: "DS1307PinMode" ?

Hint#2: Why are some member functions "static" and others not?

@MikaelPatel if only I knew, I haven't made this library myself, this is why it's so unnerving for me as well, especially since I'm a beginner with the Arduino. The manufacturer of the code elecrow is responsible for this, I've sent them a message that there's something wrong. Now I'm waiting for a reply.. I will try to implement your solution in the meanwhile, thanks!

Hint#3: Uppercase-only symbols are traditionally used for defines (preprocessor symbols, macros, etc) in C/C++.

FINAL EDIT WITH SOLUTION:
I finally stumbled upon the last wall of issues before getting it to work,

I redownloaded all the libraries
Went to the .h library file of RTClib
Changed the variable names from OFF to OFF and on to ONN (it's stupid I know but bear with me)
Encounter an entirely new error which seemingly occurs at board version 1.6.23

Error:

In function 'global constructors keyed to
  BME280_LCD_TIME.o':
lto1.exe: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See http://gcc.gnu.org/bugs.html for instructions.
lto-wrapper.exe: fatal error: C:\Program
  Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc
  returned 1 exit status
compilation terminated.
c:/program
  files/windowsapps/arduinollc.arduinoide_1.8.15.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe:
  error: lto-wrapper failed
collect2.exe: error: ld returned 1 exit status
exit status 1 Error compiling for board Arduino/Genuino Uno.

Go to Tools > Board > Boards manager
I personally had to change "Arduino AVR Boards by Arduino version 1.6.23"  to version 1.6.21
Compile the code
And that should do the trick!

A general rule is to keep definitions such as enum's within the context of the class (library). Below is a possible refactoring:
class RTC_DS1307 {
public:
   enum SqwPinMode { OFF = 0x00, ON = 0x80, SquareWave1HZ = 0x10, SquareWave4kHz = 0x11, SquareWave8kHz = 0x12, SquareWave32kHz = 0x13 };

   ...
   static SqwPinMode readSqwPinMode();
   static void writeSqwPinMode(SqwPinMode mode);
   ...
};

Cheers!

This sure did something! Seems like I have to dig a bit in to the .cpp now! I will try to mess around a bit! Thanks!

So I tried some things such as changing the name
RTC_DS1307 Ds1307SqwPinMode::readSqwPinMode() {
but all that does is give me 'Ds1307SqwPinMode' has not been declared. I'm stuped on this one

@CCG Do not forget to accept the answer.

check my upcoming edit!


text:
How do I fill an empty array with the values from a sensor and compare it to another given array I filled before
I'm designing a safe lock of 4 digits, but the password is in terms of colors, I have 3 colors. we are obliged to use a grayscale sensor (SKU: SEN0147).
The assignment is as follows:
Write a program on Arduino that will be used as a safe lock.
Consider having 3 colors black white and grey. Black = 0, Red = 1 and White = 2.
• When  the microcontroller is  turned  on, the safe is locked. The Serial  Monitor should display:
“System is  online.”
• The combination lock should be saved in an array of integers called arr_code.
• The user has 3 trials to open the safe
• The system will wait for the user to enter 4 colors. To enter a color, the    grayscale sensor should be  place   on  top of  the desired color.  Once    ready   the push    button  is  pressed. Once released, the color   is  saved   in  another array called arr_user_code.
• Once 4    colors  are entered,    the system  should  test    automatically   if  the code    entered by
the user    is  equal   to  the code    saved   in  arr_code.
• If    the wrong   code    is  entered,    the serial  monitor displays:   “Wrong  Code.   Try Again.”
• If    the user    enters  the wrong   code    3   times   in  a   row the system  is  locked  and a   message is
displayed:  “System Locked.”
• If    the correct code    is  inserted,   the Led on  pin 13  is  turned  on.
• The   combinations    entered by  the user    should  be  displayed   on  the Serial  Monitor.
The Arduino program should  be  clear,  separated   into    functions   and documented.
The program I wrote is the following:
char led_pin = 13;
char pb_pin = 2;
int gs_pin = A0;
//the brightness of the flash light im using is giving 894 value so im using it for testing purpose
int arr_code[4] = { 894, 894, 894, 894 };
int arr_user_code[4];

int counter;
int Lock_Interval = 2500;

char trigger = false;
bool equal = true;
char led_state = false;

int Array_Compare(int *a, int *b) {
  for (int i = 0; i < 4; i++) {
    if (a[i] != b[i]) return 0;
    else return 1;
  }
}

void Button_Wait(int buttonPin) {//function to sense if button is pressed
  int curr_state;
  int prev_state;

  while (1) {
    prev_state = curr_state;
    curr_state = digitalRead(buttonPin);
    if (curr_state != prev_state) {
      if (curr_state == false) {
        delay(10);
        return;
      }
    }
  }
}

int GS_Value(int gsPin) {
  int gs_value = analogRead(gs_pin);
  return gs_value;
}

void setup() {
  // put your setup code here, to run once:
  pinMode(led_pin, OUTPUT);
  pinMode(pb_pin, INPUT);
  Serial.begin(9600);
  digitalWrite(led_pin, false);
}

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

  Serial.println("System Online");
  Serial.println("Please Enter Passcode:");

  for (counter = 0; counter < 3; counter++) {
    for (int i = 0; i < 4; i++) {//uploading user array with gs values
      Button_Wait(pb_pin);
      arr_user_code[i] = analogRead(gs_pin);
      Serial.print(analogRead(gs_pin));//printing values on monitor
      Serial.print(" ");
    }

    Serial.println(" ");

    for (int i = 0; i < 4 && equal; i++) {//testing if passcode is true
      if (arr_user_code[i] != arr_code[i]) {
        equal = false;
      }
      else equal = true;
    }
    if (equal == true) {
      Serial.println("System Unlocked");
      digitalWrite(led_pin, true);
    }

    else if (equal == false) {
      Serial.println("Wrong Passcode. Try Again");
    }
  }

  /*Array_Compare( arr_user_code, arr_code);
  if (Array_Compare) Serial.println("System UNLOCKED");
  else Serial.println("Wrong Passcode. Try Again");
  */
  if (trigger == false) {//for locking the system
    Serial.println("System LOCKED!");
    while (1) {
      Lock_Interval = Lock_Interval * 2;//CHANGE TO MINUTES LATER ON!!
      delay(Lock_Interval);
      return;
    }
  }
  delay(100);
}

I'm sorry for having a lot of functions not used and a lot of canceled algorithms by remarks but its my scratch. the issue is that my program is always giving me a wrong passcode even if its correct.
Can you help me find the problem please? Thank you in advance.

Are the values you see printed over Serial correct?

yes i set the password according to them

Since you have else return 1; in Array_Compare this will terminate always after the first iteration.. A return 1; must be placed after the for loop.

@MaximilianGerhardt you are correct, but the code isn't calling the function.

@RamblinRose true. A few more remarks.  In the code arr_user_code[i] = analogRead(gs_pin); Serial.print(analogRead(gs_pin)); the value in the array and the one printed out can be different since you're taking 2 different ADC measurements (is that even what you want)? You should print arr_user_code[i]. Also then before comparing it  to the other array you should print out its full contents. Then you'll see if there is a difference in the values.

@RayanHamadeh what is the purpose of the outermost loop on "counter"?

@RamblinRose the outermost counter is to block the whole system if the code is entered wrong 3 times

@MaximilianGerhardt, in this case, the value printed on the Serial  Monitor will be a random number 30 thousand something which isn't the value from the sensor for sure

@RayanHamadeh a analogRead returned a value beyond 30K? Should be 0-1023. Can you edit the question to show the current code that you're running?

Since you are trying to distinguish tree different colours, I assume you are using SEN0147 in analog mode. That means the sensor output is between 0-5V. I do not believe that this will always be exactly a value of 894.
I suggest to change your comparison check in a way not to check if values are identical but to check if values are in a certain range. (additionally to all the answers @RamblinRose already suggested)
Here is a modification of the comparison loop of @RamblinRose with the change I propose. Check with different values of threshold, starting from high to lower values.
// returns 1 if equal, 0 otherwise.
int Array_Compare(int *a, int *b) {

   int threshold = 500;
   int temp;
   for (int i = 0; i < 4; i++) {
       temp = a[i] - b[i];
       if (abs(temp) > threshold)
       return 0;
   }
   return 1;
}

Your program has a lot of issues, but the main problem revolves around
if (trigger == false)

The code initializes this to false and the logic never alters the value, thus the program will always indicate "System LOCKED!"
It looks like you've mixed the variables trigger and equal.  Get rid of the trigger variable and use equal.
if (equal == false) {//for locking the system
    Serial.println("System LOCKED!");
    while (1) {
      Lock_Interval = Lock_Interval * 2;//CHANGE TO MINUTES LATER ON!!
      delay(Lock_Interval);
      return;
    }
  }

I recommend a different variable name to equal, such as "unlock", as it makes clear the use of the variable.  Also, initialize variables such as "equal" at the beginning of loop().  Good luck.
EDIT
Your comparison check in loop() is valid.  However if you have to use Array_Compare, here is the fix.
// returns 1 if equal, 0 otherwise.
int Array_Compare(int *a, int *b) {
   for (int i = 0; i < 4; i++) {
       if (a[i] != b[i])
          return 0;
   }
   return 1;
}

Then in loop, remove your local comparison loop with
//for (int i = 0; i < 4 && equal; i++) {//testing if passcode is true
//  if (arr_user_code[i] != arr_code[i]) {
//      equal = false;
//  }
//  else equal = true;
//}

equal = Array_Compare(arr_user_code, arr_code);

I'm not comfortable writing your program for you, this is not a coding service.

but this doesn't solve the issue concerning comparing arr_user_code and arr_code

@RayanHamadeh the code is comparing the arrays in the loop() function, and altering the 'equal' variable according to the comparisons made.

source: Stack Exchange

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

sort: votes


text:
how do i fill an array from a grayscale sensor (SKU:SEN0147)?
I'm designing a safe lock of 4 digits, but the password is in terms of colors, I have 3 colors. we are obliged to use a grayscale sensor (SKU: SEN0147).
The assignment is as follows:
Write a program on Arduino that will be used as a safe lock. Consider having 3 colors black white and grey. Black = 0, Red = 1 and White = 2.
• When the microcontroller is turned on, the safe is locked. The Serial Monitor should display: “System is online.”
• The combination lock should be saved in an array of integers called arr_code.
• The user has 3 trials to open the safe
• The system will wait for the user to enter 4 colors. To enter a color, the grayscale sensor should be place on top of the desired color. Once ready the push button is pressed. Once released, the color is saved in another array called arr_user_code.
• Once 4 colors are entered, the system should test automatically if the code entered by
the user is equal to the code saved in arr_code.
• If the wrong code is entered, the serial monitor displays: “Wrong Code. Try Again.”
• If the user enters the wrong code 3 times in a row the system is locked and a message is
displayed: “System Locked.”
• If the correct code is inserted, the Led on pin 13 is turned on.
• The combinations entered by the user should be displayed on the Serial Monitor. The Arduino program should be clear, separated into functions and documented.
The program I wrote is the following:
char led_pin = 13;
char pb_pin = 4;
int gs_pin = A3;

int arr_code[4] = {14, 14, 14, 14};//color im testing on
int arr_user_code[4];

int counter;
int Lock_Interval = 2500;
bool compare;

bool equal = true;

bool Array_Compare(int *a, int *b) {//function for comparision
  for (int i = 0; i < 4; i++) {
    if (a[i] != b[i]) return false;
  }
  return true;
}

void Button_Wait(int buttonPin) {//function to sense if button is pressed
  int curr_state;
  int prev_state;

  while (1) {
    prev_state = curr_state;
    curr_state = digitalRead(buttonPin);
    if (curr_state != prev_state) {
      if (curr_state == false) {
        delay(10);
        return;
      }
    }
  }
}

int GS_Value(int gsPin) {//function to get GSsensor value
  Button_Wait(pb_pin);
  int gs_value = analogRead(gs_pin);
  return gs_value;
}

void setup() {
  // put your setup code here, to run once:
  pinMode(led_pin, OUTPUT);
  pinMode(pb_pin, INPUT);

  Serial.begin(9600);//sync

  digitalWrite(led_pin, false);//start with a turned off LED
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("System Online");
  Serial.println("Please Enter Passcode: ");

  for (counter = 0; counter < 3; counter++) {
    for (int i = 0; i < 4; i++) {
      arr_user_code[i] = GS_Value(gs_pin); //uploading GSsensor values to array !!!the problem is here!!!

      Serial.print('GS_Value');//printing GSsesnor values on monitor
      Serial.print(" ");//inserting space
    }
    Serial.println(" ");//skipping a line after every attempt

    compare = Array_Compare( arr_code[4], arr_user_code[4]); // compare arrays and return false if not equal

    if (compare == true) {//in case arrays are equal
      Serial.println("System UNLOCKED!");
      digitalWrite(led_pin, true);
    }

    else if (compare == false) {//in case arrays arent equal
      Serial.println("Wrong Passcode. Try Again");
    }
  }

  if (compare == false) {
    Serial.println("System LOCKED");
    while (1) {
      Lock_Interval = Lock_Interval * 2;
      delay(Lock_Interval);
      return;
    }
  }
  delay(100);
}

the issue is that the arr_user_code isnt actually filling with the correct sensor values but a value between 20000 and 30000. Thank you in advance.

How do you know the values? I don't see you printing them anywhere.

please proofread your post

you have no code that prints tthe value of GS_Value ........... why are you comparing arrays?

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


text:
Does baud rate for HC-05 Bluetooth module need to match the Serial Monitor?
I have this sketch that I got as a sample.  I have the two HC-05s connected.  What I type in one serial monitor shows up on the other, but as question marks.  The most common reason for this I find is baud rate doesn't match.   I didn't change the baud rate on the HC-05s when I got them, so I assume they are set to default.  I can put them in command mode and ensure the baud rate is set.
Does the baud rate of the HC-05s have to match the baud rate of the Serial monitor?  I would assume not.  I am also wondering if this is a problem with formatting a char[] when writing to the serial display.
#include <SoftwareSerial.h>
SoftwareSerial BTserial(7, 8); // RX | TX
// Connect the HC-05 TX to Arduino pin 7 RX.
// Connect the HC-05 RX to Arduino pin  8 TX through a voltage divider.
//

char c = ' ';

void setup()
{
Serial.begin(9600);
Serial.println("Arduino is ready");
Serial.println("Remember to select Both NL & CR in the serial monitor");

// HC-05 default serial speed for AT mode is 38400
BTserial.begin(38400);
}

void loop()
{

// Keep reading from HC-05 and send to Arduino Serial Monitor
if (BTserial.available())
{
    c = BTserial.read();
    Serial.println(c);
}

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

It was the baud rate.  I read the baud rate from the bluetooth modules, it was set to 9600.  I tweaked the code and its working now

Both of these comments should be answers @jsotola

@jsotola thanks.  I didn't think so.

No, they do not need to match.
You are talking about two separate serial port connections.
The baud rate between the HC-05 and the Arduino (BTserial) has to match.
The baud rate between the Arduino and your PC (Serial) has to match.
BTserial and Serial can use different baud rates.
An overflow problem can arise if a lot of data arrives from the HC-05 and there is not enough memory to store it until it can be forwarded to Serial.

simulate this circuit – Schematic created using CircuitLab


text:
I need a random code for Arduino Uno to trigger a single relay
I am trying to get a random triggering of a single relay from an Arduino Uno. I would also ultimately like to be able to adjust the speed that the random triggering happens at. How are the times between the randoms adjusted?
I have tried some codes and have the relay hooked up to pin 8 on the Uno, and would like more control. Thanks
void setup () {
pinMode(8, OUTPUT);
}

void loop() {

long randnumber;
long randnumber2;
long randnumber5;
long randnumber6;

randomSeed(analogRead(A0));

randnumber = random(5, 9);
randnumber2 = random(5,9);
randnumber5 = random(3370,498);
randnumber6 = random(537,4370);

digitalWrite(randnumber, HIGH);
digitalWrite(randnumber2, LOW);
delay(randnumber5);
digitalWrite(randnumber, LOW);
digitalWrite(randnumber2, HIGH);
delay(randnumber5);
}

Can you show us the sketch you are using now?

Use the blink-without-delay https://www.arduino.cc/en/tutorial/BlinkWithoutDelay Remove the 'const' of the variable interval, and use random https://www.arduino.cc/reference/en/language/functions/random-numbers/random/ for the interval. Set the new random interval inside the if-statement. Adjust the min and max parameters of the random for speed control.

VE7JRO, Here is the code I have so far:       void setup () {
pinMode(8, OUTPUT);
}
void loop() {
long randnumber;
long randnumber2;
long randnumber5;
long randnumber6;
randomSeed(analogRead(A0));
randnumber = random(5, 9);
randnumber2 = random(5,9);
randnumber5 = random(3370,498);
randnumber6 = random(537,4370);
digitalWrite(randnumber, HIGH);
digitalWrite(randnumber2, LOW);
delay(randnumber5);
digitalWrite(randnumber, LOW);
digitalWrite(randnumber2, HIGH);
delay(randnumber5);
}

This is my 1st Arduino project

@WaddyP consider editing your original post by adding your code section. Non trival code in a comment section is nearly unreadable.

Yeah, don't post multiple lines of code in comments. Edit your question and add the code using code tags.

RamblinRose, don't know how to do that. I am new here

there are 4 buttons just below your question .... one of then is edit


text:
Creating an array of structures which store bitmaps to work with u8glib
I've tried reading the documentations and I'm getting desperate because I can't find anything.
I need to create an array of structures, which contains a bitmap stored in PROGMEM space (because of issues with memory usage).
The bitmaps are created as follows:
const uint8_t pat[] PROGMEM = {
...
};

Then I need to create a structure like this:
typedef struct{
    uint8_t bitmap[8];
} chars;

chars allChars[1];

but the compiler doesn't like that for some reason and spit out a bunch on invalid conversion from const to char so it was clear I couldn't use that!
My next attempt was to create a pointer to the pattern like so:
typedef struct{
    const uint8_t *bitmap[8];
} chars;

chars allChars[1];

This time it again gave warnings about invalid conversion but at least compiled!
I then tried to write the entire code and run it:
#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

typedef struct{
    const uint8_t *bitmap[8];
} chars;

chars allChars[1];

const uint8_t pat[] PROGMEM = {
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x66
};

void draw(void) {
  u8g.drawBitmapP( 37, 28, 1, 8, pat);
  u8g.drawBitmapP( 74, 28, 1, 8, (char*) allChars[0].bitmap);
}

void setup(void) {
  allChars[0]= (chars) {*pat};
}

void loop(void) {
  draw();
  while(true);
}

the first line where I have used the pattern directly in the draw function, works perfectly fine, but the second line which retrieves the value from the pointer draws some weird noise shape (I'm guessing memory dump of an address or something)!
Is it even possible to create a struct with one of the variables being just a pointer to the constants that I have defined earlier? I'm pretty sure I'm doing something very wrong as I'm not familiar with using pointers and addresses and whatnot, so it would be great if someone could help with these issues!

Try "allChars[0].bitmap = pat;"

That still wouldn't solve the issue with struct!
I think I have found a glitch in GCC compiler where if you define your struct in dynamic memory rather than PROGMEM, even if you use a buffer and fetch the data using memcpy_P, it will return the correct value while printing, but when you copy it again to allChars[0].bitmap , the wrong value is copied! the thing that solved the issue was adding PROGMEM to the struct like below:
typedef struct {
  unsigned int ascii;
  int size[2];
  const PROGMEM unsigned char *bitmap;
} chars;

I have not yet encountered any compilers that are this specific and don't even allow transfer between memory spaces correctly. (Not to mention other issues with GCC linker that are brought up by david from eevblog like stack overflow without warning, etc). They really need to solve issues like this as this compiler is one of the most frequently used on different platforms.
anyways, here is the final code if anyone finds it useful (I will probably end up making a youtube video about it later):
#include "U8glib.h"
//U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

typedef struct {
  unsigned int ascii;
  int size[2];
  const PROGMEM unsigned char *bitmap;
} chars;

chars allChars[1];

const unsigned char pat[] PROGMEM = {
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x01, 0xfc, 0x00,  //.......%%%%%%%.......
  0x0f, 0xff, 0x00,  //....%%%%%%%%%%%%.....
  0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
  0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
  0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
  0x0f, 0xff, 0x80,  //....%%%%%%%%%%%%%....
  0x01, 0xfc, 0x00,  //.......%%%%%%%.......
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
};

void charToBitmap(int x, int y, char chr){
  for(unsigned int i=0; i<sizeof(allChars);i++){
    if (allChars[i].ascii=chr){
      u8g.drawBitmapP( x, y, allChars[i].size[0], allChars[i].size[1], allChars[i].bitmap);
      break;
    }
  }
}

void draw(void) {
  charToBitmap(0,0,'0');
}

void setup(void) {
  allChars[0] = (chars) {48,{3,54},pat};
}

void loop(void) {
    u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );
}

You're making it far too hard on yourself.
All you need is a single 2-dimensional array of data in PROGMEM:
const uint8_t bitmaps[10][8] PROGMEM = {
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
  { 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x66 },
};

Each row is a bitmap, and there are 10 rows, so 10 bitmaps (I have them all the same at the moment).
Then you just reference the slice number you are interested in:
u8g.drawBitmapP( 100, 30, 1, 8, bitmaps[3]);

Note: I haven't tested this.


text:
Weird problem with arduino
I wrote the code below and the result is not what I expected at all! I'm not sure why it's happening!
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

const uint8_t pat[] PROGMEM = {
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x66
};

void loop() {
  delay(100);
  Serial.println(sizeof(pat));
  for (int i=0; i<8; i++){
    Serial.print(pat[int(i)],HEX);
  }
  Serial.println("");
  Serial.print(pat[0],HEX);
  Serial.print(pat[1],HEX);
  Serial.print(pat[2],HEX);
  Serial.print(pat[3],HEX);
  Serial.print(pat[4],HEX);
  Serial.print(pat[5],HEX);
  Serial.print(pat[6],HEX);
  Serial.print(pat[7],HEX);
  Serial.println("");
  while(true);
}

the output is surprisingly this:

8
008000010
FF0FF0FF0FF66

What is compiler doing in the background but it seems to be messing things up really bad! The loop should be doing the exact same thing as manually writing that code over and over but it's not! How can I fix the loop?

does the output represent one iteration of loop()?  .....  you really need to print a delimiter by using something like Serial.println("--------------");

If you want to get a value from PROGMEM you must read it with pgm_read functions. Read the PROGMEM reference.
for (int i = 0; i < 8; i++) {
  Serial.print(pgm_read_byte_near(pat + i),HEX);
}

pat[0] in Serial.print(pat[0],HEX); is an item in a constant array const uint8_t pat[]. it can't change at runtime so the compiler uses the value 0xFF. that is why it is printed ok without pgm_read_byte_near

that would explain it, but why when I write pat[6] manually in print statement, it doesn't return the same value? somehow only the loop values are replaced at compile time?

@OM222O, as I write in the answer, the constant uses are replaced at compilation

My question still remains: Why is the code in the loop SPECIFICALLY replaced during compilation? if I do something i=0; print(pat[i]); it should not be different to print(pat[0]); ! it's almost as if the compiler is treating integers differently!

because using the value from the array position requires less instructions then getting the value from the array every time. the compiler optimizes for small size of the binary

that wouldn't make a ton of sense! they're both ints! I even made sure to use int(i)! The int is created and the increased ever cycle the program runs!

@OM222O, pat[0] in Serial.print(pat[0],HEX); is an item in a constant array const uint8_t pat[]. it can't change at runtime so the compiler uses the value 0xFF. that is why it is printed ok without pgm_read_byte_near


text:
Combining sketches
I have two codes for my to sensors and they work separately. However, I need to combine them in one program please can you help?
The pulse code
 /* PulseSensor Starter Project and Signal Tester
 *  The Best Way to Get Started  With, or See the Raw Signal of, your PulseSensor.com™ & Arduino.
 *
 *  Here is a link to the tutorial
 *  https://pulsesensor.com/pages/code-and-guide
 *
 *  WATCH ME (Tutorial Video):
 *  https://www.youtube.com/watch?v=RbB8NSRa5X4
 *
 *
-------------------------------------------------------------
1) This shows a live human Heartbeat Pulse.
2) Live visualization in Arduino's Cool "Serial Plotter".
3) Blink an LED on each Heartbeat.
4) This is the direct Pulse Sensor's Signal.
5) A great first-step in troubleshooting your circuit and connections.
6) "Human-readable" code that is newbie friendly."

*/

//  Variables
int PulseSensorPurplePin = 0;        // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
int LED13 = 13;   //  The on-board Arduion LED

int Signal;                // holds the incoming raw data. Signal value can range from 0-1024
int Threshold = 550;            // Determine which Signal to "count as a beat", and which to ingore.

// The SetUp Function:
void setup() {
  pinMode(LED13,OUTPUT);         // pin that will blink to your heartbeat!
   Serial.begin(9600);         // Set's up Serial Communication at certain speed.

}

// The Main Loop Function
void loop() {

  Signal = analogRead(PulseSensorPurplePin);  // Read the PulseSensor's value.
                                              // Assign this value to the "Signal" variable.

   Serial.println(Signal);                    // Send the Signal value to Serial Plotter.

   if(Signal > Threshold){                          // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
     digitalWrite(LED13,HIGH);
   } else {
     digitalWrite(LED13,LOW);                //  Else, the sigal must be below "550", so "turn-off" this LED.
   }

delay(10);

}

The gsr code:
void setup()
{
    Serial.begin(9600);
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    digitalWrite(2, HIGH);
    delay(500);
    digitalWrite(3, HIGH);
    delay(500);
    digitalWrite(4, HIGH);
    delay(500);
}

void loop()
{
    if (analogRead(A0) > 60)
    {
        digitalWrite(4, HIGH);
    }
    else
    {
        digitalWrite(4, LOW);
    }
    if (analogRead(A0) > 20)
    {
        digitalWrite(2, HIGH);
    }
    else
    {
        digitalWrite(2, LOW);
    }
    if (analogRead(A0) > 45)
    {
        digitalWrite(3, HIGH);
    }
    else
    {
        digitalWrite(3, LOW);
    }

    Serial.println(analogRead(A0));
    delay(20);
}

just combine the codes in setup and loop functions - at a quick glance, there shouldn't be any conflict - have you even tried? if so, what problem did you face?

I faced problem my sensor not reading and i tried to change the analog input  but it wouldn't read

Please provide us with the actual combined code so we can compile and flash it. Also the corresponding output of your three codes could be helpful


text:
Prints to the serial monitor are being overwritten
Using esp32, Arduino IDE 1.8.9 on OSX.
My code is interspersed with Serial.println() writes to the serial monitor of various status messages.
As far as I can tell, if a println is not fully written out to the serial monitor before another println is sent, then the first println does not finish displaying properly, and appears to garbled.
I'm using baud rate 115200.
I'm guessing that there's no flow control between the serial monitor and the computer.
It's strange though because I've been doing quite a bit of Arduino IDE programming for a while now but I don't ever recall this being an issue.
Does anyone have any idea of what might be going on, and how I can ensure that messages are fully displayed on the serial monitor?

I've never had such an issue - perhaps you're doing something unusual in your code - are you able to create a minimal piece of code that produces this odd behaviour

There is no flow control. Please post code that exhibits this behaviour - perhaps you have a bug.


text:
Selection of External CT for my application
Here I have attached my ckt for my application. My application is Motor protection Relay. Based on Current sense of 3 CT tripping of relay will occur. Tripping might due to under/over/SC/Locked rotor Etc. Now I am facing in selection of CT and interfacing with Arduino Un0.
I know HP rating and its max current measurement range.

How to Select CT for my application based on Current measurement range
How Burden resistor calculated.
How Size of CT can be calculated.
How to judge max supply voltage supplied to Arduino
Type of CT to be used protection class CT or Normal CT
How to calculate Max Current level can read through CT. it will be mentioned in datasheet. what it will do when it cross rated current? means when it attain saturation if I use above circuit what is effect on Arduino Uno board.
How burden VA calculated here.

I have researched and got one of application where they using AC AC1030 datasheet
Ip=30A I max=75A
 turns ratio: 1000:1
 supply voltage = 220VAC
min power continuous CT can sense = 220X30 = 6.6 kW
Max power sense for short period=220*75=16.5 kW
 Irms=1.4*30A=42A

burden resistor= 2.5/(42/1000)=59.5ohm R1=R2=100kohm resistor.
Is it correct? What are other care I need to consider while taking hardware design?


text:
Is this a good way to filter noise due to vibration in limit switch?
I have a circuit connected as follows

my limit switches which are attached to my structure sometimes gets falsely triggered, so I wrote this code to address it. My motor is supposed to go down skip the up limit switch at first hit the down one then go back to the up one. is this a good way to implement it?
https://pastebin.com/qVU1Gp0q
//Switch pressed ->  reading HIGH
//Switch not pressed -> reading LOW
//Motor direction 0 is down, 1 is up

const int uplimit = 32;
const int downlimit = 34;
const int motorspeed = 9;
const int motordirection = 28;
//const int pumpspeed=5;
//const int pumpdirection=6;
const int motorenable = 26;
//const int pumpenable=;
int Finishedcleaning = 0;
int Reachedup = 0;
int Motorinitialsetup = 0;
int Motorsecondsetup = 0;
int downfiltered = 0;
int upfiltered = 0;
void setup() {
  // put your setup code here, to run once:

  pinMode(motorspeed, OUTPUT);
  pinMode(motordirection, OUTPUT);
  pinMode(motorenable, OUTPUT);
  //pinMode(pumpspeed, OUTPUT);
  //pinMode(pumpenable, OUTPUT);
  pinMode(uplimit, INPUT);
  pinMode(downlimit, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int average1 = 0;
  int average2 = 0;
  if (Motorinitialsetup == 0 ) // to be run before hitting initial switch
  { digitalWrite(motorenable, HIGH);
    analogWrite(motorspeed, 190);
    digitalWrite(motordirection, 0); // Bring motor down
    //   digitalWrite(pumpenable,HIGH);
    //  digitalWrite(pumpdirection,1);
    // analogWrite(pumpspeed,240);
    Motorinitialsetup = 1; //so this if statement does not run again

  }

  for (int i = 1; i < 100; i++)
  { downfiltered = digitalRead(downlimit);
    average1 = average1 + downfiltered;
  }
  average1 = average1 / 100;

  if ((average1 > 0.9) && Finishedcleaning == 0 ) // Function after hitting down switch
  {
    delay(1000); // wait until motor cross switch
    analogWrite(motorspeed, 0); // stop motor
    Finishedcleaning = 1; //indicate cleaning is over for next loop
    delay(500); // wait until motor cross switch
  }

  if ( (Finishedcleaning == 1) &&   (Reachedup == 0)  && (Motorsecondsetup == 0))
  {
    digitalWrite(motordirection, 1); // reverse motor direction
    analogWrite(motorspeed, 190); // start motor again
    Motorsecondsetup = 1;
  }

  if ( Motorsecondsetup == 1) // only checks switch up switch after motors comes back
  {

    for (int i = 1; i < 300; i++)
    { upfiltered = digitalRead(downlimit);
      average2 = average2 + downfiltered;

    }
    average2 = average2 / 300;
    if ((average2 > 0.9) && (Finishedcleaning == 1)) // Stop Motor after returning
    { analogWrite(motorspeed, 0);
      delay(1000);
      Reachedup = 1; // indicate finished returning after cleaning cycle
    }
  }
}

Start by increasing consistancy and quality. Why does one switch have a pull down resistor of 220 ohm and the other of 4k7 ohm? In your sketch, the indents and brackets are all over the place. Try pressing ctrl+t in the arduino ide. Please describe in words how you want to filter the spikes before you put that in code. Put the sketch itself in your question please, instead of a link.

They both have 4k7
Also I used pastebin for the code because it has C formating I want to filter it by taking 100 points average of the digital reading to make sure it's actually high.

@Jot I added the code to the post.

It can also be the wiring. Noise from the motor can induce a signal on the limit switch wiring. A capacitor in parallel to each limit switch can help with this.

@sa_leinad I thought the capacitor should be in series with the resistor for an RC filter? then I could take the output from the capacitor? since a capacitor is a short circuit at high frequency thus would give me 0 volt?

I'm sorry to say that your wiring is wrong. Here is just one reference https://electronics.stackexchange.com/q/237938/104097. More if you Google  "switch debounce capacitor".

Hardware:
You have the switch at 5V with a pull down resistor.
When using longer wires or when everything is put into a box, it might be safer to have a GND wire to the switch (with a pull up resistor) instead of a 5V wire. When a switch or button is connected with a shielded cable, it can also be better to connect one pin of the switch to GND.
If you change the switch and connect one pin to GND with pullup resistor, then you have to change the sketch as well, because the pin will become LOW when the switch is pressed.
You may add a capacitor of 1 nF to 100 nF between the digital input and GND. That will help against spikes and noise.
The pull down resistors of 4k7 is a high value for a noisy environment. I suggest to use 470 Ω or 1k resistors.
The ground path is very important. You have the GND of the motor driver connected to the breadboard and that is also where the switches are connected. That means the input (switches) and the output (motor driver) share a piece of ground wire. Always avoid such situations.
Breadboards have often bad contacts. If the GND to the breadboard is not very solid, then you are injecting the input pins with noise from the output pins of the Arduino board.
Use two seperate breadboards for input and output. Or connect the GND of the motor driver directly to the Arduino board.
Software:
An integer can not be 0.9, therefor your filter does not work.
The function digitalRead() returns HIGH or LOW. You add those values, but I prefer to stick with HIGH or LOW.
Taking multiple samples and have a threshold is a good idea. Do you really need 100 or 300 samples? A button may bounce for 10 ms, so I suggest to use about 20 samples during 20 ms.
int digitalReadFiltered(int pin) {
  int result;
  const int n = 20;                // maximum 30
  int count = 0;                   // an integer can hold 30 analog samples

  for (int i = 0; i < n; i++) {
    if (digitalRead(pin) == HIGH) {
      count++;
    }
    delay(1);        // 1 ms for sampling during 20 ms with 20 samples
  }

  if (count > (n / 2)) {
    result = HIGH;   // counted enough HIGH values
  } else {
    result = LOW;
  }

  return(result);
}

In short, a pull down (or pull up) resistor with a low value makes the circuit low impedance, and the electrical noise will have less influence.
When a button is pressed, that connects the digital input pin of the Arduino board directly to 5V (or GND). Then it is almost impossible that electrical noise can get to that pin.
When a button is not pressed, then the resistor keeps the input pin low (or high). Then electrical noise can cause spikes.
A circuit with low impedance is less influenced by the electrical noise. The lower the value of the resistor, the less troubles with noise.
It is not something that can be calculated, see it as electrical/capacitive/electromagnetic/radio-noise combined with bad ground currents from a wrong ground path. What is the best way to receive that? With a high impedance circuit of course.
A pull down (or pull up) resistor with a value of 10k can be used when there are no wires connected to it that are going outside the circuit board. When there is a button with wires, then I would suggest a lower value, for example 2k2 or 4k7. Since you have troubles with noise, I suggest a value of 470 Ω or 1k.

Thank you, this is a very good and detailed answer. Would there be any apprehension about using a 47uF capacitor instead just to be safe? Also, I think my filter works just by changing int average to double average, or was that what you meant to say?

Also may I ask why would a higher resistance increase noise? I thought it would be the opposite if I have (V+v_n)/R = V/R +vn/R and vn/R goes to zero for high values of R  thus there is less noisy current with high resistance?

Using float (the arduino uno has no double) for the average should also work, but then you still add HIGH + HIGH + HIGH, I think that is weird. A capacitor of 47µF seems way much. I shall add a paragraph to my answer about the resistor.


text:
How to perform two tasks in one loop in Arduino?
I am trying to make a weather monitor using Arduino. I want my weather monitor to send me a message of the weather data every 5 hours using GSM sheild. Also, there is an LCD on my weather monitor which shows live weather conditions. The problem I am facing is that the delay of 5 hours in my code also applies to the LCD which updates the LCD every 5 hours and not every second as it should. Please tell me how to run these two functions simultaneously.

see the BlinkWithoutDelay example

Here is a simple abstraction (Timemark) that makes it very easy to write. https://github.com/mikaelpatel/Arduino-Timemark/blob/master/Timemark.h

please post your code

Consider using a finite state machine to track multiple tasks.  Specifically, the state in which you send your message once every 5 hours.  And, the state you update your LCD, perhaps once every second.
As your tasks are associated with time, consider using the built in Arduino call to millis() to find how many milliseconds the Arduino program has been running.  This will not block your program.  Instead it will immediately return with a number you then need to manage.
To create a delay, use the above number from millis() and add the number of milliseconds for the desired delay.  Call millis() repeatedly until it returns the calculated number or a number greater than the calculated number.  Use this to drive your state machine.  Perhaps you only use millis() to count seconds and use software to count up to 5 hours (5 x 60 x 60 seconds).
Note, millis() will eventually roll over as it is of type "unsigned long".  That is, it will roll over once about every 50 days.  If you want to keep accurate timing when this happens, you will have to account for the roll over in your program.

note: the BlinkWithoutDelay example "accounts for the roll over "

Something along the lines of this pseudocode should help you.
unsigned long weatherUpdate; // Use unsigned longs for millis times
unsigned long screenUpdate;  // You need to worry about wraparound less often
unsigned long timeNow;

setup {

  unsigned int interval1 = 0; // 0 Should be whatever delay you need
  unsigned int interval2 = 0; // 0 Should be whatever delay you need

  updateScreen();
  screenUpdate = millis();

  updateWeather();
  weatherUpdate = millis;

}

loop {

  timeNow = millis();

  /*
     These if statements are true when the interval between the current time
     and the last time the if ran is greater than the required interval. For
     organization purposes, maybe create separate functions for when you
     update your screen and weather functions instead of just replacing
     the function stubs I've included.
  */

  if((timeNow - screenUpdate) > interval1){

    updateScreen();  // Do what you need
    screenUpdate = millis();  // Update time since last run

  }

  if((timeNow - weatherUpdate) > interval2){

    updateWeather();  // Do what you need
    weatherUpdate = millis();  // Update time since last run

  }

}


text:
Not able to receive string from database
A few days ago I posted a thread as I was not being able to send data to my database online. It worked when I changed the GPS module. Now I am trying to retrieve data from the same Server and i'm not being able to do it. The PHP code parses the outputs the data as string and i'm not being able to receive it.
when I visit the URL I am able to see the output on a browser window.
I will Basically get a address which i plan to use substring into 3 lines and display on an 20x4 LCD. is there a better way to go about it?
Thank You!
Arduino Code
#include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <Wire.h>
#include <DS1307new.h>
#include <LiquidCrystal_I2C.h>
#include "LiquidCrystal.h" // For LCD
#include "LiquidCrystal_I2C.h"

#define DEBUG true

TinyGPS gps;

SoftwareSerial sGPS(10,11);

LiquidCrystal_I2C lcd(0x3F,2,1,0,4,5,6,7);  // SET I2C Address

uint16_t startAddr = 0x0000;  //Start address to store in NVRam
uint16_t lastAddr;        //New address to store in NVRam
uint16_t TimeIsSet = 0xaa55;  //Helper that time must not be set again

int currentDay = 0;
int currentMonth = 0;
int currentYear = 0;
int currentHour = 0;
int currentMinute = 0;

float flat, flon;
float previousFLat = 0.0;
float previousFLon = 0.0;

const int buttonPin1 = 2;
const int buttonPin2 = 3;
const int buttonPin3 = 4;
const int buttonPin4 = 5;
const int buttonPin5 = 6;    //call Cluster
const int buttonPin6 = 7;    //call User

const int ledPin1 =  22;
const int ledPin2 =  24;
const int ledPin3 =  26;
const int ledPin4 =  28;

int button1State = 0;
int button2State = 0;
int button3State = 0;
int button4State = 0;
int button5State = 0;
int button6State = 0;

String rcv=""; //Variable in which the server response is recorded.

void setup()
{
  Serial.begin(9600);
  sGPS.begin(9600);
  Serial1.begin(9600);
  lcd.begin(20,4);  // Initialinze LCD.
  lcd.setBacklightPin(3,POSITIVE); // BL, BL_POL
  lcd.setBacklight(HIGH);

  /*
  Control the clock.
  Clock will only be set if NV-RAM Address does not contain 0xaa.
  DS1307 should have a battery backup.
  */

  RTC.getRAM(54, (uint8_t *)&TimeIsSet, sizeof(uint16_t));
  if (TimeIsSet != 0xaa55)
  {
    RTC.stopClock();

    RTC.fillByYMD(2011,4,8);
    RTC.fillByHMS(22,7,0);

    RTC.setTime();
    TimeIsSet = 0xaa55;
    RTC.setRAM(54, (uint8_t *)&TimeIsSet, sizeof(uint16_t));
    RTC.startClock();
  }
  else
  {
    RTC.getTime();
  }

  /*
   Control Register for SQW pin which can be used as an interrupt.
*/
  RTC.ctrl = 0x00;                      // 0x00=disable SQW pin, 0x10=1Hz,
                                        // 0x11=4096Hz, 0x12=8192Hz, 0x13=32768Hz
  RTC.setCTRL();
  delay(5000);

    pinMode(ledPin1, OUTPUT);
    pinMode(buttonPin1, INPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(buttonPin2, INPUT);
    pinMode(ledPin3, OUTPUT);
    pinMode(buttonPin3, INPUT);
    pinMode(ledPin4, OUTPUT);
    pinMode(buttonPin4, INPUT);
    pinMode(buttonPin5, INPUT);
    pinMode(buttonPin6, INPUT);

  }

  void loop()
{
    RTC.getTime();

    currentDay = RTC.day;
    currentMonth = RTC.month;
    currentYear = RTC.year;
    currentHour = RTC.hour;
    currentMinute = RTC.minute;
  String rcv="";

  bool newData = false;

  //For one second we parse GPS data and report some key values

  for (unsigned long start = millis(); millis() - start < 1000;)

  while (Serial1.available())
    {
      char c = Serial1.read();
     //Serial.write(c); // uncomment this line if you want to see the GPS data flowing
      if (gps.encode(c)) // Did a new valid sentence come in?
      newData = true;
    }

  if (newData)
  {
    unsigned long age;
    gps.f_get_position(&flat, &flon, &age);

    if ((flat !=previousFLat)||(flon !=previousFLon))
    {
      previousFLat = flat;
      previousFLon = flon;
      //Serial.print (previousFLat,6)
      //Serial.println(previousFLon,6);
      SendSQL();
      PullSQL();
      startTrip();
    }
  }

}

void waitUntilReponse(int delayMs)
{
// Delay in ms
while (sGPS.available() < 0) { delay(delayMs); } while (sGPS.available() > 0)
{
Serial.write(sGPS.read());
}
}

  void SendSQL()
  {

    Serial.println("Start Send");
    waitUntilReponse(500);

    sGPS.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"\r\n");
    delay(500);
    waitUntilReponse(500);
    sGPS.println("AT+SAPBR=3,1,\"APN\",\"airtelgprs.com\"\r\n");
    delay(500);
    waitUntilReponse(500);
    sGPS.println("AT+SAPBR=1,1\r\n");
    delay(500);
    waitUntilReponse(500);
    sGPS.println("AT+SAPBR=2,1\r\n");
    delay(3000);
    waitUntilReponse(500);
    sGPS.println("AT+HTTPINIT\r\n");
    delay(500);
    waitUntilReponse(500);
    sGPS.println("AT+HTTPINIT=?\r\n");
    delay(500);
    waitUntilReponse(500);
    sGPS.println("AT+HTTPPARA=\"CID\",1\r\n");
    delay(500);
   waitUntilReponse(500);

    sGPS.print("AT+HTTPPARA=\"URL\",\"http://quickshawdic.000webhostapp.com/geta.php?");
    sGPS.print("desig=R001");

     sGPS.print("&addDay=");

     sGPS.print(currentYear);
     sGPS.print("-");

     if (currentMonth < 10) { sGPS.print("0"); sGPS.print(currentMonth); }
      else { sGPS.print(currentMonth); }
      sGPS.print("-");

      if (currentDay <10) { sGPS.print("0"); sGPS.print(currentDay); }
      else { sGPS.print(currentDay); }

      sGPS.print("&addHour=");
      if (currentHour <10) { sGPS.print("0"); sGPS.print(currentHour); }
      else { sGPS.print(currentHour); }
      sGPS.print(":");

        if (currentMinute <10) { sGPS.print("0"); sGPS.print(currentMinute); }
        else { sGPS.print (currentMinute); }

          sGPS.write("&addLati=");
          sGPS.print(previousFLat,6);
          sGPS.write("&addLongti=");
          sGPS.print(previousFLon,6);
          sGPS.println("\"");
          delay(3000);
          waitUntilReponse(500);
          sGPS.write("AT+HTTPACTION=0\r\n");
          delay(15000);
          sGPS.write("AT+HTTPTERM\r\n");
          delay(500);
          sGPS.write("AT+SAPBR=0,1\r\n");
          delay(500);
          waitUntilReponse(500);
          Serial.println("Finish");
        }

void PullSQL()

{
  lcd.clear();
  lcd.home();
  Serial.println("Start Recieve");
    waitUntilReponse(500);

    sGPS.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"\r\n");
    delay(500);
    waitUntilReponse(500);
    sGPS.println("AT+SAPBR=3,1,\"APN\",\"airtelgprs.com\"\r\n");
    delay(500);
    waitUntilReponse(500);
    sGPS.println("AT+SAPBR=1,1\r\n");
    delay(500);
    waitUntilReponse(500);
    sGPS.println("AT+SAPBR=2,1\r\n");
    delay(3000);
    waitUntilReponse(500);
    sGPS.println("AT+HTTPINIT\r\n");
    delay(500);
    waitUntilReponse(500);
    sGPS.println("AT+HTTPINIT=?\r\n");
    delay(500);
    waitUntilReponse(500);
    sGPS.println("AT+HTTPPARA=\"CID\",1\r\n");
    delay(500);
    waitUntilReponse(500);
    sGPS.print("AT+HTTPPARA=\"URL\",\"http://quickshawdic.000webhostapp.com/getr.php?");
    sGPS.print("desig=R001");
    waitUntilReponse(5000);

    String line = sGPS.readString(); //Read the server response line by line..
    rcv+=line; //And store it in rcv.
    Serial.println("Received string: ");
    Serial.print(line);
     delay(3000);
  waitUntilReponse(500);

  sGPS.write("AT+HTTPACTION=0\r\n");
          delay(15000);
          sGPS.write("AT+HTTPTERM\r\n");
          delay(500);
          sGPS.write("AT+SAPBR=0,1\r\n");
          delay(500);
          waitUntilReponse(500);
          Serial.println("Pull Finish");
}

    void startTrip()

    {

      button1State = digitalRead(buttonPin1);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (button1State == HIGH) {
    // turn LED on:
    digitalWrite(ledPin1, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin1, LOW);
  }

    }

PHP Code
<?php

 $dbusername = "username";
    $dbpassword = "password";
    $server = "localhost";

 $dbconnect = mysqli_connect($server, $dbusername, $dbpassword);
    //$dbselect = mysqli_select_db($dbconnect, "request");

 $sql="SELECT user_name FROM id8371368_quickshaw.rides
 WHERE rickshaw_id = '".$_GET["desig"]."'";

 $records=mysqli_query($dbconnect,$sql);
 $string="";

    $row=mysqli_fetch_assoc($records);
 $string=$row["user_name"];
 echo $string;
?>

Try adding newline after sending the URL: sGPS.println("desig=R001");

That's what I did at first, same no output.


text:
Arduino Code 'Bug'
I'm sharing my code.. The problem I am facing is that the code performs all the functions that are to be called except showing the MAX30100 (for heart rate) readings. I have tried this code using statement switches,cases, if-else but couldn't figure out.  Can anyone help me out regarding this?
    unsigned long runGSR() {

total = total - readings[index];         // subtract the last reading:

 readings[index] = analogRead(inputPin);  // read from the sensor:

  delay(100);

  total = total + readings[index];       // add the reading to the total:

  index = index + 1;                     // advance to the next position in the

array:

  if (index >= numReadings)               //when the end of the array is reached

    index = 0;                           // wrapped around to the beginning:

  average = total / numReadings;           // calculate the average:

  return average;       // send it to the computer as ASCII digits

    }
    void ambtemp()

    {

       reading = analogRead(A2);       //takes the reading from analogue pin 2

  tempVolts = reading * 5.0 / 1024.0;   //converts the readings to volts

  ambitemp = tempVolts / 0.01;        //output voltage /10 millivolts = 1 degree
C

  Serial.print(",Ambient Temp:");      //prints ambient temperature in serial monitor

  Serial.println(ambitemp);

  delay(10);

    }

    void hbt()    //Function for heart rate (MAX30100) in which I am having problem
    {
        do
        {
            pox.update(); // Make sure to call update as fast as possible
            if (millis() - tsLastReport > REPORTING_PERIOD_MS) {   //the loop repeats every second
            lcd.clear();
            Serial.print("HR:");
            Serial.println(pox.getHeartRate()); //prints Heart rate on LCD
            delay(100);
            ambtemp();    //calls the ambient temperature function
            gsr = runGSR();   //calls the GSR sensor function
            delay(100);
            tsLastReport = millis();
        }

You have two missing } Add them then use ctrl+t in ArduinoIDE to automatically format your code and then paste it again please. (Please use "code" function of the stackexchange editor to add code as code)

I try it but it doesn't work.

Any other solution... there is some kind of bug that is not plotting the readings of MAX30100

What I meant was "Show us your complete code in a way that we can run it on our Arduino simulators" Right now the code you pasted in the question does not compile. No one can help you right now. (You can Edit the question and change the code to the complete one)

Serial.println(pox.getHeartRate()); //prints Heart rate on LCD .... the comment does not match the command

When you say "I try it but it doesn't work" we understand the result but it isn't enough for us to help you.  For example, do you get partial output? If you try lcd.print("HR:"); do you see that on the LCD? If not, then your hbt() function is never being called because there is no branching inside the function to keep that link from executing. We can't see enough of your code you be any more assistance.  Where did you get the sample you are using, what libraries are you importing, etc. Also, it looks like that 'DO' block has no WHILE / UNTIL  visible, is it an infinite loop?

I see the result "HR:" printed on lcd but it doesn't print the value of the sensor that should be 60-100 bpm. I have mentioned the main part of code and have already included required library needed for the code. What kind of error it can be that calls hbt function but does print its value?

I assume you use this as source for your code:
This means that:
#include "MAX30100_PulseOximeter.h"
PulseOximeter pox;

Your issue is that the line:
Serial.println(pox.getHeartRate()); //prints Heart rate on LCD

Does not actually print anything on the LCD.
It only shows the value on the serial.
Try using lcd.print()

No, its  neither print value on lcd nor on serial ide.

Paste your entire code in the question please.

Done. check now please

There are many many errors in your code. According to StackExchange rules you should provide a Minimal, Complete, and Verifiable example https://stackoverflow.com/help/mcve that allows other people check for solution to your problem. Your example still does not compile and I can't test it.


text:
Connecting NodeMCU through internet
I have a NodeMCU and a website (free website domain provided by http://www.hpage.com) and I have to send and receive some data (suppose a 8bit number) from the website to the NodeMCU via internet. The NodeMCU is connected to internet through WiFi hotspot of an Android phone.

Can anyone provide an example code? How can I address the NodeMCU from the website?
Does the NodeMCU need to be a server or just a client?

Thanks in advance for kind help.

How can I address the NodeMCU from the website?

You can't. The NodeMcu is behind the phone, behind a router, behind a gateway of the operator etc. It can access the Internet over the infrastructure routing it out, but is not visible from the Internet.

Does the NodeMCU need to be a server or just a client?

The device should be a client and open the communication to the server by sending a request and renewing the connection if it times out. You can use WebSockets or MQTT or similar framework.

Well, I have seen people address devices connected to router by the name of service port. Isn't it possible for Android? Some apps use this service port address to share data over wifi. Anyway, thanks for mentioning. I'll try MQTT.

to setup port forwarding  you must have a public IP address and control over router/gateaway. other option is to use a VPN set on a server in Internet

@Shounak, did the answer help?


text:
Control Stepper via Serial Monitor
I would like to control my stepper via serial monitor and unfortunatley the code below did not work. Serial monitor works (Serial.println()), but it does not execute the stepperOne() part. Any ideas why would be awesome.
Thank you.
#include <AccelStepper.h>

const int stepPin = 5;
const int dirPin = 4;
const int enPin = 12;

String msg;

unsigned int DEST = 800;
unsigned int SPD = 1600;
unsigned int ACCEL = 1600;
const int TEST = 3;

void setup() {

  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,HIGH);
  Serial.begin(9600);  // Start Serial

}

void loop() {

if (Serial.available()>0) {
    msg = "";
    while (Serial.available()) {
      delay(10);
      char tmp = Serial.read();
      // msg += tmp;
     if( tmp!='\r' && tmp!='\n' ) msg+=tmp; // Does not work either
    }
    msg.replace(" ","");
    if (msg=="G") {
      stepperOne();
      Serial.println("Stepper turned.");
    }
    Serial.flush();
  }
}

void stepperOne() {

  AccelStepper stepper(1,stepPin,dirPin);
  digitalWrite(enPin,LOW);
  stepper.setMaxSpeed(SPD);
  stepper.setAcceleration(ACCEL);
  stepper.move(DEST);
  if (DEST > 0) {
    while ( stepper.distanceToGo() > 0 ) {
      stepper.run();
      }
  digitalWrite(enPin,HIGH);
  }
 }

It you type "G" in the serial console, it will send "G\r\n" (with an "enter" at the end). Your code doesn't account for the carriage return and newline at the end.

How can I account for carriage return ?

You could opt to ignore it. if( tmp!='\r' && tmp!='\n' ) msg+=tmp;

Thanks. I added it in the code (see above) and it still does not work. Serial works though. I am confused.

Stupid question can the Arduino version (older Uno) be the reason for this ? Or am I missing something ? Thanks

does the stepper work without the Serial code?

The serial.println works so I guess the Serial port works.

I found the solution, it was the Arduino, older version R2, the R3 works like a charm. I didn't know that the version could cause so much trouble. Sorry.

Write this as an answer!

I found the solution, it was the Arduino, older version R2, the R3 works like a charm. I didn't know that the version could cause so much trouble. But in case someone encounters the same problem R3 did it for me.


text:
DFPlayer for Writing to SD Card
Can you use the DFPlayer to write to the SD card?
Link for DFPlayer: https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299
Here's the goal of my project. I have a button that, when pressed, should a- play a song off an SD card that is hooked up to the DFPlayer and b- should log "button is pressed" to the SD card. Unfortunately, the DFPlayer library doesn't seem to have any functions for this, and I wasn't sure how to see whether the DFPlayer has the functionality to support writing onto an SD card. Are there modules that are Read-only for SD cards? If so, is the DFPlayer one of them?
PS - I'm using an Arduino Uno,
Thank you so much for your help! I am a complete novice for SD cards, so any help you give would be very much appreciated!

In short: no. The clue is in the name: "DFPlayer". It's a player. That's all it is.

whats wrong with the standard Arduino SD library? It should be able to read and write from an SD card

@esoterik, not on the DFPlayer board

why not use a second SD card? use the standard SD library with another card reader.

Thanks @Majenko, esoterik, and Juraj! I wanted to avoid buying a second sd card and reader if possible and use the DFPlayer to store information to the SD cars, but if that's not possible like you all are saying, I will go ahead and buy a new one. Thanks!

Unfortunately the DFPlayer cant write that data to the SD card. The Arduino has some non volatile memory of its own built in though. Theres 1K of EEPROM for the UNO. Notes on how to use it here: https://www.arduino.cc/en/Reference/EEPROM
If you can get what you need to done in 1K and its not important to your project that you be able to unplug the SD card and put it in another reader, then perhaps thats a nice, simple solution...


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

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

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

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

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

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

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

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

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

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

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

void setup() {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Cut-and-Paste programming?

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

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

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

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

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

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

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

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

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

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

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

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

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


text:
How to convert a delimited string of hex numbers to an int array
I am sending a string to the Arduino via serial, I made the program that sends the data, so I can change it to anything, but for now it sends a string of hex numbers delimited by ':', so for example 00:AA:FF and I need to get that into an int array onto the Arduino, the main problem is I don't always know how big the array will be, sometimes just 2 indexes, other times 16 indexes.
As I said, I made the program sending the data so I can make the data anything, I just need to get an int array to the Arduino and get it back as an int array via serial

is this a school assignment?

Do you know an upper limit on how many there will be?

You could store the hex numbers in a int array using strtok() and strtol().
char str[] = "00:AA:FF:7FFF";
int intArray[16]; // Maximum number of hex numbers.

void setup(){

  Serial.begin(9600);

  int counter = 0;
  char * pch = strtok(str, ":");

  while(pch != NULL){
    intArray[counter] = strtol(pch, NULL, 16);
    pch = strtok(NULL, ":");
    counter++;
  }
  Serial.print("Item Count = ");
  Serial.println(counter);

  for(int i = 0; i < counter; i++){
    Serial.println(intArray[i]);
  }

}

void loop(){}


text:
Emit region-neutral keyboard signals
The Keyboard API allows the Arduino boards such as the Micro or Leonardo to emit USB signals mimicking a physical keyboard. However, the signal seems to transmit key strokes and not characters which means that machines with different region settings interpret the USB signal differently. For example, a y will be interpreted as z in a German OS since the keyboard layout has these keys swapped.
Is there any way to output a signal that will result in the correct character being transmitted regardless of the OS settings without any modifications to the machine the Arduino is attached to?

@jsotola AFAIK most keyboards send the pressed physical key and not the character represented by that key. However I have heard about attempts to allow a keyboard to specify its layout and haven't found any further resources on this.

stumbled across this today ........ https://github.com/NicoHood/HID/blob/master/src/HID-Settings.h

No. There is no such facility.
If you take a German keyboard and plug it into a US configured computer the key layout will be wrong. You have to tell the computer that you're using a German keyboard.
Keyboards don't know what is printed on the keycaps. All they understand is where the buttons are physically located.
The same with the Arduino. It's sending the keypresses that correspond to the keyboard layout of a US keyboard, and you have to tell the computer that you're using a US keyboard - because that is effectively what you are using.
If you want to change the keyboard map the Arduino uses you will have to manually modify the Keyboard library (file Keyboard.cpp, array _asciimap[128]).

Download Device Class Definition for Human Interface Devices (HID)
https://www.usb.org/sites/default/files/documents/hid1_11.pdf
See section 6.2.1 HID Descriptor
bCountryCode 0x09 German
also see section E.4 (page 67)
E.4 HID Descriptor (Keyboard)
Part            Offset/Size  Description                                         Sample
                (Bytes)                                                          Value
----------------------------------------------------------------------------------------
bLength           0/1        Size of this descriptor in bytes.                    0x09
bDescriptorType   1/1        HID descriptor type (assigned by USB).               0x21
bcdHID            2/2        HID Class Specification release number
                             in binarycoded decimal—for example, 2.10 is 0x210).  0x101
bCountryCode      4/1        Hardware target country.                             0x00
bNumDescriptors   5/1        Number of HID class descriptors to follow.           0x01
bDescriptorType   6/1        Report descriptor type.                              0x22
wDescriptorLength 7/2        Total length of Report descriptor.                   0x3F

That field is ignored by all operating systems. It was intended to be used, but no one does. Keyboard manufacturers didn't want to have to create separate controllers for each and every language of keyboard - it is so much cheaper to just have one and change what's printed on the keyboard. Also I know of no operating system that can apply keymaps to individual inputs - it's only set on the user session as an entirety. All inputs are amalgamated first and then mapped from key codes to characters afterwards.