Last active
August 29, 2015 14:04
-
-
Save kaleocheng/5511301d16cf9b9dd284 to your computer and use it in GitHub Desktop.
PWM调速和光电传感器测速
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<reg52.h> | |
#include<stdio.h> | |
#define uchar unsigned char | |
#define uint unsigned int | |
#define KongNums 20 //码盘上孔的数量 | |
#define HighTime 500 //高电平持续时间 | |
#define LowTime 500 //低电平持续时间 | |
sbit Kong = P0^0; //是否有孔 | |
sbit led1 = P1^0; //LED指示灯 | |
sbit LeftInc = P2^0; | |
sbit LeftInd = P2^1; | |
sbit LeftEn = P2^2; | |
sbit RightIna = P2^3; | |
sbit RightInb = P2^4; | |
sbit RightEn = P2^5; | |
uint num = 0; //计数器 | |
uint testnums = 0;//检测到的经过的孔的数量 | |
uint speed = 0;//速度 | |
//左右电机的控制 | |
void drive(void){ | |
//LeftInc = 1; | |
//LeftInd = 0; | |
//LeftEn = 1; | |
RightIna = 0; | |
RightInb = 1; | |
RightEn = 1; | |
} | |
void delayms(uint xms){ | |
uint i,j; | |
for (i = xms; i > 0; i--){ | |
for (j = 110; j > 0; j--); | |
} | |
} | |
//初始化串口(52单片机,9600波特率,12MHz晶振) | |
void init_UART(void){ | |
RCAP2L = 0xD9; | |
RCAP2H = 0xFF; | |
T2CON = 0x34; | |
SCON = 0x50; | |
} | |
//初始化 | |
void init(void){ | |
TH0 = (65536-50000)/256; | |
TL0 = (65536-50000)%256; | |
TH1 = (65536-HighTime)/256; | |
TL1 = (65536-HighTime)%256; | |
EA = 1; | |
TMOD = 0x11; | |
ET0 = 1; | |
TR0 = 1; | |
ET1 = 1; | |
TR1 = 1; | |
init_UART(); | |
} | |
//发送1字节到串口 | |
void UART_send_byte(uint dat){ | |
SBUF = dat; | |
while (TI == 0); | |
TI = 0; | |
} | |
//处理数据并发送到串口 | |
void send_data_UART(uint temp){ | |
//UART_send_byte(temp/10 + '0'); | |
//UART_send_byte(0 + '0'); | |
UART_send_byte(temp/KongNums + '0'); | |
UART_send_byte('.'); | |
UART_send_byte(((temp%KongNums)*10)/KongNums + '0'); | |
UART_send_byte((((temp%KongNums)*10)%KongNums)/2 + '0'); | |
UART_send_byte('r'); | |
UART_send_byte('\\'); | |
UART_send_byte('s'); | |
UART_send_byte('\r'); | |
UART_send_byte('\n'); | |
} | |
void main(){ | |
init(); | |
drive(); | |
while (1) { | |
if ( Kong == 1 ){ | |
testnums++; | |
while ( Kong == 1 ); | |
} | |
} | |
} | |
//每隔一段时间向串口发送信息 | |
void T0_time() interrupt 1{ | |
TH0 = (65536-50000)/256; | |
TL0 = (65536-50000)%256; | |
num++; | |
if ( num == 20 ){ | |
num = 0; | |
led1=~led1; | |
//speed = testnums/KongNums; | |
send_data_UART(testnums); | |
testnums = 0; | |
} | |
} | |
//发射高低脉冲 | |
void T1_time() interrupt 3{ | |
if ( RightEn == 0 ){ | |
TH1 = (65536 - HighTime)/256; | |
TL1 = (65536 - HighTime)%256; | |
RightEn = 1; | |
}else{ | |
TH1 = (65536 - LowTime)/256; | |
TL1 = (65536 - LowTime)%256; | |
RightEn = 0; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment