text:
Two ports on Uno with ethernet shield
I am making an Arduino mod-bus device and I want to make a webpage as well that will allow me to reset the unit if there is any issues remotely. To do this I would need the mod-bus to operate on port 502 and the webpage to operate on port 80. is it possible for the Arduino to support two ports? I am using an Uno with a Ethernet shield and the standard ehternet.h file with a Modbus library. Any suggestions or ideas?
 #include SPI.h
 #include VL53L0X.h
 #include Ethernet.h
 #include Modbus.h
 #include ModbusIP.h
 #include VL53L0X.h
 #include Wire.h

VL53L0X sensor;
EthernetServer server(80);

//Modbus Registers Offsets (0-9999)
const int SENSOR_Hreg0 = 100;

//ModbusIP object
ModbusIP mb;

short ts;

void setup() {
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  byte ip[] = { 192, 168, 1, 177 };

  Wire.begin();
  mb.config(mac, ip);

  // Add SENSOR_Ireg register - Use addIreg() for analog Inputs
  mb.addHreg(SENSOR_Hreg0);

  ts = millis();

  //Sensor setup
  sensor.init();
  sensor.setTimeout(500);
  sensor.startContinuous();

  //remote reset
    pinMode(13, INPUT);
    digitalWrite(13, LOW);

   // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Ethernet WebServer Example");

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  // start the server
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

}

void loop() {

  mb.task();

    //Webpage
    // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    bool currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          // output the value of each analog input pin

            client.print("Distance Measures ");
            client.print(sensor.readRangeContinuousMillimeters());
            client.print("mm");
            client.println("
");
            client.print("Filter Count:");
            client.print(-2.2*sensor.readRangeContinuousMillimeters()+404);
            client.println("
");
          }
          client.println("");
          break;
        }

      }

  //Modbus
  if (millis() > ts + 100) {
    ts = millis();

     mb.Hreg(SENSOR_Hreg0, sensor.readRangeContinuousMillimeters() );

     }
}}

Edit:
Note: The issue seems to lie somewhere in with the sensor, because when I run it with out have the sensor code in there is no problem but when I add it the issue starts again.

to test, run two instances of a web server ... one on port 80 and one on port 502 .... access the webpage using two devices so that you are serving a page to two different devices at the same time .... if that works, then try adding some modbus test code (if such a thing exists) instead of a webserver on port 502

I tried that and it didn't take the ip address for the webpage but took it for the modbus, and when I added a second instance of the ip to see that would work it errored out.

EthernetServer has nothing to do with IP. Servers should  run on a different ports on the same IP.

try to print the IP before server.begin()

Same result when I moved the Serial.print("server is at ");
Serial.println(Ethernet.localIP()); before the server.begin()

I don't have the sensor, but the rest of the sketch works.

move the modbus refresh out of the if (client) condition
mb.begin() calls Ethernet.begin(). Do not repeat it in setup()
move client.println(""); break; inside the if block before it
copy the rest of the detection of empty line from the WebServer example
stop() the client after response
change type of ts to unsigned long

I've added to code I am using, I have port 80 assigned and the modbus library sets a port 502 for the modbus. When I use this I can ping the device but Modbus and web communication is not there.

When i check the serial monitor, I planned to remove it once this was working, it reports the IP address as 0.0.0.0

but it is not the IP address of the EthernetServer, it is the IP of the shield. the ip is reported wrong or the shield did not connect. try to connect with DHCP.

when I comment out all the webpage parts it works fine, and I can even ping the device with the code in using the set ip.

I removed Ethernet.begin() and tried it out and it still didn't work, I can still ping the device but getting Modbus data or the webpage still doesn't work.

Let us continue this discussion in chat.


text:
Websockets with the ESP8266 using arduino uno board
I'm trying to make an iot device that connects to my wifi, establishes a socket connection with my golang backend and then starts to send sensor data from the ardunio.
I've got an ardunio uno board and this ESP8266:

I found this websockets library but I don't know if I can import the .h files if I have "arduino uno" selected in the IDE
My question:
Is it possible to establish a WebSocket connection with my go backend using the esp model that I have? If so, how can I import the required libraries in the arduno IDE? I would be happy if you could give me some directions.

can you communicate with the AT firmware on the module?

The library you linked is not for Uno with esp8266 module.
It is possible to use the ESP-01 with Uno for WebSockets client for example with ArduinoHttpClient library over the WiFiEsp library.
Better option is to use only an esp8266 development board programmed with Arduino IDE without the Uno.

source: Stack Exchange

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

sort: votes


text:
ESP8266 Peer to Peer with AP and STA - Cache AP Clients, Flush Their Requests?
I'm fairly inexperienced with Arduino and entirely new to networking, so bear with me.
I've programmed a couple of NodeMCU devices to communicate the use of an instrument via activation of an LED. I have one set up as an access point and another as a client. I roughly followed the second answer from this question to set mine  up. I'll eventually shift this particular project to mqtt but I'd like to understand how to get the direct peer-to-peer working for other projects as well.
While it is partially working, I am having a couple issues that I assume are related to networking.
1. After plugging in the client ESP8266, the server only recognizes it for two loops (taking ~5 seconds each), then I have to restart the client, which is discovered instantaneously by the server.
2.  After the client connects, if I press the pushbutton on the client - while recognized - only once, the "toggle" command is repeatedly sent, resulting in the LED blinking for a handful of loops until it stops and the client has to be restarted again.
2.1. If I comment out the button debounce on the client, this happens more reliably. With debounce on, if I click the button immediately upon the first "client found!" message, the LED will typically toggle on the second (final) loop. Subsequent presses changing nothing.
Server sketch:
// Particle counter use server
// Place outside with LED

// load libraries
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

// Set up variables
#define use_LED   D2

const char* ssid = "esp_server";
const char* password = "password";

WiFiServer server(80); // set port to 80

int toggle = 0;
String request = "";

void setup() {
  Serial.begin(9600);
  pinMode(use_LED, OUTPUT);

  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);
  digitalWrite(use_LED, HIGH);
  delay(1000);
  Serial.println(WiFi.softAPIP());

  digitalWrite(use_LED, LOW);

  server.begin();
}

void loop() {
  // Check for a client
  WiFiClient client = server.available();
  if (client) {
  // Wait until client is connected
//  while(!client.available()) { delay(1); }/
  Serial.println("client found!");

  // Parse commands
  String request = client.readString();
  Serial.println(request);

  // After pressing client switch once, this dances between on and off with every loop
  if (request == "toggle") {
    toggle = 1 - toggle; // switches to opposite on request reception
    digitalWrite(use_LED, toggle);
    delay(2000);
  }

  client.flush();
  }

}

Client sketch
// Particle counter use client
// Place in analysis room with button

#include <ESP8266WiFi.h>
#include <WiFiClient.h>

#define toggle_button D1 // make sure to use a pulldown resistor

int toggled = 0;

// Set up connection to server ESP
const char* ssid = "esp_server";    // ssid of server
const char* password = "password";  // password of server
const int port = 80;                // port of server

byte ip[] = {192,168,4,1};

WiFiClient client;

void setup() {
  Serial.begin(9600);
  pinMode(toggle_button, INPUT);
  Serial.println("active");

  WiFi.mode(WIFI_STA); // Setup as client
  WiFi.begin(ssid, password); // Connect to server ESP
}

void loop() {
  toggled = digitalRead(toggle_button);

  if (client.connect(ip, port)) { Serial.println("CONNECTED"); }

  if (toggled == HIGH) {
    // send command to toggle LED when button is pressed
    Serial.println("triggered");
    client.print("toggle");
  }

  client.flush();
}

Strangely, the slow recognition is only on the server side, the client spams its serial output with "CONNECTED", until stopping (I assume when the second loop completes on the server side, I can only monitor the serial of one at a time). But once found the following lines suggesting a WiFi or memory error in the output nestled among all the lines of "CONNECTED":
Exception (29):
epc1=0x40202a8f epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

ctx: cont
sp: 3ffefa30 end: 3ffefc40 offset: 01a0

>>>stack>>>
3ffefbd0:  3ffe8b70 3ffee9b0 3ffeebe4 40202a8d
3ffefbe0:  0104a8c0 00000000 3ffeebe4 4020328c
3ffefbf0:  00000000 3ffee9b4 3ffeebe4 3ffeec10
3ffefc00:  3fffdad0 3ffee9b0 3ffee998 40202107
3ffefc10:  401070a0 0104a8c0 00000001 40203519
3ffefc20:  3fffdad0 00000000 3ffeec08 40203544
3ffefc30:  feefeffe feefeffe 3ffeec20 40100710
<<<stack<<<

I have pulldown resistors on both the client switch and the server LED, I'm guessing that client.flush() does not clear the command? I'm baffled as to why the loop on the server only runs twice before I have to reset the client, and why upon resetting the client is instantly recognized, but takes so long to see it again. Does anyone have any advice?

