Friday, June 12, 2020

String inputs Over Serial on ESP8266

Current issue: I'm trying to be able to enter my SSID and password over serial (so I can avoid committing that info to Git). If I hardcode the SSID and password, say mySSID and myPassword as a string object, I can connect. But if I try to type it over serial, it doesn't work. The ESP8266 uses both NL and CR for serial communication, so my current hypothesis is that it's probably an issue with that.

This happened the same whether I use Serial.readString() or Serial.readStringUntil('\n'). I could immediately tell that Serial.readString() didn't work because there was a visible newline.

Thinking there might be a character I missed (though it wasn't '\r' either), I added the following code to get the exact string:


When I enter mySSID as Serial.readString(); I get the following hex back:
6D7953534944DA0EFEF80FEEFEFFE
Which after converting to ASCII with this website, returns
mySSIDÚ þø îþÿ

If I enter mySSID as Serial.readStringUntil('\n'); I get the following hex back:
6D7953534944D0FEEFEF80FEEFEFFE
And convert to ASCII returning
mySSIDÐþïï€þïïþ

Two things I notice. First off, readString returns an odd number of nibbles. readStringUntil returns an even number of nibbles, so I have complete bytes. This certainly seems odd, but I couldn't tell you the significance.

Even more substantially (I think), there is a 0xD right after mySSID with both read methods. If there was a 0x0 between mySSID and 0xD, I would get a \n character and boom! Problem solved. So seems like maybe it's somehow getting dropped somewhere? I'll have to further investigate.

Update 2020-06-13

I guess I actually hadn't used Serial.readStringUntil('\r'). It's possible I had done something silly like specifying only 'r'.

At this point, I could connect by typing in my SSID and hardcoding the password. But because of... something it was bypassing the prompt for password. I think because it was picking up an extra garbage \n and \r from my input. So now to flush the input. Serial.flush() seems good!

Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)
 
Oh... Ok. This is fine.
 
First I tried
while (Serial.available()) {Serial.read();}

But no dice. Finally I figured out I guess it's not enough to read, you have to do something with that read data. Leading me to the code below.

String serialTrash;
do
{
    serialTrash = Serial.read();
} while (Serial.available() > 0);

Success!

References

  1. Topic: converting string to hex (the non-rude, actually helpful posts)