Arduino with pushbutton

Specifically, write a sketch that prints the on/off durations of pushbutton input to the serial port. The output format should be separate lines of the format " ", where value is “1” when the button is pushed and “0” when it is not, and duration is the time duration of that state in milliseconds. You should print the previous state every time the state changes.

For example, if you press the button for one second, then release it for two seconds, then press it for five seconds, then release it again, the output shown on Serial Monitor should be:

1 1000
0 2000
1 5000

You can use the millis() function to get the current time in milliseconds since bootup, which will allow you to calculate the durations.

Are you assigning us homework? Is this a test? Post the code that YOU have written and we can help you fix it if it is not giving you what you expect.

@OP

Convert the following steps into codes; post them; we will help you to correct/modify these codes.

1. Connect a button at DPin-2 with external 2.2k pull-down resistor.

2. Set the direction of DPin-2 as input.

3. Write code to check that button has been closed.

4. If Step-3 is true, send 1 to Serial Monitor.

5. Insert delay for 1-sec.

6. After the delay, send a space to serial Monitor and then send 1000 to Serial Monitor.

7. Write code to check that button is open; if so, send 0 and space to Serial Monitor.

...... and then ..........

Do not insert a delay when you are measuring when you are measuring how long a button has been pressed/released for.

Metallor: Do not insert a delay when you are measuring when you are measuring how long a button has been pressed/released for.

It is always good to know the reason with the opinion; it develops confidence. The poster is (looks like) a beginner, and let him proceed with simple thing among the resources that we have. There should be a way to account the 1-sec elapsed time -- used delay() or millis() function of the Arduino or TC1 of the MCU

OP has transcribed assigned homework to their one and only post. If anyone posts a sketch that does exactly what the assignment asks for, they will copy it and hand in your work.