You connect() and do not stop() the client. You get out of the 5 connections limit.
Use client in if (client.connect(...)), print and then do client.stop().
And also stop() the server's client object.
readString has one second timeout. you should send a delimiter and use readStringUntil
Edit: For permanent connection of multiple clients on server side see the WiFiTelnetToSerial example. At client side you can use one global client object. But check if it is connected and if not, call stop and then connect again.
void loop() {

    if (!client.connected()) {
      client.stop();
      if (!client.connect(ip, port)) {
        delay(1000);
        return;
      }
    }

    int toggled = digitalRead(toggle_button);

    if (toggled == HIGH) {
      // send command to toggle LED when button is pressed
      Serial.println("triggered");
      client.print("toggle.");
    }
}

Thanks, that solved the 2 loop problem!   Now I've got new client side issues, after sending the toggle once, I can't send it again without resetting the client esp; is there a way to maintain the connection as open?

do you stop the client on server side?

for permanent connection on server side see the WiFiTelnetToSerial example. at client side you can use one global client object. but check if it is connected and if not, call stop and then connect again

Yes, I stop on the server side. Client side I refactored to loop() {if (client.connect(...)) { while (client.connected()) { if(toggled) client.flush() } client.stop() } which solved all issues except it dumps a Soft WDT reset error every few seconds. I looked up the example, thanks!

remove flush() and while (connected()). do you use the latest release of esp8266 arduino core package? (2.4.2)

Removing the while(connected()) portion brings back the single-use issue. As for the library, after updating in the library manager, it shows it's version 1.0.0

Library Manager? this is a board package

make WiFiClient client global and use the loop() as loop

Ah, I'm on 2.4.1, just updated, it did not solve the client side error. WiFiClient client is global, and I am using loop() for the loop as far as I can tell.

2.4.1 had bugs.

I added client's loop to answer

Fantastic,  no more error, I must've been exceeding memory by trying to make a connection every time. Thanks a lot for all the help!

2.4.1 had a memory leak with reusing the WiFiClient object

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


text:
ADC noise when sharing ground from external supplies
i have resistor based sensor, when i test it using arduino connect to PC using serial monitor  without sharing ground to other circuit it has a nice value between 300-650 in adc range and the error/ accuracy reading just have about 5 value (ex: 607-612) if there is no condition change in the sensor.
But the problem comes when i sharing the ground to the other circuit. The accuracy is messed up bigger than 60 adc value (570-660) with the same condition without sharing ground.
My circuit is powered by PSU 24V and 24V driver to produce input signal for electric pressure regulator. The arduino ground is sharing because to control the input of the 24V driver. Here my circuit in the attachment.
So there is two ground from PC (i need it to use serial monitor) and the PSU 24V
How to eliminate the noise? Is there any way to control the 24v driver and read the sensor at the same time without sharing ground? Maybe using two controller with master/slave? Or there is any advice?

You could use an opto-coupler between the arduino and driver. Then you don't need to have a common ground. I'd also try putting a 1-10kOhm resistor between the arduino output and driver input.

What you have shown in the schematic is insufficient in determining your problem and a possible fix. What needs to be seen is exactly where are the wires are run to and from. The exact routing of the wires. And a schematic does not show that.

Can you tell me what Arduino board you are using? Uno, Nano, etc. And what sensor.

I had the same problem with communication between a Rasberry Pi and an Arduino Mega.  Ultimately I solved the problem by powering the Pi from the Mega.  You may need to separate the power and communication lines to the PC.

Thanks @Gerben i solved my problem by using an optocoupler. Before My arduino UNO PWM output go through PWM driver, I separate this line using Optocoupler so the ground from power supply doesn't contact to my controller that preventing from ground loop.

You've created what's known as a "Ground Loop".  You have 2 grounds in your circuit, your 24v PS has a ground and the PC supplying 5V to your Arduino has a ground.  They are not likely to be equivalent and will cause many unwanted side effects.
You can reduce some noise using RC or RLC circuits on your power supply pins.  It's probably best to use only a single power supply (and ground).

"You can reduce some noise using RC or RLC circuits on your power supply pins." How will this eliminate the ground loop?


text:
Having some issues with an array
I am having an issue that I can't seem to get my head wrapped around.  What I am trying to accomplish is to have a minutes worth of sensor data in an array (reading every 5 seconds) so I'll have 12 values in this after one minute.
I want to keep the array to 12 values so I need to keep moving all the values in it down one index per new value hitting index [0] to make sure that each reading has a lifetime of 60 seconds on the array.  Here is my code so far:
void add_readings_to_averages() {
  // At this point, I am moving values down the array to make room at the beginning.
  for (int a = 11; a >= 0; a--) {
    Serial.print("The value at temperature_c_minute_avg[");
    Serial.print(a);
    Serial.print("] is ");
    Serial.print(temperature_c_minute_avg[a]);
    Serial.println();
    if (a == 11) {
      Serial.println("At 12 so need to overwrite this value");
    }

    if (a <= 10) {
      Serial.print("a is ");
      Serial.println(a);
      temperature_c_minute_avg[a] = temperature_c_minute_avg[a + 1];  // This moves each entry down one index in the array creating an empty space at index[0]
    }

    if (a == 0) {
      temperature_c_minute_avg[a] = temperature_c;
    }
  }

I've loaded my array at the time of initialization with some dummy data so I could see what was going on.  First run displays as you would expect.
The value at temperature_c_minute_avg[11] is 120.00
At 12 so need to overwrite this value
The value at temperature_c_minute_avg[10] is 110.00
a is 10
The value at temperature_c_minute_avg[9] is 100.00
a is 9
The value at temperature_c_minute_avg[8] is 90.00
a is 8
The value at temperature_c_minute_avg[7] is 80.00
a is 7
The value at temperature_c_minute_avg[6] is 70.00
a is 6
The value at temperature_c_minute_avg[5] is 60.00
a is 5
The value at temperature_c_minute_avg[4] is 50.00
a is 4
The value at temperature_c_minute_avg[3] is 40.00
a is 3
The value at temperature_c_minute_avg[2] is 30.00
a is 2
The value at temperature_c_minute_avg[1] is 20.00
a is 1
The value at temperature_c_minute_avg[0] is 10.00
a is 0
2018/11/2 11:4:39  -  Running for a total of 0 hours 0 minutes and 7         seconds

But the second time through the loop() my array is trashed.
The value at temperature_c_minute_avg[11] is 120.00
At 12 so need to overwrite this value
The value at temperature_c_minute_avg[10] is 120.00
a is 10
The value at temperature_c_minute_avg[9] is 120.00
a is 9
The value at temperature_c_minute_avg[8] is 120.00
a is 8
The value at temperature_c_minute_avg[7] is 120.00
a is 7
The value at temperature_c_minute_avg[6] is 120.00
a is 6
The value at temperature_c_minute_avg[5] is 120.00
a is 5
The value at temperature_c_minute_avg[4] is 120.00
a is 4
The value at temperature_c_minute_avg[3] is 120.00
a is 3
The value at temperature_c_minute_avg[2] is 120.00
a is 2
The value at temperature_c_minute_avg[1] is 120.00
a is 1
The value at temperature_c_minute_avg[0] is 0.00
a is 0
2018/11/2 11:4:44  -  Running for a total of 0 hours 0 minutes and 12     seconds

The entire array was overwritten with the last value and the new value was not added.  The array itself is setup as a global variable.  The initialization at the top.
float temperature_c_minute_avg[12] = {10.0,20.0,30.0,40.0,50.0,60.0,70.0,80.0,90.0,100.0,110.0,120.0};

What am I missing here?  Been staring at this for some time, but this is the first time I've tried to use an Arduino array so I can totally believe the issue is PBKAC! :)

I'm voting to keep this question open. According to this page: https://arduino.stackexchange.com/help/on-topic, "On topic" includes "Specific questions about Arduino boards, code…".

Your issue is a C programming issue and has nothing to do with the Arduino specifically.  You should research how to implement a circular buffer.  You don't want to move around the values within the array, but rather just increment array index values.  Keep two index values, one of the current index position (the place where the next recorded value will be placed) and another of the number of values recorded.  Eventually the number of values recorded will be equal to your maximum array size and only the index position will increment.  When the array index exceeds the maximum array size it wraps back to 0.

Guys, thanks for the assistance.  I've gone down the path of a circular buffer to solve this.

In your if (a <= 10) block, you are inside a for loop that is decreasing and replacing each value with the value inside index+1. This means that as you are going down the indices, you are carrying the 11th index value with you. Here is how it is without variables (allow me to shorten the variable name to t):
t[10] = t[11];
t[9] = t[10];
t[8] = t[9];

And so forth. Whatever was in a[11] is being dragged through each of the variables of lower indices.
I strongly suggest going the other way around with either your loop or which way you are pushing the data. For instance (continuing with array name t):
for (int i = 11; i >=0; i--) {
    if (i > 0)
        t[i] = t[i-1]; // shift data from index 10->11, 9->10, etc.
}
t[0] = arbitrary_data; // fill in new 'empty' space

Or, alternatively if you still want to put new data in index 11:
for (int i = 0; i <= 11; i++) {
    if (i < 11)
        t[i] = t[i+1]; // shift data from index 1->0, 2->1, etc.
}
t[i] = arbitrary_data; // fill in new 'empty' space

This is my solution for your current data management method. Another answer suggested a circular buffer where you simply keep track of which datum is being changed at a time and is far more efficient.


text:
DHT22 need pull down/up ESP8266
I have the strange pb.
My esp8266 was working fine with my DHT22 and then failed every time.
I loaded an example sketch in a other ESP8266 and I have the same pb.... until I shut down -> up the DHT22 when the ESP8266 is working.
To check more, I added this at the setup before dht.begin() :
      digitalWrite(0, LOW); // turn the LED on (HIGH is the voltage level)
  delay(1000); // wait for a second
  digitalWrite(0, HIGH);

And it works. But I don't know why I need to do this "pull up".
PS : I already tried with or without the 10K resistor, same pb.
PS2 : I already tried with 3.3v or 5V for DHT22. Same pb.
Any idea ?

how is the DHT22 wired and what esp8266 module you use?

I use a nodeMCU (Bangood, Geekcreit). The DHT22 is wired like this : https://learn.adafruit.com/adafruit-io-basics-temperature-and-humidity/arduino-wiring?fbclid=IwAR0cLuSXA4HMeCTtD-YC03FJ9pqGUj37HY_hyMXhz5dp4z-I-HkIzA1Or0Y

to which pin of NodeMcu is the DHT data pin 2 connected? to D2 (io 0)?

I connected it to pin D4. But the pb is I can see the data AFTER the pullUp trick. So why ?

sorry D2 is not io 0, it is io 4

Can you use a i2c humidity and temperature sensor? The dht sensors are not accurate and they cause many problems. The esp8266 is sensitive for this bug: https://github.com/adafruit/DHT-sensor-library/issues/48 The data signal has a shortcut since that library was written. The issue is from 2015 and adafruit has not fixed it yet, so they probably never will. Please use a i2c humidity and temperature sensor.

No, I haven't an other one. As the DHT11 and 22 seams to be used frequently, I thought it was good. I will check the issue. Does it work if we modify the lib code ?

Cocorico, when you use @Jot in your answer, I will get notified. There are also timing issues with the esp8266 and the dht11 / dht22 sensors, and library incompatibilities. That was already a problem, but since this year many have issues. So please use a i2c humidity and temperature sensor.

I answer my own question in case someone has the same issue.
The ADAFRUIT_DHT lib DOESN'T WORK WITH ESP8266. It keep saying Failed to read from DHT sensor! until you unplug/plug the VCC on the DHT.
But the DHTesp (link) works very well at first try !
Thx @Juraj and @Jot for their support.


text:
Loops fail after ~5 minutes when making two API calls every 10 seconds using WiFi client
I am running into an issue with a loop call on an Arduino MKR1000. I have tried the solutions suggested in this question and it usually works for 5 minutes and then collapses.  I am trying to make two calls to different APIs every 10 seconds and update something on the Arduino accordingly, but the loops seem to be getting out of sync after a few minutes. Here is the code - I tried to shorten it...

#include <Time.h>
#include <SPI.h>
#include <WiFi101.h>
#include "arduino_secrets.h"

// put your local wifi info here
const char* ssid     = SECRET_SSID;
const char* password = SECRET_PASS;

const char* host = "bustime.mta.info";

void setup() {
  Serial.begin(9600);
  delay(10);
 // connecting to a WiFi network
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.print(". ");
  }
}

void loop() {
  Serial.println("START THE LOOP");
  // Use WiFiclient class to create TCP connections
  WiFiClient client;
  WiFiClient client2;
  char * serviceDeliveryString = new char[40]();
  strcpy(serviceDeliveryString, "/ServiceDelivery");
  char * responseTimestampString = new char[40]();
  strcpy(responseTimestampString, "<ResponseTimestamp>");
  char * TString = new char[40]();
  strcpy(TString, "T");

  if (!client.connect(host, 80)) {
    lcd.clear();
    lcd.gotoXY(0, 0);
    lcd.string(connectionFailed);
    delay(2000);
    return;
  }

  //connect to schedule data
  if (!client2.connect(host, 80)) {
    lcd.clear();
    lcd.gotoXY(0, 0);
    lcd.string(connectionFailed);
    delay(2000);
    return;
  }

  char * req1full = new char [100]();
  strcat(req1full, "GET /api/siri/stop-monitoring.xml?key=KEY&OperatorRef=MTA");
  strcat(req1full, " HTTP/1.1");
  client.println(req1full);
  client.println("Host: bustime.mta.info");
  client.println("Connection: close\r\n");

  char * req2full = new char [100]();
  strcat(req2full, "GET /api/where/schedule-for-stop/MTA_");
  strcat(req2full, stopNum);
  strcat(req2full, ".xml?");
  strcat(req2full, "key=KEY HTTP/1.1");
  Serial.println(req2full);
  client2.println(req2full);
  client2.println("Host: bustime.mta.info");
  client2.println("Connection: close\r\n");

  //Pause long enough for the connection to happen. Make this longer if you have issues.
  delay(1000);

  while(client.available()){
    if (client.findUntil(responseTimestampString, serviceDeliveryString)){
      Serial.println("inside client...");
      client.findUntil(TString, serviceDeliveryString);
      String mtaTime = client.readStringUntil('.');
      Serial.println(mtaTime);
    }
    delay(10);
  }

  while(client2.available()){
    if (client2.findUntil("<currentTime>", "/data")){
      Serial.println("inside client2...");
      String mtaTime2 = client2.readStringUntil('<');
      Serial.println(mtaTime2);
    }
    delay(10);
  }

  client.stop();
  client2.stop();
  delay(9000);

}

The output starts out looking good:
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:13:38
inside client...
22:13:38
inside client2...
1541211218146
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:13:51
inside client...
22:13:51
inside client2...
1541211231815
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:14:04
inside client...
22:14:04
inside client2...
1541211244465

But eventually something seems to happen with the loops and this is the final output, when it should keep running:
inside client...
22:19:02
inside client...
22:19:02
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
START THE LOOP

Any suggestions for how to fix this?

is there a restriction on the frequency or the number of API calls to bustime.mta.info?

No, I don't believe so.

Hint: Possible memory leak. A lot of "new" but few "delete" (malloc/free).

thanks @MikaelPatel, I have cut out the 'new' and it seems to be working okay.

You keep calling new to allocate memory but you never free it.  This is a memory leak and eventually you run out.  Instead of constantly creating new arrays, why don't you make those global or static.  Or even just local arrays if you don't need them to be persistent.  On a microcontroller you really don't want to be using new unless absolutely necessary.

I used "new" so that all the entries would be initialized as missing. I could move all the array declarations to before loop() though. Or maybe in setup()? THANK YOU for responding!

What do you mean by "initialized as missing".  That phrase doesn't make any sense to me.

If you put the array definitions in setup then they'll be local to setup and you can't use them in loop.

If you want to use "dynamic" allocation like that, consider using alloca(), since it allocates the space on the stack and it's automatically freed when the function finishes.


text:
Is Arduino Keyboard in Single User Mode Possible?
Has anyone had success using the keyboard functionality of any arduino in single user mode of mac computers? I would like to inject keystrokes in single user mode, and have been unsuccessful with the atmega32u4.

Does it work in normal user mode? Are you using a Leonardo?

Yes, it works in single use mode. It is a Micro/Leonardo clone.

It works in Single user mode? I thought that it was in Single user mode that you were having problems. Now I am confused

I have found the solution to my problem. The issue is that the presence of both the usb device and serial port causes issue in single user mode. For the keyboard to work properly, the serial port must be disabled. This means that reflashing the micro requires pulling the reset pin low twice quickly for the port to show up again. Here is an example of how to remove the serial port:
https://github.com/gdsports/usb-metamorph/tree/master/USBSerPassThruLine

OS X requires a "Boot Interface" compatible HID profile for a keyboard to work in single user mode (it has only loaded very rudimentary drivers by that point).  The Arduino doesn't provide that interface, so can only work with the more advanced drivers the OS provides once booted.
You can try setting the "boot interface" flag to 1 in the interface subclass (here, I think, changing HID_SUBCLASS_NONE to HID_SUBCLASS_BOOT_INTERFACE) though I have no clue what the actual effect of that will be given that it's a composite device that may or may not conform to the boot interface standard.

Thanks for the suggestion. I tried this and saw no difference in behavior.

Ah well - then the answer is probably "no"...

Do you think it has to do with the board I'm using or the fact that I'm trying to do it on a mac?

It's a combination of the two. The Mac has specific requirements (the same requirements as a PC when in the BIOS), and the Arduino's USB software doesn't meet those requirements. There may be a better board for the job that has a better USB stack, but I don't know of one off hand.


text:
Splitting a message
I have a string to be splitted into define chunks.
For example new_str="abcdefghjklmnopqrstuvwxyz, and my goal is to split it to chunks of split_size=5, so the result should be :abcde,fghij and so o.
new_str gets every time a different string.
split_size can be any size.
I have 2 questions:
1) Attached code does the job, but looks a BIT not elegant for a newbie like me. is there another way doing it ?
2)In code attached, output is Serial.println(tmp) and should be replaced with an output function to post each chunk to as a MQTT message. Ive rather that each chunk would be stored into a global array, to be sent later on in code out side msgSplitter.
So I wrote the following code:
int split_size=5;
char new_str[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
void setup() {

        Serial.begin(9600);
        Serial.print("String length: ");
        Serial.println(strlen(new_str));
        Serial.print("Split Size: ");
        Serial.println(strlen(split_size));

        msgSplitter(new_str, split_size, "Split #");

}
void msgSplitter( const char* msg_in, int chop_size, char *prefix){
        num=ceil((float)strlen(msg_in)/chop_size);
        char tmp[50];
        int pre_len;

        if (num > 1) {
                for (int k=0; k<num; k++) {
                  pre_len=0;
                        sprintf(tmp,"%s %d: ",prefix,k);
                        pre_len = strlen(tmp);
                        for (int i=0; i<chop_size; i++) {
                                tmp[i+pre_len]=(char)msg_in[i+k*chop_size];
                                tmp[i+1+pre_len]='\0';
                        }
                        Serial.println(tmp);
                }
        }
        else {
                Serial.println(msg_in);
        }
}

// concat version
void msgSplitter(const char* msg_in, int chop_size, char *prefix) {
  char tmp[50];
  int size = strlen(msg_in);
  for (int pos = 0, k = 0; pos < size; pos += chop_size) {
    int l = sprintf(tmp, "%s %d: ", prefix, k++);
    strncat(tmp + l, msg_in + pos, chop_size);
    Serial.println(tmp);
  }
}

// only value version
void msgSplitter(const char* msg_in, int chop_size, char *prefix) {
  char tmp[chop_size + 1];
  tmp[chop_size] = 0;
  int size = strlen(msg_in);
  for (int pos = 0; pos < size; pos += chop_size) {
    strncpy(tmp, msg_in + pos, chop_size);
    Serial.println(tmp);
  }
}

Can you answer my 2nd cquestion ?

the second version of the function in my answer is it. replace println with the publishing function

You Rock Juraj!

U2 :) ( cough cough )


