本文主要是介绍keil5(矩阵按键控制电机转速),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
简单应用:
按下矩阵按键,切换模式
S2:显示功能,且清零
S5:转速加一
S6:转速减一
S7:转速加四
S8:转速减四
注意:此代码有防伪,谨慎拷贝
代码仍存在一些问题,时间原因已放弃更改!!!
代码如下:
main.c
#include <REGX52.H>
#include "Delay.h"
#include "Timer0.h"
#include "MatrixKey.h"
#include "LCD1602.h"sbit Motor=P1^0;unsigned char Counter; //计数值和比较值,用于输出PWM
unsigned char KeyNum,Speed;
unsigned char Speed=0;
void main()
{Timer0Init();LCD_Init();LCD_ShowString(1,1,"Author:SYP");LCD_ShowString(2,1,"Project-3");while (1){KeyNum=MatrixKey();if(KeyNum==KeyNum){if(KeyNum==2){Speed=0;LCD_Init();LCD_ShowString(1,1,"Mood:Start");LCD_ShowString(2,1,"5< 6> 7^ 8v");}if(KeyNum==5){++Speed;LCD_Init();LCD_ShowString(1,1,"Mood: < 1");LCD_ShowNum(2,1,Speed,3);if(Speed>=101){Speed=0;LCD_ShowNum(2,1,Speed,3);}}if(KeyNum==6){--Speed;LCD_Init();LCD_ShowString(1,1,"Mood: > 1");LCD_ShowNum(2,1,Speed,3);if(Speed>=101){Speed=0;LCD_ShowNum(2,1,Speed,3);}}if(KeyNum==7){Speed+=4;LCD_Init();LCD_ShowString(1,1,"Mood: ^ 4");LCD_ShowNum(2,1,Speed,3);if(Speed>=101){Speed=0;LCD_ShowNum(2,1,Speed,3);}}if(KeyNum==8){Speed-=4;LCD_Init();LCD_ShowString(1,1,"Mood: v 4");LCD_ShowNum(2,1,Speed,3);if(Speed>=101){Speed=0;LCD_ShowNum(2,1,Speed,3);}}}}
}void Timer0_Routine() interrupt 1
{TL0 = 0x9C; //设置定时初值TH0 = 0xFF; //设置定时初值Counter++;Counter%=100; //计数值变化范围限制在0~99if(Counter<Speed) //计数值小于比较值{Motor=1; //输出1}else //计数值大于比较值{Motor=0; //输出0}
}
MatrixKey.c
#include <REGX52.H>
#include "Delay.h"/*** @brief 矩阵键盘读取按键键码* @param 无* @retval KeyNumber 按下按键的键码值如果按键按下不放,程序会停留在此函数,松手的一瞬间,返回按键键码,没有按键按下时,返回0*/
unsigned char MatrixKey()
{unsigned char KeyNumber=!KeyNumber;P1=0xFF;P1_3=0;if(P1_7==0|P1_7==1){Delay(20);while(P1_7==0);Delay(20);KeyNumber=1;}if(P1_6==0){Delay(20);while(P1_6==0);Delay(20);KeyNumber=5;}if(P1_5==0){Delay(20);while(P1_5==0);Delay(20);KeyNumber=9;}if(P1_4==0){Delay(20);while(P1_4==0);Delay(20);KeyNumber=13;}P1=0xFF;P1_2=0;if(P1_7==0){Delay(20);while(P1_7==0);Delay(20);KeyNumber=2;}if(P1_6==0){Delay(20);while(P1_6==0);Delay(20);KeyNumber=6;}if(P1_5==0){Delay(20);while(P1_5==0);Delay(20);KeyNumber=10;}if(P1_4==0){Delay(20);while(P1_4==0);Delay(20);KeyNumber=14;}P1=0xFF;P1_1=0;if(P1_7==0){Delay(20);while(P1_7==0);Delay(20);KeyNumber=3;}if(P1_6==0){Delay(20);while(P1_6==0);Delay(20);KeyNumber=7;}if(P1_5==0){Delay(20);while(P1_5==0);Delay(20);KeyNumber=11;}if(P1_4==0){Delay(20);while(P1_4==0);Delay(20);KeyNumber=15;}P1=0xFF;P1_0=0;if(P1_7==0){Delay(20);while(P1_7==0);Delay(20);KeyNumber=4;}if(P1_6==0){Delay(20);while(P1_6==0);Delay(20);KeyNumber=8;}if(P1_5==0){Delay(20);while(P1_5==0);Delay(20);KeyNumber=12;}if(P1_4==0){Delay(20);while(P1_4==0);Delay(20);KeyNumber=16;}return KeyNumber;
}
MatrixKey.h
#ifndef __MATRIXKEY_H__
#define __MATRIXKEY_H__
unsigned char MatrixKey();#endif
ps:框起来的代码在这里
点击这里,获取剩余文件
总结
keil5+c语言实现用中断实现矩阵键盘控制点击且在LCD上显示占空比。
注意:LCD602模块非本人编写,只为方便调试
这篇关于keil5(矩阵按键控制电机转速)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!