- #include "reg52.h" // 此文件中定义了单片机的一些特殊功能寄存器
- typedef unsigned int u16; // 对数据类型进行声明定义
- typedef unsigned char u8;
- // 是否是前进
- bit isFoward = 0;
- // 是否后退
- bit isBack = 0;
- // 控制行驶电机
- sbit EN_A = P0^0;
- sbit IN_A1 = P0^1;
- sbit IN_A2 = P0^2;
- sbit IN_B1 = P0^3;
- sbit IN_B2 = P0^4;
- sbit EN_B = P0^5;
- // 是否行使总开关
- bit ALL_EN = 0;
- u8 speedNum = 10;
- // 步进电机转动
- int harfMotoNum = 10;
- int currentMotoNum = 15;
- sbit r_pwm = P3^7;
- void initFunc(){
- P0 = 0x00;
- // 首先设置 TMOD 工作方式
- TMOD = 0x21;
- PCON = 0x00;
- SCON = 0x50;
- // 计算初始值设定
- TH1 = 0xFD;
- TL1 = 0xFD;
- // 打开
- TR1 = 1;
- // 打开串口中断
- ES = 1;
- TH0=0XFF; // 给定时器赋初值, 定时 1ms
- TL0=0XA3;
- ET0=1;// 打开定时器 0 中断允许
- EA=1;// 打开总中断
- TR0=1;// 打开定时器
- }
- void checkRun(){
- if(isFoward){
- EN_A = ALL_EN;
- IN_A1 = 0;
- IN_A2 = 1;
- } else if(isBack){
- EN_A = ALL_EN;
- IN_A1 = 1;
- IN_A2 = 0;
- }
- else{
- EN_A = ALL_EN;
- IN_A1 = 0;
- IN_A2 = 0;
- }
- }
- u8 motoDriveRecord = 0;
- bit motoNeedRun = 0;
- void main()
- {
- initFunc();
- while(1)
- {
- checkRun();
- }
- }
- u8 systemCount = 0;
- u8 row = 0;
- u8 colum = 0;
- u8 judgeNum = 0;
- bit leftOrRight = 0; // 旋转方向, 0 左, 1 右
- void Timer0() interrupt 1
- {
- TH0=0XFF; // 给定时器赋初值, 定时 1ms
- TL0=0XA3;
- /*********************** 定时器控制 PWM 调速 **************************/
- /* (/0)(/1)(/2)(/3) (/19)
- (%0) 0 5 10 15 ... 95
- (%1) 1 6 11 16 ... 96
- (%2) 2 7 12 17 ... 97
- (%3) 3 8 13 18 ... 98
- (%4) 4+ 9+ 14+ 19+ ... 99
- */
- if(systemCount>= 1000)
- systemCount = 0;
- row = ((systemCount/10) % 5);// 这时候取值是 0,1,2
- colum = (systemCount/10) / 5;// 取值为 0-19;
- judgeNum = row * 20 + colum;
- if(judgeNum <speedNum){
- ALL_EN = 1;
- }else{
- ALL_EN = 0;
- }
- /*********************** 舵机控制 **************************/
- if((systemCount%200) == 0){
- r_pwm = 1;
- }
- if((systemCount%200)>= currentMotoNum){
- r_pwm = 0;
- }
- systemCount++;
- }
- // 中断事件
- u8 receivedData;
- u8 operation;
- void Usart() interrupt 4
- {
- if(RI == 1) { // 如果收到.
- // 定义一个变量, 接收数据
- receivedData = SBUF;
- if (receivedData == 101){
- // 前进
- isFoward = 1;
- isBack = 0;
- ALL_EN = 1;
- }else if(receivedData == 102){
- // 后退
- isFoward = 0;
- isBack = 1;
- ALL_EN = 1;
- }else if(receivedData == 103){
- // 停止
- isFoward = 0;
- isBack = 0;
- ALL_EN = 0;
- }else if(receivedData == 104){
- // 调整行驶速度
- operation = receivedData;
- }else if(receivedData == 105){
- // 调整方向
- operation = receivedData;
- }else if(receivedData == 106){
- // 校准方向
- currentMotoNum = harfMotoNum + 5;
- }else if(receivedData <= 100){
- if(operation == 104){
- if(receivedData>= 0 && receivedData <= 100){
- speedNum = receivedData;
- }
- }else if(operation == 105){
- if(receivedData>= 0 && receivedData <= harfMotoNum * 2){
- currentMotoNum = receivedData + 5;
- }
- }
- }
- RI = 0;
- }
- }
来源: http://www.bubuko.com/infodetail-2971338.html