text:
Is there a way to traverse a filesystem and read files with an arduino?
I recently got into arduino and I want to set up something big. My project will need the arduino to be able to get into a specific directory of a windows (later may change to linux but for now windows) computer which will have some files with values required for the arduino to run.
Is it possible to set it to go to a fixed path and open a file with a specific name and get it's contents?
Ideally I would want those values to be stored to my micro sd so I do not load too many things on memory as my board is a Leonardo and the code is quite extensive already. (The board can be changed if needed)
Any help/ideas are appreciated!

what kind of files are on the windows machine that you wish to retrieve?  .....  set up a web server on the windows machine .... the Arduino could get the files as a web client

The Arduino has no access to the file system on a PC.  All it has is a serial connection with which it can communicate with some program running on the PC. The code that is handling the PC's file system would have to run on the PC itself.

Leonardo has USB for HID.

@Juraj how would that help?

It would not. But it is not true that it has only a 'serial' connection. (and I know that USB is serial communication too)

@Juraj Strictly speaking, yes it is true. The "S" in USB stands for Serial. It has a serial connection - over which a number of protocols are layered. One of which itself emulates another serial connection.

I was slow with edit of comment

so Win+E starts Explorer, some shortcut goes into path field, type in the path, Enter, Tab to pane. the 'serial' HID can do this

