UART1
2018-08-30 本文已影响7人
昨天剩下的一杯冷茶
#include "uart.h"
#define UART_BUF_MAX 10
unsigned char uart_buf[UART_BUF_MAX];
unsigned char uart_in,uart_out;
/*32MHz系统时钟
**
*/
void Uart_Init(unsigned long baudrate)
{
P0SEL |= BV(2) | BV(3);
U0CSR |= BV(7);
switch (baudrate)
{
case UART_BAUDRATE_115200:
U0GCR = 11;
U0BAUD = 216;
break;
case UART_BAUDRATE_19200:
U0GCR = 9;
U0BAUD = 59;
break;
case UART_BAUDRATE_9600:
U0GCR = 8;
U0BAUD = 59;
break;
default: //115200
U0GCR = 11;
U0BAUD = 216;
break;
}
UTX0IF = 0;
U0CSR |= BV(6);
URX0IE =1;
EA = 1;
uart_in = 0;
uart_out = 0;
}
void Uart_String(char *p)
{
while(*p !=0)
{
U0DBUF = *p++;
while(!UTX0IF);
UTX0IF = 0;
}
}
bool get_uart_data(unsigned char *p)
{
if (uart_in == uart_out) return false;
p[0] = uart_buf[uart_out++];
uart_out = uart_out%UART_BUF_MAX;
return true;
}
void send_uart_data(unsigned char *p,unsigned char len)
{
U0DBUF = *p++;
while(!UTX0IF);
UTX0IF = 0;
}
#pragma vector=URX0_VECTOR
__interrupt void URX0_ISR(void)
{
uart_buf[uart_in++] = U0DBUF;
uart_in = uart_in%UART_BUF_MAX;
URX0IF = 0;
}
//头文件==========================================================
#ifndef __UART_H__
#define __UART_H__
#include "all.h"
#define UART_BAUDRATE_115200 (115200)
#define UART_BAUDRATE_19200 (19200)
#define UART_BAUDRATE_9600 (9600)
void Uart_Init(unsigned long baudrate);
void send_uart_data(unsigned char *p,unsigned char len);
void Uart_String(char *p);
bool get_uart_data(unsigned char *p);
#endif
//例子==========================================================
#include "all.h"
#include "led.h"
#include "uart.h"
void main(void)
{
unsigned char data;
CLKCONCMD &= ~0x40; //设置系统时钟源为32MHZ晶振
while(CLKCONSTA & 0x40); //等待晶振稳定
CLKCONCMD &= ~0x47; //设置系统主时钟频率为32MHZ
char p_buf[]="hello world\r\n";
InitGPIO();
Uart_Init(UART_BAUDRATE_115200);
Uart_String(p_buf);
while(1) //死循环
{
if (get_uart_data(&data))
{
switch(data)
{
case 'a'://open led
LED1 = 1;
Uart_String("a\r\n");
break;
case 'b'://close led
LED1 = 0;
Uart_String("b\r\n");
break;
default:
break;
}
}
}
}