Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Measure user response time using getch() funtion.
#include <termios.h>
#include <stdio.h>
#include<time.h>
#include<stdlib.h>
static struct termios old, new;
/* Initialize new terminal i/o settings */
void initTermios(int echo)
{
tcgetattr(0, &old); /* grab old terminal i/o settings */
new = old; /* make new settings same as old settings */
new.c_lflag &= ~ICANON; /* disable buffered i/o */
new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}
/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
/* Read 1 character without echo */
char getch(void)
{
return getch_(0);
}
/* Read 1 character with echo */
char getche(void)
{
return getch_(1);
}
/* Let's test it out */
int main(void) {
int i;
double elapsed[3];
struct timeval begin, end;
for(i=0; i<3; i++){
srand(time(NULL));
int ranTime = rand()%3+1;
int ranNum = rand()%10;
char ranCha = (char)(((int)'0')+ranNum);
char c;
printf("\nWait 1 to 3 seconds & enter the diplayed number...\n");
sleep(ranTime);
printf("%d\n", ranNum);
gettimeofday(&begin, NULL);
while(1){
c = getche();
if(c==ranCha){
printf("\t(Correct)\n");
break;
}
else printf("\t(Try again)\n");
}
gettimeofday(&end, NULL);
elapsed[i] = (end.tv_sec - begin.tv_sec) +
((end.tv_usec - begin.tv_usec)/1000000.0);
//printf("You spent %f seconds\n", elapsed[i]);
}
printf("\n________Summary_______\n");
double minTime = elapsed[0];
double maxTime = elapsed[0];
if(elapsed[1]<minTime) minTime = elapsed[1];
if(elapsed[2]<minTime) minTime = elapsed[2];
if(elapsed[1]>maxTime) maxTime = elapsed[1];
if(elapsed[2]>maxTime) maxTime = elapsed[2];
printf("Minimum Time: %f\n", minTime);
printf("Maximum Time: %f\n", maxTime);
printf("Average Time: %f\n\n", (elapsed[0]+elapsed[1]+elapsed[2])/3);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment