引言
180度舵机,给一个占空比就转相应的角度
50HZ: 0.5ms高电平----0度
1ms高电平 ----45度
1.5ms高电平----90度
2.5ms高电平----180度
代码
PC向单片机发送一个角度值(0-180),舵机就转到相应的角度。串口调试助手里勾上“发送新行”。
#include "driverlib.h"
#include "stdio.h"
#include <string.h>
#include <stdarg.h>
#define MCLK_IN_HZ 1048576
#define delay_us(x) __delay_cycles((MCLK_IN_HZ/1000000*(x)))
#define delay_ms(x) __delay_cycles((MCLK_IN_HZ/1000*(x)))
static int a=0;
static int t = 0;
static int b=0;
static int c=0;
static int word[];
static int length=0;
static int data;
static int angle = 0;
void uartinit1()
{
GPIO_setAsPeripheralModuleFunctionInputPin(GPIO_PORT_P4,GPIO_PIN5);
GPIO_setAsPeripheralModuleFunctionOutputPin(GPIO_PORT_P4, GPIO_PIN4);
USCI_A_UART_initParam param1 = {0};
param1.selectClockSource = USCI_A_UART_CLOCKSOURCE_SMCLK;
param1.clockPrescalar = 6;
param1.firstModReg = 13;
param1.secondModReg = 0;
param1.parity = USCI_A_UART_NO_PARITY;
param1.msborLsbFirst = USCI_A_UART_LSB_FIRST;
param1.numberofStopBits = USCI_A_UART_ONE_STOP_BIT;
param1.uartMode = USCI_A_UART_MODE;
param1.overSampling = USCI_A_UART_OVERSAMPLING_BAUDRATE_GENERATION;
if (STATUS_FAIL == USCI_A_UART_init(USCI_A1_BASE, ¶m1)){
return;
}
USCI_A_UART_enable(USCI_A1_BASE);
USCI_A_UART_clearInterrupt(USCI_A1_BASE,USCI_A_UART_RECEIVE_INTERRUPT);
USCI_A_UART_enableInterrupt (USCI_A1_BASE, USCI_A_UART_RECEIVE_INTERRUPT);
}
void UART_printf(uint16_t baseAddress, const char *format,...)
{
uint32_t length;
va_list args;
uint32_t i;
char TxBuffer[128] = {0};
va_start(args, format);
length = vsnprintf((char*)TxBuffer, sizeof(TxBuffer), (char*)format, args);
va_end(args);
for(i = 0; i < length; i++)
USCI_A_UART_transmitData(baseAddress, TxBuffer[i]);
}
void action()
{
GPIO_setOutputHighOnPin (GPIO_PORT_P1, GPIO_PIN2);
b=0;
while(b<c)
{
delay_ms(0.085);
b++;
}
b=0;
GPIO_setOutputLowOnPin (GPIO_PORT_P1, GPIO_PIN2);
while(b<200-c)
{
delay_ms(0.085);
b++;
}
}
int main(void) {
WDT_A_hold(WDT_A_BASE);
uartinit1();
GPIO_setAsOutputPin (GPIO_PORT_P1,GPIO_PIN2);
GPIO_setAsOutputPin (GPIO_PORT_P1,GPIO_PIN0 );
__bis_SR_register(GIE);
while(1)
{
action();
}
return (0);
}
#pragma vector=USCI_A1_VECTOR
__interrupt void USCI_A1_ISR()
{
GPIO_toggleOutputOnPin (GPIO_PORT_P1, GPIO_PIN0);
data=USCI_A_UART_receiveData (USCI_A1_BASE);
word[length++] = data;
if((word[length-1]==0x0A)&&(word[length-2]==0x0D))
{
if(length==3)
{
angle = word[length-3]-'0';
}
if(length==4)
{
angle = word[length-3]-'0' + (word[length-4]-'0')*10;
}
if(length==5)
{
angle = word[length-3]-'0' + (word[length-4]-'0')*10 + (word[length-5]-'0')*100;
}
UART_printf(USCI_A1_BASE, "%d\r\n", angle);
c = angle/9 + 5;
UART_printf(USCI_A1_BASE, "%d\r\n", c);
length=0;
}
}