#include <iostm8s103f3.h>
#include <intrinsics.h>
#define UART1_FLAG_TXE (unsigned char)0x80 // Tx Data Register Empty flag
#define UART1_FLAG_RXNE (unsigned char)0x20 // Rx Data Register Not Empty flag
unsigned char RxBuf = '0';
unsigned char UART_RxBuffer[32];
unsigned char UART_TxBuffer[64];
int MyPWM = 0;
int Rxflag = 0;
int Tx_W_flag = 0;
int Tx_R_flag = 0;
/*SendByte*/
void uart_SendByte(unsigned char data)
{
UART_TxBuffer[Tx_W_flag] = data;
Tx_W_flag++;
UART1_CR2 |= 0x80;
}
/*SendString*/
void uart_SendString(unsigned char Str[])
{
unsigned char n = 0;
while(Str[n])
uart_SendByte(Str[n++]);
}
/*SendInt*/
void uart_SendInt(int x)
{
static const char dec[] = "0123456789";
unsigned int div_val = 10000;
if (x < 0){
x = - x;
uart_SendByte('-');
}
while (div_val > 1 && div_val > x)
div_val /= 10;
do{
uart_SendByte (dec[x / div_val]);
x %= div_val;
div_val /= 10;
}while(div_val);
}
int main( void )
{
// setup clock
CLK_CKDIVR &= (unsigned char)(~0x18); // 16MHz high speed internal clock
// setup uart: 115200, 8-n-1
// reference: Table 54. Baud rate programming and error calculation
UART1_CR1 = 0x00; // 1-8-nn, uart enabled, no parity check and interrupt
UART1_CR2 = 0x2C; // rx/tx enabled, rx int enabled, tx int disabled
//UART1_CR2 = 0xAC; // rx/tx enabled, rxne int enabled, txc int disabled
UART1_CR3 = 0x00; // 1 stop bits
UART1_CR5 = 0x00; // IrDA mode disabled
UART1_BRR2 = 0x0B; // 115200 baud rate. must set BRR2 first
UART1_BRR1 = 0x08; // 115200 baud rate. must set BRR2 first
//LED: B5
PB_DDR |= 0x20; // output
PB_CR1 |= 0x20; // push pull
PB_CR2 |= 0x20; // 10MHz output speed
// enable interrupt
__enable_interrupt();
uart_SendString("usart int\r\n");
while (1) {
}
}
/*发送interrupt*/
#pragma vector = UART1_T_TXE_vector
__interrupt void UART1_T_TXE_Handler(void)
{
if(Tx_W_flag == Tx_R_flag)
UART1_CR2 &= 0x7F;
else
{
UART1_DR = UART_TxBuffer[Tx_R_flag];
Tx_R_flag++;
}
}
/*接收interrupt*/
#pragma vector = UART1_R_RXNE_vector
__interrupt void UART1_R_RXNE_IRQHandler(void)
{
RxBuf = UART1_DR;
if(RxBuf >= '0' && RxBuf <= '9' || RxBuf == '?'||RxBuf == 'd'){
UART_RxBuffer[Rxflag] = RxBuf;
Rxflag++;
}
UART1_DR = RxBuf;
if(RxBuf == 13){
if(UART_RxBuffer[0] == 'd'){
if(Rxflag == 4)
MyPWM = (UART_RxBuffer[1]-'0')*10+(UART_RxBuffer[2]-'0');
if(Rxflag == 3)
MyPWM = (UART_RxBuffer[1]-'0');
if(UART_RxBuffer[Rxflag-1]=='?'){
uart_SendString("duty cycle is ");
uart_SendInt(MyPWM);
Rxflag=0;
}
}
}
}