Serial Display Gives Unreliable Results

Hello,

I have run the code below in my set-up and i am measuring the response time after pushing a button. I have done this a couple of times and i have come to realize that even when i dont press the button, the serial display still produces a value which made me realize that my values may not be reliable. I need assistance on how to address this for an on-going project activity at my university.

The code is as below;

int buttonPin=10;
int greenLed=9;
long time1=0;
long time2=0;
long int reactionTime=0;
int buttonState=0;
long ranDelay=0;
void setup() {
// put your setup code here, to run once:
pinMode(greenLed,OUTPUT);
pinMode(buttonPin,INPUT);
Serial.begin(9600);
Serial.println("subject1");
}

void loop() {
// put your main code here, to run repeatedly:

buttonState=0;
digitalWrite(greenLed,HIGH);
time1=millis();
time2=time1;
while(buttonState==LOW){
buttonState=digitalRead(buttonPin);
time2=millis();}
digitalWrite(greenLed,LOW);

reactionTime=time2-time1;
Serial.print("reaction time");
Serial.println(reactionTime);
ranDelay=random(1,6);
delay(ranDelay*1000);
}

Your assistance in this regard will be highly appreciated

Since this is a uni project you really ought to work it out for yourself!

Try writing the desired behaviour of the software in pseudo code (plain English statements), then translate this into C code.

Circuit wise you will need a pull up resistor on your switch and may need to consider switch bounce.

Hello,

I am not really good at any programming language and i seek for your clarification on exactly what you meant that i need to "switch bounce."

kasozi:
Hello,

I am not really good at any programming language and i seek for your clarification on exactly what you meant that i need to "switch bounce."

Generally Google has an answer:

Whether this is important depends on your code.

kasozi:
I am not really good at any programming language and i seek for your clarification on exactly what you meant that i need to "switch bounce."

Another explanation further down on Google.