本帖最后由 紫气东升 于 2016-8-25 08:16 编辑
#include <stm8l052c6.h>
#include <stdio.h>
/*********函数声明********/
void delay(unsigned int time);
void IO_Init(void);
void USART1_Init(void);
void CLK_Init(void);
/*********主函数********/
main()
{
USART1_Init(); //通用串行接口USART1初始化
IO_Init(); //IO端口初始化
CLK_Init(); //时钟初始化
_asm("rim"); //开总中断
while(1)
{
PD_ODR=0x02; //PD1(红)亮
delay(65535); //延时1s
PD_ODR=0x00; //PD1(红)灭
delay(65535); //延时1s
}
}
/*********CLK初始化*********/
void CLK_Init(void)
{
CLK_CKDIVR=0x03; //对HSI进8分频16MHZ/8=2MHZ
}
/******USART1初始化*********/
void USART1_Init(void)
{
USART1_CR1=0x00; //设置字长,8位数据位
USART1_CR2=0x0c; //使能发送、接收;
USART1_CR3=0x00; //1位停止位
USART1_BRR2=0x00; //2MHZ时钟下9600波特率
USART1_BRR1=0x0d;
//USART1_SR=0x40; //TC位置1
}
/*********GPIO初始化*********/
void IO_Init(void)
{
PD_ODR=0x00; //初始使小灯全灭
PD_DDR=0x03; //设置PD端口为输出模式
PD_CR1=0x03; //设置PD端口为推挽输出
PD_CR2=0x00; //设置PD端口为低速输出
}
/******中断服务程序********/
@far
@interrupt void USART_Rx_IRQHandler(void)
{
if((USART1_SR & 0x20)==0)
{
USART1_DR=0xB6;
PD_ODR=0x01;
}
if((USART1_SR & 0x60)==0)
{
USART1_DR=0xB6;
}
}
/********延时函数**********/
void delay(unsigned int time)
{
while(time--);
}
这是我用寄存器写的程序,想搞个串口中断的,没想到怎么试都不成功,有哪位高手会的请教教我,不胜感激!
[mw_shl_code=applescript,true]void init_uart(void)
{
_asm("rim");
CLK_PCKENR1 |= SETBIT2; //fMASTER to peripheral enabled--UART1
UART1_CR2 &= CLRBIT2; //Receiver is disabled
UART1_CR2 &= CLRBIT3; //Transmitter is disabled
UART1_BRR2 = 0x1b; //Baud rate register 2 2400=0x1b 9600=0x03
UART1_BRR1 = 0xa0; //Baud rate register 1 2400=0xa0 9600=0x68
UART1_CR3 &= CLRBIT4; //1 Stop bit
UART1_CR3 &= CLRBIT5; //1 Stop bit
UART1_CR1 &= CLRBIT2; //Parity control disabled
UART1_CR1 &= CLRBIT4; //1 Start bit, 8 Data bits, 1 Stop bit
UART1_CR2 &= CLRBIT6; //Interrupt is inhibited
UART1_CR2 |= SETBIT5; //An UART interrupt is generated whenever OR=1 or RXNE=1 in the UART_SR register
UART1_CR1 &= CLRBIT5; //UART enabled
UART1_CR2 |= SETBIT2; //Receiver is enabled and begins searching for a start bit
UART1_CR2 |= SETBIT3; //Transmitter is enabled
}
@far @interrupt void UART_Rx_Interrupt(void)
{
unsigned char temp[5] = {0x01, 0x02, 0x03, 0x04};
char i;
temp[4] = UART1_DR;
PA_ODR &= CLRBIT3;
for(i = 0; i < 5; i++)
{
while((UART1_SR & CHSBIT7) == 0x00); //wait for data transfers to shift register
UART1_DR = temp;
}
while((UART1_SR & CHSBIT6) == 0x00); //wait for transmit complete
PA_ODR |= SETBIT3; //note: TC bit is set 1 after reset,it is clear by a software sequence
//(a read to the UART_SR register followed by a write to the UART_DR register)
}
[/mw_shl_code]
收到什么回发什么,你自己看看吧
一周热门 更多>