Single chip microcomputer realizes the operation of long press 3s and long press 10s for the same key

Keywords: less

How to realize single-chip click, double-click and long press operation can refer to other people's articles: https://blog.csdn.net/qq997758497/article/details/80606710

Here, I mainly extend this function to realize the operation of click, double-click, long press for 3s and long press for 10s.

What needs to be revised:

 

1. Predefined:

//#Define key? Long? 3 3 comment this line of code
 #Define key? Long? 3s 3 / / return value, long press 3s
 #define key_long_10s 4 / / return value, long press for 10s

#Define key? State? 4 4 / / define a new state value

2. Modify the key driver() function:

unsigned char key_driver(void)
{

	unsigned char key_return = key_no;
	
	
	key1 = ((keys_flag)&(0x00080000));//key_input;  //read the I/O states
	
	switch(key_state_buffer1)
	{
		case key_state_0:
			if(key1 == KeyOn())
				key_state_buffer1 = key_state_1; 
				//When the key is pressed, the status changes to the key shake elimination and confirmation status//
			break;
			
		case key_state_1://Elimination of trembling
			if(key1 == KeyOn())
			{
				key_timer_cnt1 = 0;
				key_state_buffer1 = key_state_2;
				//The key is still pressed at this time
				//After the buffeting is completed, the key ﹐ timer ﹐ cnt1 will start timing / / 10ms self adding once
				//State switch to press time start timing state
			}
			else
				key_state_buffer1 = key_state_0;
				//If the key is lifted and released, the key status will return to the initial status
			break; //Software buffeting
			
		case key_state_2:
			if(key1 == KeyOff()) 
			{
				key_return = key_click;  //If the key is lifted and released, complete one click (short press) operation
				key_state_buffer1 = key_state_0;  //Switch to the initial state of the key
			}
			else if(++key_timer_cnt1 >= 300)  //If the key is in the state of continuous pressing, when the time counter exceeds 3s
			{
				key_state_buffer1 = key_state_3;  //Wait for the key release after long press
			}
			break;
			
		case key_state_3:
			{
				if( key1 == KeyOn() && ++key_timer_cnt1 >= 1000)//Press the key to continue to press, the timing is more than 10s
				{
					key_return = key_long_10s; //Send back the event of long press 10s
					key_state_buffer1 = key_state_4;  //Waiting for release
				}
				if( key1 == KeyOff() && key_timer_cnt1 <1000 ) //Release the key, and the timing is less than 10s
				{
				 	key_return = key_long_3s;
					key_state_buffer1 = key_state_0;
				}
			 
			}
			break;
		case key_state_4:  //Wait for key release
			if(key == KeyOff())  //Key release
				key_state_buffer1 = key_state_0;  //Switch back to the initial state of the key
			break;


	}

	return key_return;
}

Note that the definition of key ﹣ timer ﹣ cnt1 needs to be modified to the type of unsigned int, otherwise the count value will not exceed 255

Posted by Mahfouz on Tue, 19 Nov 2019 14:06:30 -0800