But how do you then get the data back to the Arduino? It can't see the screen.  You'd basically have HID writing a program on your PC that reads the data and sends it down through the CDC/ACM channel. Quite a task, and really a bit silly. Just write the program for the PC and have it communicate through CDC/ACM alone - that way it doesn't mess with your desktop session and interrupt you. Or use a network connection instead and collect the data from a website / online service.

I only wanted to indicate how the idea of controlling the PC could emerged

This could get complicated.
You'll need to develop a USB interface on your Arduino to "talk" to the PC.  Then you'll need to write an application (use whatever language you feel comfortable with - that's an entire religious discussion for another place and time) that "listens" for the Arduino's USB connection and does most of the legwork.  Think of the PC application as sort of a "script server", allowing the Arduino to make cryptic requests ("FCNT" requests a 'File Count' on your target PC folder, that sort of thing) which the PC application will then return data from, as needed.  (In the previous example "FCNT" gets a file count of a predetermined folder - which would return a four-byte [integer] value revealing the results of the file count.)  From this point you could add additional scripts and functionality, allowing your Arduino to make abbreviated (sometimes wonky-seeming) calls to the PC, and have the PC do what is necessary to fulfill those requests.
In the example I hastily described above, your Arduino sends "FCNT" and then "listens" to the USB interface, eagerly awaiting the return value that it knows will be a four-byte response.  If the PC application were properly programmed, you could get slick with your command calls, sending "XFR #" which asks the PC application to "transfer file [#] to me" at which time the Arduino goes into "paddle board" mode, where it receives data from USB and immediately transfers it to the MicroSD until  is "seen" in the data stream, at which point the Arduino returns to normal code operations mode.
Of course, your PC application will need to be extremely fault-tolerant in order to prevent sending your Arduino bad data or worse, sending it into a state that can't be easily recovered, such as if the Arduino "thinks" it's expecting a file and goes into "wait for transfer" state, but the file it requested doesn't exist because it got deleted sometime between the file count request and the transfer request.  The Arduino would appear to be "hung up" because it would be in "File Transfer" or "paddle board" mode, and not looking for other messages or awaiting other operator stimulus.
Due to the different architectures, there really is no simple way to interface an Arduino to a PC.  Sorry about that.


text:
NodeMCU does not connect to wifi
I'm trying to connect my nodeMCU to my WiFi network but it keeps printing ........ which means is not connecting to the network. Here is my code used to connect to WiFi. Any reason why it isn't connecting to WiFi network?.
#include <ESP8266WiFi.h>

        // Replace these with your WiFi network settings
        const char* ssid = "******"; //replace this with your WiFi network name
        const char* password = "******"; //replace this with your WiFi network password

        void setup()
        {
          delay(1000);
          Serial.begin(57600);

          WiFi.begin(ssid, password);

          Serial.println();
          Serial.print("Connecting");
          while (WiFi.status() != WL_CONNECTED)
          {
            delay(500);
            Serial.print(".");
          }

          Serial.println("success!");
          Serial.print("IP Address is: ");
          Serial.println(WiFi.localIP());
        }

        void loop() {
        }

could  be that your router is refusing the connection

@jsotola how to fix it?

that is only a guess ..... there could be other reasons ...... try connecting to another network ..... maybe one that does not require a password

try WiFiScan example

@Juraj I tried it and it shows all the WiFi connection available.

including the SSID you want to connect?

@Juraj Yes including the one im trying to connect

has the ssid or password unusual characters like space, hashtag, dolar?

@Juraj No only letters and numbers. Btw what if remove the password? can i pass an empty string to the password variable?

use only one parameter, the ssid

has the network, you want to connect, DHCP?

@Juraj No its not DHCP

then assign IP address

@Juraj How to do that?

try to print WiFi.status() instead of '.'. or better wifi_station_get_connect_status()

did you solve it?

I also have the same issue but i can connect it with mobile hotspot!! so just try in this method

5ghz networks will not connect to esp

If your WiFi network doesn't have DHCP, then you must set the IP addresses
example:
  IPAddress ip(192, 168, 1, 8);
  IPAddress gw(192, 168, 1, 1);
  IPAddress sn(255, 255, 255, 0);
  WiFi.config(ip, gw, sn, gw);

gw is gateway. the last parmeter is dns server's IP. sn is subnet mask.

Thanks for the answer but i checked my router configs and its is DHCP enabled

see DHCP logs in router if there is a record about DHCP request from the esp

If your powering the device via a computer USB port there is a good chance it’s not providing enough power for the wifi.
Try powering fron an external source.

where did you get this? 500 mA from USB is enough. he has no motor connected


text:
Arduino Nano- Programer not responding after upload WDT
I followed an example link for WDT. Code was copied as is, and uploaded to Nano successfully.
Now- when I wish to upload another code, I get an error message saying avrdude: stk500_recv(): programmer is not responding.
Is it possible to undo it ?
code:
#include <avr/wdt.h>

#define led 13 // pin 13 is connected to a led on Arduino Uno

void setup()
{
  pinMode(led, OUTPUT);      // set pin mode
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);                // wait for a tenth of a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(100);                // wait for a tenth of a second
}

