Response redundance from serial !

Hi everybody,

I wrote a simple sketch, an ask-for-the-num game ( you have to find out the num randomly choosen by Arduino ); the player enters his proposals through serial.

int mystere;//GLOBALE CAR INITIALISÉE DANS SETUP ET UTILISÉE DANS LOOP

void setup() {

	Serial.begin(9600) ;
	randomSeed(analogRead(5)); //initialisation générateur "aléatoire"
        mystere = int(random(1,101)) ; //tirage d'un entier entre 0 et 100 NON INCLUS

}

void loop() {
     
	int proposition ;
     
	while ( Serial.available() == 0) {  //boucle qui attend que la liaison série ne soit pas vide
	}
        
	proposition = Serial.parseInt() ; //récupération du nombre proposé par le joueur

	//évaluation de la réponse

	if ( proposition > mystere ) {
		Serial.print(proposition);
		Serial.println( " : Trop grand !") ;
	}

	else if ( proposition < mystere ) {
		Serial.print(proposition);
		Serial.println(" : Trop petit !") ;
	}

	else if ( proposition == mystere ) {     // OU : else { } suffit !!
		Serial.println("Gagné !") ;
	}

}

The sketch works, except it returns two sentences ( it's designed to write back only one... ) :

  • the reply to the player according to his proposal ( "Too high", "too low", "won !! " )
  • another reply, always the same, as if the player enters the "0" number...

( see attached picture )

I tried to temporize the sketch, suspecting unsuitable timing...but no success !

Any advice ?

Thanks !!

Chris

Capture du 2012-09-02 17:01:35.png

        mystere = int(random(1,101)) ; //tirage d'un entier entre 0 et 100 NON INCLUS

Your comment is wrong. The random() function, with those arguments does not return a value between 0 and 100.

What is sending data to the Arduino? If it is the Serial Monitor, what line ending setting (lower, right corner) are you using?

Edit: Never mind. I looked at your picture. It appears that the Serial Monitor is adding a carriage return to the string entered. Change that to nothing appended to the string to get rid of the duplicate response.

If you are sending lines from a Windows machine they may end in CRLF ("/r/n"). Serial.parseInt() may see that as two line endings. The second line ending would be for an empty line so the numerical value would always be zero.

I don't see any easy way to fix the problem. If you always throw away a character after parseInt() it will fail a different way with a non-Windows host.

Edit: Never mind. I looked at your picture. It appears that the Serial Monitor is adding a carriage return to the string entered. Change that to nothing appended to the string to get rid of the duplicate response.

That was it !! Shame on me, I could have find it by myself with a little care :-((

Thank you very much for pointing it !

But what do you mean by "my comment is wrong ?"

EDIT : never mind, I found it ( heedless again :cold_sweat: ); the num range is 1 -100 INCLUDED, not 0-100 ....

Thanks again !