STC8H8K64U——定时器生成PWM控制舵机

定时器生成PWM控制舵机

设置5个按键,分别控制舵机转0度,45度,90度,135度,180度。

main.c

#include 
#include 
/*
舵机 DXW90
无负载操作速度:0.12秒/60度(4.8V);0.10秒/60度(6.0V)
棕色线 GND,红色线VCC,橙色信号线 
*/
sbit Servo = P1^0;         //PWM波输出

unsigned char Count = 40;  //定时器计数,20毫秒 
unsigned char Pulse = 0;   //脉冲宽度   

void Timer0Init(void)	//495微秒@24.000MHz
{
	AUXR |= 0x80;	    //定时器时钟1T模式
	TMOD &= 0xF0;		//设置定时器模式
	TL0 = 0x10;		    //设置定时初始值
	TH0 = 0xD2;		    //设置定时初始值
	TF0 = 0;		    //清除TF0标志
	TR0 = 1;		    //定时器0开始计时
}

void main (void)
{	
/*P1.0 推挽输出*/
	P1M0 |= 0x01;
	P1M1 &= ~(0x01);
	Key_GPIO_Init();	
/*定时器初始化*/
	Timer0Init();	
	ET0 = 1;       //定时器T0中断允许
	EA = 1;        //总中断允许	
	Servo = 0;
	while(1)
	{
		unsigned char temp;	
		/*按键扫描*/	
		temp = key_scan();	
		switch(temp)
		{
			case 1: Pulse = 1; break;   //0.5ms 0度
			case 2: Pulse = 2; break;   //1ms   45度
			case 3: Pulse = 3; break;   //1.5ms 90度
			case 4: Pulse = 4; break;   //2ms   135度
			case 5: Pulse = 5; break;   //2.5ms 180度  
		}
	}
}

void Int0(void) interrupt 1  
{	
	Count--;
	if(Count < Pulse)
		Servo = 1;
	else
		Servo = 0;	
	if(Count == 0) //整个周期为20ms
		Count = 40;
}

key.h

#ifndef KEY_H
#define KEY_H

#include 

sbit KEY0 = P1^3;
sbit KEY1 = P1^4; 
sbit KEY2 = P1^5; 
sbit KEY3 = P1^6; 
sbit KEY4 = P1^7; 

void Key_GPIO_Init(void);
unsigned char key_scan(void);

#endif

key.c

#include 

void Key_GPIO_Init(void)
{
	P_SW2 |= 0x80; 		
/*高阻输入模式*/	
	P1M0 &= ~(0xF8);
	P1M1 |= 0xF8;;
/*上拉电阻使能*/
	P1PU |= 0xf8; 
}
/*按键扫描*/
unsigned char key_scan(void)
{
	static unsigned char Key_Flage = 0;
	
	if(KEY0 == 0)
		 Key_Flage = 1;
	
	else if(KEY1 == 0)
		 Key_Flage = 2;
	
	else if(KEY2 == 0)
		 Key_Flage = 3;
	
	else if(KEY3 == 0)
		 Key_Flage = 4;
	
	else if(KEY4 == 0)
		 Key_Flage = 5;
	
	return Key_Flage;
}

PWM控制舵机

你可能感兴趣的:(STC8H8K64U——打狗棍,单片机,嵌入式硬件,c语言,51单片机)