void loop(){
  wdt_enable(WDTO_15MS);     // enable the watchdog
                             // will fire after 15 ms without reset

  while(1)
  {
//     wdt_reset();          // uncomment to avoid reboot
  }
}

change the bootloader in Nano to a new one, which doesn't have this problem. and you shuold enable wdt in setup and reset it in loop.

One of the things with the watchdog is that after a watchdog reset it remains active. It has to specifically be turned off - and the bootloader doesn't (IIRC) normally turn it off.
If the timeout is too short (shorter than the time taken to upload new code) the watchdog will reset the chip while you're uploading.
The only way to turn it off is to physically remove power from the chip, and make sure that the loaded sketch never runs.

Select the board / port etc ready to upload
Unplug the board
Hold the reset button in
Plug in the board
Press upload on the IDE
6 Just as avrdude is about to run (that's the program that does the actual uploading) - just as the compiling has finished, release the reset button

If you did it right you should be able to upload properly.  If not, you will have to try again from step 1.

If the WDT program is running when you try to upload a new one, it may be blocking the bootloader. Try holding the reset button while you click the the IDE's upload button, releasing the reset once you see avrdude launch. It may take a few tries to get the button-dance just right.
Update:

what is avrdude ?

It is the program on your PC that uploads the compiled image to the Arduino. You'll see it running in the lower pane of the Arduino IDE.

what is avrdude ?


text:
using esp8266 feather to burn bootloader on redboard
Is it possible to burn the bootloader of an arduino redboard using an esp8266 feather? whenever i connect my redboard to my pc the ports list on the ide would just be greyed out. I've looked around online and tried everything I found except burning the bootloader since I didnt have a spare arduino, atmega or a programmer. I have an EPS8266 feather though.
If anyone know whether or not this is possible to do and could walk me through on how to do it if it was.

Sparkfun Redboard? yes it is possible, but complicated and it will not help with port grayed out

The RedBoard has an FT232 chip for the USB interface.  Flashing the bootloader on the main MCU will have no effect at all on your problem.
While, yes, it is technically possible to use the ESP8266, it's not easy and, since it won't cure your problem of a greyed out port option, isn't worth the effort to try and do it.
Instead, you should be looking at things like your USB ports, USB cables, FT232 drivers, etc on your computer.

well I guess my redboard is broken then. I've tried 3 different cables which I know isn't just for power and the ports work fine with other devices so those are good too, FT232 drivers? don't remember installing those but my arduino worked fine before, and loopback test doesn't work. Guess I need to get a new arduino

What OS are you using?  Check the chip next to the USB port - it should say "FT232" on it.

I am on Windows 10. Chip? on my redboard? This is what I see https://imgur.com/a/SQroRKO

Yep, that's the FT232. The strange looking one.

the latest project i used on it was this https://i.imgur.com/lyP0gkA.png.
I used an 8pack aa battery for 12v and wired it into the vin to power the arduino. reckon that burned it out?

You'd need to test the correct functionality of all the components on the board. Start with checking all the right voltages are in the right places.

It was working as intended. Everything was working fine and the voltages going to the rfid and solenoid was just about right. the voltage going into vin was the exact same as the solenoid at around 11.45v. It's just the next day it just stopped working


text:
How to convert byte array into a single variable
In this code i am taking the TID data(20bytes of 160bits) in the form of array according documentation and and its working correctly and getting the output of RFID tags.
Now I just need your guidance that how can i convert the array of 20 Bytes into a single variable or into a double long datatype? or another. Because I have to push it on to my MySQL database server for further processing.
I had tried the following code which works fine
byte x[10] = "450210921";
long result = atol(x);
Serial.print("long value of the byte is: ");
Serial.println(result);

but when i put the above code into my main code, getting not any error and I am not getting the required output.!
void setup()
{
  Serial.begin(115200);
}

void loop()
{
  byte response;
  byte myTID[20]; //TIDs are 20 bytes
  byte tidLength = sizeof(myTID);

  //Read unique ID of tag
  response = nano.readTID(myTID, tidLength);
  if (response == RESPONSE_SUCCESS)
  {
    for(byte x = 0 ; x < tidLength ; x++)
    {
      if(myTID[x] < 0x10) Serial.print("0");
      /*temp[x]=(myTID[x], HEX);*/
      //Swapping values into temp variable
      temp[x]=myTID[x];
      Serial.print(temp[x]);
    }
    /*byte x[10] = "450210921";*/
    //Convert a whole array into a single long variable
    long result = atol(temp);
    Serial.print("long value of the byte is: ");
    Serial.println(result);
  }
  else
    Serial.println("Failed read");
}

There is no such thing as a single variable that is 160 bits in size.  I think you want to format the bytes as a string (and there are plenty of questions about that on here).

Ok @Majenko but is there any way to push complete an array to MySQL into a single table cell using nodemcu?

I have no idea about the MySQL side of things, but you can take each byte in the array, turn it into a text representation of a hexadecimal pair, concatenate them all in a string, and use that string.

https://arduino.stackexchange.com/questions/53258/how-to-store-an-rfid-tag-number-in-a-string

There are several simple errors: 1) "atol(x)" should be "atol(tmp)", 2) but then "tmp" should be null-terminated, 3) which then implies that it is too short. And so on.

You can't convert 20 bytes to long. Send it as string of hex values. A byte takes two characters in hex, so you will send a 40 characters string, which can be simply decoded back to bytes.
char str[sizeof(myTID) * 2 + 1];
const char* hex = "0123456789ABCDEF";
for (int i = 0; i < sizeof(myTID); i++) {
  str[i * 2] = hex[(myTID[i] >> 4)];
  str[i * 2 + 1] = hex[(myTID[i] & 0x0F)];
}
str[sizeof(str)] = 0;
Serial.println(str);

It works! Thank, what about for this
for(byte x = 0 ; x < sizeof(myTID) ; x++)
{
content.concat(String(myTID[x] < 0x10 ? " 0" : " "));
content.concat(String(myTID[x], HEX));
}
content.toUpperCase();
softSerial.print(content);

String is not good

Could you explain it that how the string is not good!!

https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/


text:
Arduino Uno with ESP8266-01 with AT
Here is the schematic I followed:

Here also the link: https://www.circuito.io/app?components=10167,11021,12083,13678,13959
#include "DHT.h"
#include "NewPing.h"
#include <SoftwareSerial.h>
#define DEBUG true

SoftwareSerial esp8266(11,10);

#define DHTPIN 2       // DHT-11 Output Pin connection
#define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
#define TRIGGER_PIN 4
#define ECHO_PIN 3
#define MAX_DISTANCE 400

NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

float hum;
float temp;

DHT dht(DHTPIN, DHTTYPE);

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

  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  sendData("AT+RST\r\n",2000,DEBUG);
  sendData("AT+CWMODE=2\r\n",1000,DEBUG);
  sendData("AT+CIFSR\r\n",1000,DEBUG);
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);
}

