arduino keeps printing over and over to the serial monitor

hy guys i am trying to make a code that stores data to eeprom if you type (write 3 1) it will save 1 in the address 3 and if you type (read 3) it will type the content wich is 1 everything is going great but thers a slight problem for example if i save a value to the eeprom and then request it on the serial monitor it keeps printing that value over and over and i want it to be printed once what modifications should i make on the code

#include <EEPROM.h>
int b,i,address,value,memval;
String input="",add="",val="";
char wr[17];


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

}


void loop() {  

while(Serial.available()){input=Serial.readString();} 



b=input.length();
//Serial.print(b);
//Serial.print("\n");

input.toCharArray(wr, b+1);

char *token =strtok(wr, " ");
i=0;
while(token != NULL)
{
i++;
token = strtok(NULL, " ");
if (i==1) add=token; 
if (i==2) val=token;
}

address=add.toInt();
value=val.toInt(); 


if (wr[0]=='w') { EEPROM.write(address, value); Serial.print("---value is saved---");Serial.print("\n");}
if (wr[0]=='r') { memval = EEPROM.read(address);Serial.print(" value : ");Serial.print(memval);Serial.print("\n");}

}

First you should re-think this piece of code - it may not work as you want it to since it does not read until a linebreak, but until there is no more to read and "input" will hereafter be the last chunk received:

while(Serial.available()){input=Serial.readString();}

Second, you should re-thing this piece of code - it makes no sense:

char *token =strtok(wr, " ");
i=0;
while(token != NULL) //Will only loop once
{
i++;
token = strtok(NULL, " "); //token == NULL after this call, loop finished
if (i==1) add=token; //This will always happen
if (i==2) val=token; //This will never happen
}

the second code actually works fine it devides the char array into two parts with the strtok funct
and can you please explain more that first line of code and thnks

mansouri:
the second code actually works fine it devides the char array into two parts with the strtok funct and can you please explain more that first line of code and thnks

It cannot work properly, token of NULL is NULL. Also, you must clear "wr[0]" (eg. set it to ' ') before you call "toCharArray" or else "wr[0]" may contain last loops value causing the same task to be performed endlessly.

EDIT: Sorry, the usage of strtok in your code is valid - I was wrong about that :slight_smile:

i will redo that and fix my code thnks for clearing things up

I was wrong about the way strtok works, but you should consider not to use it and read each token directly, like this:

String cmd, addr, val;
...
void loop() {
  cmd="";
  if (Serial.available()) {
    cmd = Serial.readStringUntil(' ');
    addr = Serial.readStringUntil(' ');
    val = Serial.readStringUntil('\n');
  }
  //Convert the tokens and proceed
}

You should also consider not to use String at all.