Hi, new to coding and hope to get some help. Here is the code provided to me:
int readIntFromSerialWithEnter() {
byte ndx ;
const char endMarker = '\n';
const byte numChars = 32 ;
char receivedChars[numChars] ;
char rc;
ndx = 0 ;
while ( true) { // loop forever until a return breaks out of function
while(Serial.available() == 0) ; // hang waiting on next serial data
rc = Serial.read(); // read the next char
if (rc != endMarker) { // if enter was not pressed
receivedChars[ndx] = rc; // add the char to the string array
ndx++; // increment the index into the array
if (ndx >= numChars) ndx = numChars - 1; // this is a hack way of preventing overflow of char array
}
else { // enter was pressed
receivedChars[ndx] = '\0'; // terminate the string
return atoi(receivedChars) ; // convert to integer and return
}
}
}
/* ****************************************************************************************** */
void setup() {
Serial.begin(9600); // set serial port up, use 9600 bps
}
void loop() {
int val ; // this is the integer that the read integer is returned to
Serial.println("Enter a number in the box on the serial monitor.") ; // this prompts for the user to enter a number
val=readIntFromSerialWithEnter() ;
Serial.print("The integer you entered is ") ;
Serial.println(val) ;
The code provided waits for an integer to be entered in the serial monitor and outputs the exact integer. My goal is to modify the loop code so that every time an integer is entered, a count of the number of integers entered so far, a running sum, and the average (sum/count) is the output. For example, suppose the number 3, 6, 9 have been entered so far, I should get count=3, sum=18, average=6 as my output.
I tried declare int count and int sum inside void loop and do count=++count and sum=sum+=val, but it doesn't seem to work. Any help is appreciated and thank you for your time.