void loop()
{
  delay(2000);  // Delay so DHT-11 sensor can stabalize

  hum = dht.readHumidity();  // Get Humidity value
  temp= dht.readTemperature();  // Get Temperature value

  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

  long duration,distance;
  duration = pulseIn(ECHO_PIN,HIGH);

  distance = duration/58.2;

  Serial.print("Humid: ");
  Serial.print(hum);
  Serial.print(" %, Temp: ");
  Serial.print(temp);
  Serial.print(" C, ");
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(50);

  if(esp8266.available())
  is sending a message
  {
    if(esp8266.find("+IPD,"))
    {
      delay(1000);
      int connectionId = esp8266.read()-48;
      /* We are subtracting 48 from the
         output because the read() function returns
         the ASCII decimal value and the
         first decimal number which is 0 starts at 48 */
      String webpage = "
IOT Garbage Monitoring System
";
      webpage += "

";
      if (distance<5)
      {
        webpage+= " Trash can is Full";
      }
      else{
        webpage+= " Trash can is Empty";
      }
      webpage += "

";
      String cipSend = "AT+CIPSEND=";
      cipSend += connectionId;
      cipSend += ",";
      cipSend +=webpage.length();
      cipSend +="\r\n";

      sendData(cipSend,1000,DEBUG);
      sendData(webpage,1000,DEBUG);
      String closeCommand = "AT+CIPCLOSE=";
      closeCommand+=connectionId;
      closeCommand+="\r\n";
      sendData(closeCommand,3000,DEBUG);
    }
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";
  esp8266.print(command);
  long int time = millis();
  while( (time+timeout) > millis())
  {
    while(esp8266.available())
    {
      char c = esp8266.read();
      response+=c;
    }
  }
  if(debug)
  {
    Serial.print(response);
  }
  return response;
}

I've been trying to solve this problem for almost a week.

Comments are not for extended discussion; this conversation has been moved to chat.

This is not a forum. Questions should stand on their own, and comments under questions should seek clarification which is edited into the question. If there is more information which would help answer this question it should be edited into the question by the asker of the question (the OP, namely Xiaomy).

@NickGammon, that is what we did. only it took many clarification questions. clarifications were edited into Question

@Juraj need your assistance

related in this topic see the chat thank you sir @Juraj

@Juraj https://chat.stackexchange.com/rooms/85432/discussion-on-question-by-xiaomy-arduino-uno-with-esp8266-01-with-at

If you want to use esp-01 over SoftwareSerial, you must set the AT firmware's default baud rate to 9600 baud. The default baud rate of AT firmware is 115200 baud. SoftwareSerial can't work at this speed.
To change the baud rate you must have a way to communicate with AT firmware at the default baud rate of 115200 baud. You can use the USB adapter of the Uno. Upload BareMinimal sketch from Examples to Uno to make it silent and connect the esp-01 to RX and TX pins of the Uno.
Connect RX to RX and TX to TX to have the cross connection to USB of the Uno. Then connect from Serial Monitor to esp-01 at 115200 with "Both line end characters" set. Try some basic AT commands and then still at 115200 baud send the command to change the default baud rate AT+UART_DEF=9600,8,1,0,0

In setup() in sketch begin for SoftwareSerial is missing. Add  esp8266.begin(9600);

Uno pin 11 is RX of software serial, pin 10 is TX. The RX pin 11 must connect to TX pin of esp-01. Same applies for TX pin 10. It must connect to RX pin of the esp-01.
On the Fritzing schema on Uno pin 11 is green wire and on esp-01 TX is green wire. But the green wire is on sides of the level converter not on the same position. The conclusion is that you have RX connected to RX not to TX. Switch wires on best at level converter.

The 3.3 V pin of some Uno clones can't supply enough current for WiFi operations of the esp8266. You need to convert to 3.3 V from Uno 5 V pin or use a separate 3.3 V power source for the esp-01.

This guy is a genius and very kind! :)

details are in chat https://chat.stackexchange.com/transcript/85432

sir @Juraj need your help sir


text:
Trying to understand how to make a program do three things with a button press
I am trying to write some code, which I barely grasp - but it's coming along! But I think I've hit a wall that I could using some help getting  over...
I'm not asking for you to fix my code - I know that's not how I am going to learn, maybe explain why my code isn't doing what I want it to, and/or some resources I can using to learn about it.
I think it has something to do with me trying to use the same pins in the initialization part since the error is about a conflicting declaration..
Here's my breadboard layout if this helps too:

//ABOUT - This programs goal is to make a button cycle through three    different 'modes'
//Mode 1 - make a RGB LED cycle through its colors
//Mode 2 - make the same RGB LED fade-cycle through its colors
//Mode 3 - make the same RGB LED blink on-off all three colors at once
//Additional modes may follow but this is the beginning.

//currently all my initialization code is from three different programs and I think that's why parts are not working.. I think
//I can share the mode initialization code for each mode....?  But the face code uses the uint8_t vs just int so maybe not?

//Button Cycle - this is the first part of my code, designed to teacah me how to make a button cycle through to different parts of the code

int counter = 0;
int switchPin = 13;
int LEDB = 11;
int LEDG = 10;
int LEDR = 9;

//RGB LED Cycle Circuit - mode 1
const int redLED=3; //red LED connects to digital pin 8
const int blueLED=5; //blue LED connected to digital pin 7
const int greenLED=6; //green LED connected to dogotal pin 6

//RGB LED Fade Circuit - mode 2
const uint8_t redLED = 3;  // pin connected to the red LED - I don't understand why this code says const uint8_t  -
const uint8_t blueLED = 5;  // pin connected to the green LED
const uint8_t greenLED = 6; // pin connected to the yellow LED

void setup()
{
  Serial.begin(9600); //I added this to help learn what the counter was doing
  pinMode(switchPin, INPUT);
  pinMode(LEDR, OUTPUT);
  pinMode(LEDG, OUTPUT);
  pinMode(LEDB, OUTPUT);
}

void loop() {
  //Handle input
  int switchVal = digitalRead(switchPin);
  if(switchVal == LOW) //changed from HIGH which was making the modes appear to change randomly - may come in useful later but not what I want initially
  {
    delay(500);
    counter ++;
    Serial.println(counter); //prints value of counter to serial monitor so I can see why it appeared to be random
    //I learned that when the switchVal == HIGH was in place the counter would cycle continuously. Making each button
    //press appear random. Changing this to LOW made the counter wait for a LOW event before counting. Increasing the
    //delay to half a sec gives time to release the button before the counter continues.

    //Reset count if over max mode number
    if(counter > 3)
    {
      counter = 1; //in serial monitor you will see that the counter goes to 4 but this code tells the program that 4 = 1 so it runs the right mode
    }
  }
  else
    //Change mode 1
    switch (counter) {
    case 1:
      analogWrite(LEDB, 000);
      analogWrite(LEDG, 000);
      analogWrite(LEDR, 255);

      //start LED Cycle - this is simply pasted in from the LED cycle program - seems to work fine

      digitalWrite(redLED,HIGH);//turns the LED on
      delay(100);//waits 3 seconds
      digitalWrite(redLED,LOW);//turns the LED off
      digitalWrite(greenLED,HIGH);//turns the LED on
      delay(100);//waits 3 seconds
      digitalWrite(greenLED,LOW);//turns the LED off
      digitalWrite(blueLED,HIGH);//turns the LED on
      delay(100);//waits 3 seconds
      digitalWrite(blueLED,LOW);//turns the LED off
      break;

    //mode 2 code
    case 2:
      analogWrite(LEDR, 000);
      analogWrite(LEDB, 000);
      analogWrite(LEDG, 255);

      //LED Fade Cycle
      // Fade an analog pin up and down.
      void fade(uint8_t pin);
      {
        for (int i = 1; i <= 255; i=i+5) {
          delay(10);
        }
        for (int i = 254; i >= 0; i=i-5) {
          delay(10);
        }
      }
      //void loop(); - think I can only have one void loop so I'm commenting this out for now..
      {
        //Serial.println(F("Fading GREEN."));
        fade(redLED);
        //Serial.println(F("Fading BLUE."));
        fade(blueLED);
        //Serial.println(F("Fading YELLOW."));
        fade(greenLED);
      }
      break;

    //mode 3 not coded yet - waiting to make mode 2 work
    case 3:
      analogWrite(LEDG, 000);
      analogWrite(LEDR, 000);
      analogWrite(LEDB, 255);
      break;
    }
}

Change the title to a more specific question.  What exactly about the code do you not understand?

There are two immediate things I can see wrong:

You have two sets of the same pin definitions. You only want one set. Both sets are identical - once it's defined its defined - you can't define it again as the same thing.
You seem to have a function defined in the middle of your loop() function.  That can't work - functions have to be separate things. (also you don't want a ; in your function definition...)

You've used the blue lower rail for Ground but used the red lower rail (usually used for +5v) as a simple connection point. It's not wrong but it's unusual enough to be confusing to readers. The choice of red  button-signal wire on the red rail also strongly suggest a connection to +5v even though that is not the case here.
The buttons, "tact" switches, are confusing by design (see picture below). Each pair of pins curved toward each other (I marked one with a red arrow) are the physically same pin and always connected to each other. The pairs are connected to each other only when the button is pressed. It's really easy to miss that and insert the button 90deg either way from what you intended. Fritzing's button icon doesn't show the orientation either. Yours may well be correct - it's just a pitfall to be aware of.

