Report Number of Key Clicks During Timer

I am currently trying to get my program to print how many times ‘a’ is pressed while the timer counts to 2000ms. So far, all I can get printed is some wildly larger number than how many times I pressed ‘a’.
It says anywhere from 90 to 120 even when I only click 3 or 4 times.

Is there a problem in my draw function?

<// The duration of the time
int timerDuration = 2000;

//The time at which we start the timer
int startTime = 0;

// Whether or not the timer was started
boolean timerState = false;

int aVal;

void setup() {
size(200, 200);
aVal = 0;

void draw(){

if (timerState) {
//We subtract the current time and the time when we startedt he timer
int currentDuration = millis() - startTime;

fill (0);
textAlign(CENTER, CENTER);
text(currentDuration, width /2, height /2);

if (key == ‘a’) {

//If the event is over
if (currentDuration > timerDuration) {
timerState = false;
println("‘a’ pressed “, aVal, " times”);
aVal = 0;

void mousePressed() {
startTime = millis();
timerState = true;

Yes your count goes up every time the draw loops and the a key was pressed.
Maybe even if it was the last key that was pressed.
You need to look into the keyPressed()/keyReleased() functions.
These only get triggered once and are independent of the draw loop.

Please use the code button when you post code, it makes it easier to read.

So the chunk of code currently located in draw() would function normally in the keyPressed() function? I’ll give that a try.


move this into a function

void keyPressed() {

1 Like