body:
Update 2:
Have tested by pinging various devices on different subnets / vlans
and did a pcap on the wifi AP

I can see the icmp requests going through for each request except for ones on the 4.x subnet, almost like the arduino doesnt like that IP address and refuses to send those packets?

Update 1:

Have tested the following

Turned on logging on firewall and noticed the following actions:

 - Ping router from Arduino - See logs in firewall, arduino gets response. (Red line)

 - Send external web request from arduino - See logs in firewall, arduino gets response. (Orange Line)

 - Send web request to internal server - Arduino queries internal DNS and gets IP of web server, but no request send (Nothing in firewall logs) (Yellow and Blue)

 - Send ping to internal server - Arduino queries same dns server, gets ip, but no request sent (Firewall logs again) (Yellow and Green)

however, sending the ping and web request from desktop, shows both the firewall log blocking the ping request, and the rule allowing the web request.(Brown Purple Pink)

Have attached diagram again to help visualize whats going onAnd can attach router logs or rules if required

https://imgur.com/a/g4TipmZ

Also have set a windows PC with the same IP address, and can ping the web server, so I know it's something wrong with the arduino's requests to the web server in particular, and not the firewall?
###End Update###

I have two Node MCUs which I'm using for a project.
A while ago they were working fine, but i recently changed some network settings on my home network and found that it broke the script I had running on them.
I finally figured out where it went wrong and fixed it, but now I have another interesting problem.

One of my nodes runs this script fine, where as the other gets stuck on the ping stage.
I have uploaded the same script to both nodes and swapped over the IP address assigned and it follows the device not the IP.
So I know its not a networking issue.

I know the WiFi is working on the funny node, as it gets a IP address.
but it doesn't go any further

Any ideas?

Script attached below:

        #include <DHT.h>
        #include <ESP8266WiFi.h>
        #include <ESP8266HTTPClient.h>
        #include <ESP8266Ping.h>

        // WiFi credentials.
        const char* WIFI_SSID = "SSID";
        const char* WIFI_PASS = "******";
        WiFiClientSecure wifiClient;
        bool connection = false;
        WiFiClient client;
        const char* dbServer = "webaddress";

        void setup() {
          //Open Serial
          Serial.begin(9600);
          Serial.setTimeout(2000);

        //Connect to Wifi
          bool pingtest = false;
          Serial.print("Connecting to WiFi");
          WiFi.begin(WIFI_SSID, WIFI_PASS);
          //Wait for connection
          int wificount = 0;
          while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(".");
          }
          if (WiFi.status() == WL_CONNECTED) {
            connection = true;
            Serial.println("WiFi connected");
            Serial.println("IP address: ");
            Serial.println(WiFi.localIP());
            while(!pingtest){
              Serial.println("Pinging Server");
              if(Ping.ping(dbServer) == true){
                pingtest = true;
              }else{
                Serial.print(".");
                delay(1000);
              }
            }
          }

        }

    void loop() {
      Serial.println("Hello");
      delay(2000);
    }

Update (Cross posted from another forum):
I have an Arduino which pings a server on a different VLAN / subnet as part of its code.
It was working a while ago, but I changed some settings on my firewall to restrict stuff down, and that broke the Arduino code.
I found it was because I was blocking ICMP across VLANs.
So I created a rule to allow ping requests between the two VLANs
tested on my desktop (on same net as Arduino) and works fine.
Went to test on Arduino and wasn't getting any response.

So I put the router IP in and tested it on the Arduino, works fine. I can even ping the Arduino from my desktop, and ping my desktop from the Arduino

So I figured I must have some other firewall rule allowing my desktop to have special access. (not that I could find it)
so gave the arduino the same Ip address and no luck, yet can still ping the router

I have attached a crude drawing here. Hopefully it helps to visualize my problem.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/zTwb2.png

title: NodeMCU Ping working on one but not another

Answers: 1

body:
If a ping doesn't work over a routed connection it could be.

1. Default gateway on the Arduino device, add a `Serial.println(WiFi.gatewayIP().toString());` to print the default gateway.

2. DNS issue, I presume that the `const char* dbServer = "webaddress";` indicate a FQDN.

3. Firewall is blocking the ICMP on either the inbound or outbound path.


body:
I'm using an Arduno UNO WiFi Rev 2 and trying to connect to a database, but it does not connect nor shows any errors.

The arduino connects successfully to WiFi and pinging google works fine.
But when I add the part to connect to database, on line: 65, the script just stops at "DB Connecting..." on the line above.

Inside Arduino IDE you can see a difference between the includes, the MySQL ones are not luminated:
https://i.stack.imgur.com/ERD0N.png

This is how the code looks like:

    #include <SPI.h>
    #include <WiFiNINA.h>
    #include <MySQL_Connection.h>
    #include <MySQL_Cursor.h>

    // MySQL Information
    IPAddress server_addr(111,222,333,4);
    char user[] = "arduino"; // MySql username
    char password[] = "qwerty"; // MySql password

    WiFiClient client;
    MySQL_Connection conn((Client *)&client);

    // WiFi Information
    char ssid[] = "Router-SSID";        // your network SSID (name)
    char pass[] = "router-pw";    // your network password (use for WPA, or use as key for WEP)
    int status = WL_IDLE_STATUS;     // the WiFi radio's status

    // Specify IP address or hostname
    String hostName = "www.google.com";
    int pingResult;
    int pingWorks = 0;

    void setup() {
      pinMode(hallPin, INPUT);
      pinMode(LED, OUTPUT);

      Serial.begin(115200);

      // check for the WiFi module:
      if (WiFi.status() == WL_NO_MODULE) {
        Serial.println("Communication with WiFi module failed!");
        // don't continue
        while (true);
      }

      String fv = WiFi.firmwareVersion();
      if (fv < "1.0.0") {
        Serial.println("Please upgrade the firmware");
      }

      // attempt to connect to WiFi network:
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network:
        status = WiFi.begin(ssid, pass);

        // wait 5 seconds for connection:
        delay(5000);
      }

      // you're connected now, so print out the data:
      Serial.println("You're connected to the network");

      printCurrentNet();
      printWiFiData();

      delay(2000);
      Serial.println(server_addr);
      Serial.println(user);
      Serial.println(password);
      // Connected to the WiFi lets continue..
      Serial.println("DB - Connecting...");
      if (conn.connect(server_addr, 3306, user, password)) {
        delay(500);
        Serial.print ( "." );
      } else {
        Serial.println("Failed to connect..");
      }
      Serial.println("Connected.");
    }

    void loop() {
      runWifi();
    }

    void runWifi() {
      if (pingWorks == 0) {
        Serial.print("Pinging ");
        Serial.print(hostName);
        Serial.print(": ");

        pingResult = WiFi.ping(hostName);

        if (pingResult >= 0) {
          Serial.print("SUCCESS! RTT = ");
          Serial.print(pingResult);
          Serial.println(" ms");
          pingWorks = 1;
        } else {
          Serial.print("FAILED! Error code: ");
          Serial.println(pingResult);
          pingWorks = 2;
        }
      } else {
        Serial.println("Ping on google works..");
      }
      delay(200);
    }

    void printWiFiData() {
      // print your board's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print("IP address : ");
      Serial.println(ip);

      Serial.print("Subnet mask: ");
      Serial.println((IPAddress)WiFi.subnetMask());

      Serial.print("Gateway IP : ");
      Serial.println((IPAddress)WiFi.gatewayIP());

      // print your MAC address:
      byte mac[6];
      WiFi.macAddress(mac);
      Serial.print("MAC address: ");
      printMacAddress(mac);
    }

    void printCurrentNet() {
      // print the SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print the MAC address of the router you're attached to:
      byte bssid[6];
      WiFi.BSSID(bssid);
      Serial.print("BSSID: ");
      printMacAddress(bssid);
      // print the received signal strength:
      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI): ");
      Serial.println(rssi);

      // print the encryption type:
      byte encryption = WiFi.encryptionType();
      Serial.print("Encryption Type: ");
      Serial.println(encryption, HEX);
      Serial.println();
    }

    void printMacAddress(byte mac[]) {
      for (int i = 5; i >= 0; i--) {
        if (mac[i] < 16) {
          Serial.print("0");
        }
        Serial.print(mac[i], HEX);
        if (i > 0) {
          Serial.print(":");
        }
      }
      Serial.println();
    }

What can be the problem?
No working libs for WiFi uno rev 2?

title: Arduino UNO WIFI Rev 2 - MySQL trouble

Answers: 0


body:
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

title: Arduino library redeclaration error

Answers: 2

body:
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!

body:
**FINAL EDIT WITH SOLUTION:**

I finally stumbled upon the last wall of issues before getting it to work,

 1. I redownloaded all the libraries
 2. Went to the .h library file of RTClib
 3. Changed the variable names from OFF to OFF and on to ONN (it's stupid I know but bear with me)
 4. 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.

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


body:
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.

title: How do I fill an empty array with the values from a sensor and compare it to another given array I filled before

Answers: 2

body:
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.

body:
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;
    }


body:
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.

title: how do i fill an array from a grayscale sensor (SKU:SEN0147)?

Answers: 0


body:
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);
    }
    }

title: Does baud rate for HC-05 Bluetooth module need to match the Serial Monitor?

Answers: 1

body:
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.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/eD45v.png)

<!-- End schematic -->


body:
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);
    }

title: I need a random code for Arduino Uno to trigger a single relay

Answers: 0


body:
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!

title: Creating an array of structures which store bitmaps to work with u8glib

Answers: 2

body:
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.

body:
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() );
    }


body:
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?

title: Weird problem with arduino

Answers: 1

body:
If you want to get a value from PROGMEM you must read it with `pgm_read` functions. Read the [PROGMEM reference][1].

    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`

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


body:
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);
    }

title: Combining sketches

Answers: 0


body:
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?

title: Prints to the serial monitor are being overwritten

Answers: 0


body:
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.

 1. How to Select CT for my application based on Current measurement range
 2. How Burden resistor calculated.
 3. How Size of CT can be calculated.
 4. How to judge max supply voltage supplied to Arduino
 5. Type of CT to be used protection class CT or Normal CT
 6. 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.
 7. How burden VA calculated here.

I have researched and got one of application where they using AC [AC1030 datasheet][1]

<!-- language: none -->

    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?

[![Application CKt][2]][2]
[![Current _range & Motor Range][3]][3]

  [1]: https://www.promelec.ru/pdf/AC-1030_Jun-06.pdf
  [2]: https://i.stack.imgur.com/V8Zuz.png
  [3]: https://i.stack.imgur.com/TJHf0.png

title: Selection of External CT for my application

Answers: 0


body:
I have a circuit connected as follows
[![enter image description here][1]][1]

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

  [1]: https://i.stack.imgur.com/TpQWt.png

```
//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
    }
  }
}

```

title: Is this a good way to filter noise due to vibration in limit switch?

Answers: 1

body:
**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.


body: 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.

title: How to perform two tasks in one loop in Arduino?

Answers: 2

body:
Consider using a [finite state machine][1] 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()][2] 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.

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine
  [2]: https://www.arduino.cc/reference/en/language/functions/time/millis/

body:
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

  }

}
```


body:
A few days ago I posted a [thread][1] 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][2] 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;
    ?>

[![Arduino Serial Output][3]][3]

  [1]: https://arduino.stackexchange.com/questions/60056/code-getting-stuck-waiting-for-gps-output
  [2]: http://quickshawdic.000webhostapp.com/getr.php?desig=R001
  [3]: https://i.stack.imgur.com/8FvYJ.jpg

title: Not able to receive string from database

Answers: 0


body:
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();
            }

title: Arduino Code 'Bug'

Answers: 1

body:
I assume you use [this][1] 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()`][2]

  [1]: https://github.com/oxullo/Arduino-MAX30100/blob/master/examples/MAX30100_Debug/MAX30100_Debug.ino
  [2]: https://www.arduino.cc/en/Reference/LiquidCrystalPrint


body:
I have a NodeMCU and a website (free website domain provided by [http://www.hpage.com][1]) 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.

  [1]: http://www.hpage.com

title: Connecting NodeMCU through internet

Answers: 1

body:
> 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.


body:
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);
      }
     }

title: Control Stepper via Serial Monitor

Answers: 1

body: 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.


body:
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!

title: DFPlayer for Writing to SD Card

Answers: 1

body:
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...


body:
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);
           }
    }

title: Proper use of the tone() function within the loop () function

Answers: 1

body:
First off
==

Even if compiled your code will not work; in [the tone function reference][1] 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

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/


body:
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

title: How to convert a delimited string of hex numbers to an int array

Answers: 1

body:
You could store the hex numbers in a `int array` using [strtok()][1] and [strtol()][2].

  [1]: http://www.cplusplus.com/reference/cstring/strtok/
  [2]: http://www.cplusplus.com/reference/cstdlib/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(){}


body:
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*?

title: Emit region-neutral keyboard signals

Answers: 2

body:
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]`).

body:
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