void fade(uint8_t pin); doesn't define a function - it declares that one exists somewhere else. I think you meant void fade(uint8_t pin){ ... } (note no semi-colon), which would define the function, if that were a proper location to do so. But in C and C++, functions may not be defined within other functions (loop(), in this case). Fix the definition of 'fade' and move it to above 'setup()'. That will properly define it and make it usable from within the loop() function.
The braces, {}, where you tried to define a second loop function are unnecessary (and, you're correct, you can't define more than one function with the same name and signature (parameter count & types, and return type). But you don't need another loop(); the code contained in the {} - three calls to the fade function - remain part of case 2:.

I think what you are missing is a pulldown resistor for the button. Simply put, a pulldown resistor is a resistor pulls down the input reading to 0 when the button is not pressed. Without the pulldown resistor, the value read in the digitalRead will float around giving inaccurate results.

Above is a circuit showing how the pulldown resistor should be wired with a button.
If you would like to learn more about pulldown resistors, please refer to this page describing buttons in the Arduino Website.
This is just a hardware issue I noticed; hopefully, this will help you out in addition to the other recommendations given.
As a side note, a pull-up resistor can also be used, and in this case, the value will be 1 when the button is not pressed.


text:
Connecting an Arduino to a servo with an external power supply
I have purchased an MG995 servo (4.8-7.2V operating voltage, 170MA no load operating current draw) and will power this using a 5V, 2A mains plug pack. Do I need a breadboard to connect this with my Arduino (which will itself be powered through its usb port)? Or is it possible to connect the servo with the Arduino directly?
If it's possible to connect it directly, which pins should I be using on the Arduino? Will it look something like this:

except the red wire (and black wire?) connects to the external power supply?
Any answers (or links to relevant tutorials which have all three of these components) would be welcome. Thanks!

Don't  pull the power for the servo through the Arduino.  They need to be powered in parallel or from separate supplies.  What you have drawn can burn up your Arduino.

Be sure to connect the grounds.

are you asking how a breadboard works?

Potentially - I haven't purchased a breadboard so if it's possible to connect the servo (powered externally by the plug pack) and the Arduino (powered by a USB cable) together without one that would be better. if possible ;D

From what I know, and what is said here, you connect the negative terminal of the power source to arduino ground, as well as the ground of the servo. Because both the power source, and the signal have to travel as 2 independent circuits.

Your question is not very concise, but I'll try to hit the main points.
I'm going with the assumption that your "Arduino" is the Sparkfun Redboard. The Redboard has a current limit of <800mA (heat management on the Redboard probably lowers this number even more), as per the LM1117 voltage regulator listed in the provided RedBoard schematic, and a minimum input voltage of 7V. You won't be able to power your Arduino with the 5V2A powerbrick. If you are powering the RedBoard through the standard USB, then it will typically be limited to 500mA.
Are you sure your servo has a no-load draw of 170mA? That's really high for a servo. If it does, then I'm assuming it's a large servo that likely has a high stall current draw, so 800mA from the Redboard's on-board regulator won't cut it, nor a USB port.
To power your servo externally, wire the servo and Redboard according to the schematic below. The power supply is indicative of your 5V 2A "wall wart". It's important to note that you need to connect the ground of the the power supply to the ground of the Arduino. For controlling the servo, check out Adafruit's servo tutorial. You will also need to provide power to your Arduino via USB or a DC barrel jack with a power brick that outputs >= 7v.

Would you please explain why it is necessary to connect the power supply ground to the arduino ground? Thank you.

If you don't have the ground connected to the Arduino, there is no return path for current meaning your signal wire is useless. Also, in order to measure voltage you need a reference point. If you have no ground or reference, it has no idea what the voltage you are supplying it with is, or high that voltage point is with respect to ground is. So you tie both grounds so they both have the same reference point and to provide a return path of current for your control wire (granted it's an insanely tiny amount, nevertheless still must be there)

I always thought that "ground" is "ground", so Arduino has its grounds connected to its own power supply, that whats confuses-me. Thanks

You did not indicate how you plan to connect the 5V, 2A mains plug pack to the Arduino board. If you want to use the barrel jack on the left, please note the listed input voltage. 5 volts is too low if you plan on powering the Uno board with the external power source. There is a voltage comparator circuit that will switch over to the barrel jack power if the voltage is high enough.
But since you are not really asking about powering the Uno, just the servo, then it gets interesting. The Sparkfun schematic shows a diode in line with the barrel connector and the Vin connection point on the board. This could provide a power path for the servo. The problem is that the servo voltage range 4.8 volts on the low end. With a 5 volt output of your external power supply, a voltage drop from the diode would give the servo almost enough voltage to meet the 4.8 volt minimum but not quite.
You are better off to not connect the servo power through the Uno board. If you had a somewhat higher voltage supply, at least 6 volts, then it would be ok. But if it is only 5 volts then it really is at a very marginal level.

Hey, thanks so much for answering.I'm all pretty new at this so if I clarify what I meant I'm not sure if that will actually help (let me know!).So I want to power the Arduino board using a USB cable (from a laptop to the Arduino's usb jack). The servo I am using draws too high a current to power it using the 5V pin on the Arduino,so I have been advised to buy a plug pack (the 5V, 2A one),strip the end of the cable and connect it's wires to the servo (in order to power the servo separately from an external source)
Basically my question is how do I connect the servo to the Arduino? Which pins?

https://www.arduino.cc/en/reference/servo

You need to make sure what is the positive wire and what is the negative wire. You then connect the negative wire of the power supply to the Black wire of the servo above. The positive of the power supply connects to the Red wire. The Yellow and Black wire also connect to the Uno board as you show above.


text:
How can I update a sketch to a NodeMCU “over the air” with the Arduino IDE?
I’m trying to use a sketch from this repository which uses MQTT to send a notification to Home-Assistant that acts a “presence sensor”.  When the NodeMCU comes into range of the specified SSID, the controller connects to WiFi and sends a MQTT message to home-assistant which can then perform some home automation commands.  This code does exactly that.  The MQTT messages are sent and received.
What is not working is that I can’t update the sketch over the air (OTA) via the included ArduinoOTA library. After uploading this sketch to the NodeMCU, it connects to WiFi and I am getting a message from the console output that the device is ready for OTA updates.  From everything that I’ve read I beleive there is supposed to be an option in the Arduino menus where I can specify that I want to update OTA instead of a com port.  How can I enable this in the IDE?  Also, is there a way to “connect” to the serial monitor so that I can also see the output OTA?
I’m attaching the sketch for your convenience:
////////////////////////////////////////////////////////////////////////////////////////////////////
// Modify these values for your environment
const char* wifiSSID = "wifissid";  // Your WiFi network name
const char* wifiPassword = "wifipassword";  // Your WiFi network password
const char* otaPassword = "myotapassword";  // OTA update password
const char* mqttServer = "192.168.1.2";  // Your MQTT server IP address
const char* mqttUser = ""; // mqtt username, set to "" for no user
const char* mqttPassword = ""; // mqtt password, set to "" for no password
const String mqttNode = "CarPresence"; // Your unique hostname for this device
const String mqttDiscoveryPrefix = "homeassistant"; // Home Assistant MQTT Discovery, see https://home-assistant.io/docs/mqtt/discovery/
////////////////////////////////////////////////////////////////////////////////////////////////////

// Home Assistant MQTT Discovery, see https://home-assistant.io/docs/mqtt/discovery/
// We'll create one binary_sensor device to track MQTT connectivity
const String mqttDiscoBinaryStateTopic = mqttDiscoveryPrefix + "/binary_sensor/" + mqttNode + "/state";
const String mqttDiscoBinaryConfigTopic = mqttDiscoveryPrefix + "/binary_sensor/" + mqttNode + "/config";
// And a sensor for WiFi signal strength
const String mqttDiscoSignalStateTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-signal/state";
const String mqttDiscoSignalConfigTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-signal/config";
// And a sensor for device uptime
const String mqttDiscoUptimeStateTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-uptime/state";
const String mqttDiscoUptimeConfigTopic = mqttDiscoveryPrefix + "/sensor/" + mqttNode + "-uptime/config";

// The strings below will spill over the PubSubClient_MAX_PACKET_SIZE 128
// You'll need to manually set MQTT_MAX_PACKET_SIZE in PubSubClient.h to 512
const String mqttDiscoBinaryConfigPayload = "{\"name\": \"" + mqttNode + "\", \"device_class\": \"connectivity\", \"state_topic\": \"" + mqttDiscoBinaryStateTopic + "\"}";
const String mqttDiscoSignalConfigPayload = "{\"name\": \"" + mqttNode + "-signal\", \"state_topic\": \"" + mqttDiscoSignalStateTopic + "\", \"unit_of_measurement\": \"dBm\", \"value_template\": \"{{ value }}\"}";
const String mqttDiscoUptimeConfigPayload = "{\"name\": \"" + mqttNode + "-uptime\", \"state_topic\": \"" + mqttDiscoUptimeStateTopic + "\", \"unit_of_measurement\": \"msec\", \"value_template\": \"{{ value }}\"}";

// Set the signal strength and uptime reporting interval in milliseconds
const unsigned long reportInterval = 5000;
unsigned long reportTimer = millis();

// Set LED "twinkle" time for maximum daylight visibility
const unsigned long twinkleInterval = 50;
unsigned long twinkleTimer = millis();

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <PubSubClient.h>

WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);

