// https://wokwi.com/projects/409959676011130881
// Code from https://forum.arduino.cc/t/serial-input-basics-updated/382007/2#example-4-receiving-a-single-number-from-the-serial-monitor-2
// Other simulations https://forum.arduino.cc/t/wokwi-simulations-for-arduino-built-in-examples/1304754
/*
Example 4 - Receiving a single number from the Serial Monitor
So far the examples have assumed you want to receive text. But
perhaps you want to send a number or maybe a mix of text and numbers.
The simplest case is where you want to type a number into the
Serial Monitor (I am assuming you have line-ending set to newline).
Let's assume you want to send the number 234. This is a variation
on Example 2 and it will work with any integer value. Note that if
you don't enter a valid number it will show as 0 (zero).
*/
// Example 4 - Receive a number as text and convert it to an int
const byte numChars = 32;
char receivedChars[numChars]; // an array to store the received data
boolean newData = false;
int dataNumber = 0; // new for this version
void setup() {
Serial.begin(9600);
Serial.println("<Arduino is ready>");
}
void loop() {
recvWithEndMarker();
showNewNumber();
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '\n';
char rc;
if (Serial.available() > 0) {
rc = Serial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewNumber() {
if (newData == true) {
dataNumber = 0; // new for this version
dataNumber = atoi(receivedChars); // new for this version
Serial.print("This just in ... ");
Serial.println(receivedChars);
Serial.print("Data as Number ... "); // new for this version
Serial.println(dataNumber); // new for this version
newData = false;
}
}