I'm trying to use std::cin and std::cout with the ESP32. cout seems to work fairly well, but whenever I try to use cin for user input, it just seems to time-out immediately, without updating the variable I'm trying to cin to.
Here's a fairly simple program that illustrates my problem. (This is Listing 2.6 in the book "Sams Teach Yourself C++ in One Hour a Day", 9th edition - but modified for the Arduino setup() & loop() structure.)
#include <iostream>
#include <string>
using namespace std;
void setup() {
Serial.begin(115200);
Serial.setTimeout(LONG_MAX); // Wait for input essentially forever
// Declare a variable to store an integer
int inputNumber;
cout << "Enter an integer: ";
// store integer given user input
cin >> inputNumber;
// The same with text i.e. string data
cout << "Enter your name: ";
string inputName;
cin >> inputName;
cout << inputName << " entered " << inputNumber << endl;
}
void loop() {
}
The code compiles fine, but when I run it, the following appears on the Serial Monitor, with no time for me to enter anything.
Enter an integer: Enter your name: entered 0
I know there is a library ArduinoSTL, but it doesn't support the ESP32.
I suspect that 'cin' has a timeout, like Serial.parseInt() or Serial.readString(). Does the library give you a way of knowing if there is data in the input buffer (like Serial.available())?
In a "normal" implementation (like running on a PC with keyboard and screen), I don't think there's any timeout, although, it sure seems like there might be a need for one. But since cin and cout are connected to Serial in the Arduino implementation, I agree with you that there seems like there would be a timeout, that's why I have a Serial.setTimeout(LONG_MAX); call at the beginning of setup().
Where should I look in the library for information about a timeout or input buffering? I assume you're telling me to look in iostream, but how do I do that?
I have no idea. I found the 'iostream' file and it creates eternal references for 'cin'. 'cout', 'cerr', and 'clog'. I expect the C++ Runtime Library is not dependent on the Arduino library o it ha nothing to do with 'Serial'. Probably based on some I/O driver for the OS.
I'm just guessing might be causing the symptoms you see.
For Arduino, there really isn't one.
cin is for programs that run in the shell, console, or command prompt on your computer.
The programming language for Arduino is a slightly enhanced/simplified version of C++, and C++ has many applications beyond Arduino. There are a few things in C++ that don't work on Arduino.
There's a lot more too it but that's a simplified way to say it.