////////////////////////////////////////////////////////////////////////////////////////////////////
// System setup
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.begin(115200);

  Serial.println("\nHardware initialized, starting program load");

  // Start up networking
  setupWifi();

  // Create server and assign callbacks for MQTT
  mqttClient.setServer(mqttServer, 1883);
  mqttClient.setCallback(mqtt_callback);

  // Start up OTA
  if (otaPassword[0]) {
    setupOTA();
  }

  Serial.println("Initialization complete\n");
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Main execution loop
void loop() {
  // check WiFi connection
  if (WiFi.status() != WL_CONNECTED) {
    setupWifi();
  }

  // check MQTT connection
  if (!mqttClient.connected()) {
    mqttConnect();
  }

  // MQTT client loop
  if (mqttClient.connected()) {
    mqttClient.loop();
  }

  // LED twinkle
  if (mqttClient.connected() && ((millis() - twinkleTimer) >= twinkleInterval)) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    twinkleTimer = millis();
  }

  // Report signal strength and uptime
  if (mqttClient.connected() && ((millis() - reportTimer) >= reportInterval)) {
    String signalStrength = String(WiFi.RSSI());
    String uptimeTimer = String(millis());
    mqttClient.publish(mqttDiscoSignalStateTopic.c_str(), signalStrength.c_str());
    mqttClient.publish(mqttDiscoUptimeStateTopic.c_str(), uptimeTimer.c_str());
    reportTimer = millis();
  }

  // OTA loop
  if (otaPassword[0]) {
    ArduinoOTA.handle();
  }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions

////////////////////////////////////////////////////////////////////////////////////////////////////
// Handle incoming commands from MQTT
void mqtt_callback(char* topic, byte* payload, unsigned int payloadLength) {
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Connect to WiFi
void setupWifi() {
  Serial.print("Connecting to WiFi network: " + String(wifiSSID));
  WiFi.hostname(mqttNode.c_str());
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifiSSID, wifiPassword);

  while (WiFi.status() != WL_CONNECTED) {
    // Wait 500msec seconds before retrying
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected successfully and assigned IP: " + WiFi.localIP().toString());
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// MQTT connection and subscriptions
void mqttConnect() {
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.println("Attempting MQTT connection to broker: " + String(mqttServer));
  // Attempt to connect to broker, setting last will and testament
  if (mqttClient.connect(mqttNode.c_str(), mqttUser, mqttPassword, mqttDiscoBinaryStateTopic.c_str(), 1, 1, "OFF")) {
    // when connected, record signal strength and reset reporting timer
    String signalStrength = String(WiFi.RSSI());
    reportTimer = millis();
    String uptimeTimer = String(millis());
    // publish MQTT discovery topics and device state
    Serial.println("MQTT discovery connectivity config: [" + mqttDiscoBinaryConfigTopic + "] : [" + mqttDiscoBinaryConfigPayload + "]");
    Serial.println("MQTT discovery connectivity state: [" + mqttDiscoBinaryStateTopic + "] : [ON]");
    Serial.println("MQTT discovery signal config: [" + mqttDiscoSignalConfigTopic + "] : [" + mqttDiscoSignalConfigPayload + "]");
    Serial.println("MQTT discovery signal state: [" + mqttDiscoSignalStateTopic + "] : " + WiFi.RSSI());
    Serial.println("MQTT discovery uptime config: [" + mqttDiscoUptimeConfigTopic + "] : [" + mqttDiscoUptimeConfigPayload + "]");
    Serial.println("MQTT discovery uptime state: [" + mqttDiscoUptimeStateTopic + "] : " + uptimeTimer);
    mqttClient.publish(mqttDiscoUptimeConfigTopic.c_str(), mqttDiscoUptimeConfigPayload.c_str(), true);
    mqttClient.publish(mqttDiscoUptimeStateTopic.c_str(), uptimeTimer.c_str());
    mqttClient.publish(mqttDiscoBinaryConfigTopic.c_str(), mqttDiscoBinaryConfigPayload.c_str(), true);
    mqttClient.publish(mqttDiscoBinaryStateTopic.c_str(), "ON");
    mqttClient.publish(mqttDiscoSignalConfigTopic.c_str(), mqttDiscoSignalConfigPayload.c_str(), true);
    mqttClient.publish(mqttDiscoSignalStateTopic.c_str(), signalStrength.c_str());
    Serial.println("MQTT connected");
    digitalWrite(LED_BUILTIN, LOW);
  }
  else {
    Serial.println("MQTT connection failed, rc=" + String(mqttClient.state()));
  }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// (mostly) boilerplate OTA setup from library examples
void setupOTA() {
  // Start up OTA
  // ArduinoOTA.setPort(8266); // Port defaults to 8266
  ArduinoOTA.setHostname(mqttNode.c_str());
  ArduinoOTA.setPassword(otaPassword);

  ArduinoOTA.onStart([]() {
    Serial.println("ESP OTA:  update start");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("ESP OTA:  update complete");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    //Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.println("ESP OTA:  ERROR code " + String(error));
    if (error == OTA_AUTH_ERROR) Serial.println("ESP OTA:  ERROR - Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("ESP OTA:  ERROR - Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("ESP OTA:  ERROR - Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("ESP OTA:  ERROR - Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("ESP OTA:  ERROR - End Failed");
  });
  ArduinoOTA.begin();
  Serial.println("ESP OTA:  Over the Air firmware update ready");
}

Follow the instruction here https://arduino-esp8266.readthedocs.io/en/latest/ota_updates/readme.html#application-example
First load the OTA example specified. Do not waste your time implementing it in your code until you have the supplied example working.
If you are running Windows then it helps to have an application called Bonjour Browser. The OTA method makes use of mDNS. I use Bonjour Browser to confirm that the ESP is being seen. Then I go to ports in the IDE and there is an entry for the newly added OTA device.
Select the entry instead of the com ports. Then compile and upload.
If you get an error then do a power cycle on the ESP board. You should only need to do this once after the serial upload.
I use this method but sometimes the device does not appear below the com listed. I have had to close and restart the IDE to refresh the device listing. (I think this is a Windows issue) Because of this I prefer the webupdater method.
https://arduino-esp8266.readthedocs.io/en/latest/ota_updates/readme.html#web-browser

good answer Rudy. In Sloeber (Arduino Eclipse plugin) I can enter the IP address and must not relay on mDNS

of the available OTA methods, this one is the simplest imho.

Done this form a Linux laptop's command line.
For uploading to Arduino boards, I have been using (via the usual USB port connection) the command line methods as detailed at: https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc
For the OTA method of uploading to the ESP, I just chanced to discover the following method.
As the argument to "--port", I just used the ip of the wifi connected ESP board.
Let us say I want to upload a sketch "myexample1.ino" to my ESP8266 board "ESP-01 (1MB)" having OTA firmware on it. Am using Arduino 1.8.8 and ESP8266 community version 2.4.2. As already stated, the ESP-01 has the example sketch "BasicOTA.ino" uploaded to it via the usual USB port. Now, the ESP-01 is not connected via USB. It is connected to my wifi router at an ip (say, 192.168.22.221). The following command successfully uploaded the code:
~/Arduino/myexample1 $ arduino --upload myexample1.ino --port 192.168.22.221
Just felt like sharing a nice experience not found reported elsewhere on the internet.


text:
Global Variable does not Change when Value is set within Boolean Function
I have a boolean function which contains a string. In my main project this string is extracted from a website using an ESP8266 which is compatible with the Arduino IDE. I need to convert this string to a char* type of which is to be used in the loop() section of the code. The issue which I have faced is related to the setting of the mPass global variable, which does not change when it is done in the restoreConfig() Boolean function, meaning it remains blank when called for in the loop.
I do understand that this problem is related to the fact that I am defining the mPass within the Boolean function, however I am unsure as to the process in which I can change the global variable without errors.
I have tried resolving this problem through moving the mqttpass, mqttpasslen and mPass variables out of the restoreConfig() function, however it creates significantly more problems than that which I have at the moment. As a result I have only presented the code without any adjustment below:
char* mPass = "";

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

void loop() {
  if (restoreConfig()) {
    Serial.println(mPass);
    Serial.println("ABOVE IS mPass IN LOOP");
  }
  delay(1000);
}

boolean restoreConfig() {
  String mqttpass = "DOGS";
  int mqttpasslen = mqttpass.length() + 1;
  char mPass[mqttpasslen];
  mqttpass.toCharArray(mPass, mqttpasslen);
  Serial.println(mPass);
  Serial.println("ABOVE IS mPass IN BOOLEAN");
  return true;
}

My current output from this is:
DOGS
ABOVE IS mPass IN BOOLEAN

ABOVE IS mPass IN LOOP

You have local variable mPass in the function restoreConfig. It 'shadows' the global variable.

Hi @Juraj, I do understand that this is the case and have since uncommented the local variable mPass, however now my output does not show anything but blank. If I attempt to move char mPass[mqttpasslen], then I have the issue that then mqttpasslen is undefined. Do you have any suggestions as to the way I can resolve this?

the global variable is only a pointer. change it to array to allocate space.