Push button question

Hi, i'm working on measuring time duration with a push button. For example, when i press the push button for 1 second, the output should be 1 1000 which is format of " ". Likewise, when i press the button for 2 seconds and release it for 5 seconds, and then push it again for 2 seconds, the output should look like

1 2000
0 5000
1 2000

Here's my code i'm working on and it only shows when i press the button, not release it. Please help me with this problem. Thank you

const int buttonPin = 5;
int buttonState = 0;
int lastButtonState = 0;
int startPressed = 0;
int endPressed = 0;
int timeHold = 0;
int timeReleased = 0;

void setup() {
pinMode(buttonPin, INPUT);
Serial.begin(115200);
}

void loop() {

buttonState = digitalRead(buttonPin);

if (buttonState != lastButtonState) {

if (buttonState == HIGH)
{
startPressed = millis();
timeReleased = startPressed - endPressed;

if (timeReleased >= 1000)
{
timeReleased = timeReleased - (timeReleased%1000);
Serial.print("0 ");
Serial.println(timeReleased);
timeReleased = 0;
}
}

if (buttonState == LOW)
{
endPressed = millis();
timeHold = endPressed - startPressed;

if (timeHold >= 1000)
{
timeHold = timeHold - (timeHold%1000);
Serial.print("1 ");
Serial.println(timeHold);
timeHold = 0;
}
}
}
lastButtonState = buttonState;
}

part5.ino (1.12 KB)

You have contact bounce. Change ">= 1000" to ">= 0" to see it.

You should not update the released/hold timers until after testing for the minimum time.