直流电机驱动
直流电机介绍
电机驱动电路
PWM介绍
使用PWM控制呼吸灯
main.c
#include <REGX52.H>
sbit LED=P2^0;
void Delay(unsigned int t)
{
while(t--);
}
void main()
{
unsigned char Time,i;
while(1)
{
for(Time=0;Time<100;Time++)
{
for(i=0;i<20;i++)
{
LED=0;
Delay(Time);
LED=1;
Delay(100-Time);
}
}
for(Time=100;Time>0;Time--)
{
for(i=0;i<20;i++)
{
LED=0;
Delay(Time);
LED=1;
Delay(100-Time);
}
}
}
}
运行效果
产生PWM方法
直流电机调速
Timer0.c
#include <REGX52.H>
/**
* @brief 定时器0初始化,100微秒@12.000MHz
* @param 无
* @retval 无
*/
void Timer0_Init(void)
{
TMOD &= 0xF0; //设置定时器模式
TMOD |= 0x01; //设置定时器模式
TL0 = 0x9C; //设置定时初始值
TH0 = 0xFF; //设置定时初始值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
ET0=1;
EA=1;
PT0=0;
}
/* 定时器中断函数模板
void Timer0_Routine() interrupt 1
{
static unsigned int T0Count;
TL0 = 0x9C; //设置定时初始值
TH0 = 0xFF; //设置定时初始值
T0Count++;
if(T0Count>=1000)
{
T0Count=0;
}
}
*/
Timer0.h
#ifndef __TIMER0_H__
#define __TIMER0_H__
void Timer0_Init(void);
#endif
Key.c
#include <REGX52.H>
#include "Delay.h"
/**
* @brief 获取独立按键键码
* @param 无
* @retval 按下按键的键码,范围:0~4, 无按键按下返回0
*/
unsigned char Key()
{
unsigned char KeyNumber=0;
if(P3_1==0){Delay(20);while(P3_1==0);Delay(20);KeyNumber=1;}
if(P3_0==0){Delay(20);while(P3_0==0);Delay(20);KeyNumber=2;}
if(P3_2==0){Delay(20);while(P3_2==0);Delay(20);KeyNumber=3;}
if(P3_3==0){Delay(20);while(P3_3==0);Delay(20);KeyNumber=4;}
return KeyNumber;
}
Key.h
#ifndef __KEY_H__
#define __KEY_H__
unsigned char Key();
#endif
main.c
#include <REGX52.H>
#include "Delay.h"
#include "Key.h"
#include "Nixie.h"
#include "Timer0.h"
sbit Motor=P1^0;
unsigned char Counter,Compare;
unsigned char KeyNum,Speed;
void main()
{
Timer0_Init();
Compare=5;
while(1)
{
KeyNum=Key();
if(KeyNum==1)
{
Speed++;
Speed%=4;
switch(Speed)
{
case 0:Compare=0;break;
case 1:Compare=50;break;
case 2:Compare=75;break;
case 3:Compare=100;break;
}
}
Nixie(1,Speed);
}
}
void Timer0_Routine() interrupt 1
{
TL0 = 0x9C; //设置定时初始值
TH0 = 0xFF; //设置定时初始值
Counter++;
Counter%=100;
if(Counter<Compare)
{
Motor=1;
}
else
{
Motor=0;
}
}
标签:__,20,19,void,unsigned,Delay,直流电机,驱动,include
From: https://www.cnblogs.com/mzx233/p/17867417.html