#include"stm8s.h"
#include"stm8s_conf.h"
#include"UART2.h"
#include"stdarg.h"
void UART2_Config(u32 Rate)
{
CLK_PeripheralClockConfig(CLK_PERIPHERAL_UART1, ENABLE);
GPIO_Init(UART2_PORT, TX2_PIN, GPIO_MODE_OUT_PP_LOW_FAST);
GPIO_Init(UART2_PORT, RX2_PIN, GPIO_MODE_IN_PU_NO_IT);
UART2_Init(Rate, UART2_WORDLENGTH_8D, UART2_STOPBITS_1, UART2_PARITY_NO, UART2_SYNCMODE_CLOCK_DISABLE, UART2_MODE_TXRX_ENABLE);
UART2_ITConfig(UART2_IT_RXNE_OR,ENABLE);
UART2_Cmd(ENABLE);
}
void UART2_SendByte(u8 Byte)
{
while(!(UART2->SR & TC));
UART2->DR = Byte;
}
#pragma vector =ITC_IRQ_UART2_RX + 2
__interrupt void UART2_IRQHandler(void)
{
u8 Temp;
if(UART2->SR & UART2_SR_RXNE)
{
Temp =UART2->DR;
UART2->SR = ~UART2_SR_RXNE;
UART2_SendByte(Temp);
}
}
char * UART2_itoa(int value, char *string, int radix)
{
int i, d;
int flag = 0;
char *ptr = string;
/* This implementation only works for decimal numbers. */
if (radix != 10)
{
*ptr = 0;
return string;
}
if (!value)
{
*ptr++ = 0x30;
*ptr = 0;
return string;
}
/* if this is a negative value insert the minus sign. */
if (value < 0)
{
*ptr++ = '-';
/* Make the value positive. */
value *= -1;
}
for (i = 10000; i > 0; i /= 10)
{
d = value / i;
if (d || flag)
{
*ptr++ = (char)(d + 0x30);
value -= (d * i);
flag = 1;
}
}
/* Null terminate the string. */
*ptr = 0;
return string;
}
void UART2_Printf(u8 *Data,...)
{
const char *s;
int d;
char buf[16];
va_list ap;
va_start(ap, Data);
while(*Data!=0){ //判断是否到达字符串结束符
if(*Data==0x5c){ //'\'
switch (*++Data){
case 'r': //回车符
UART2_SendByte(0x0d);
Data++;
break;
case 'n': //换行符
UART2_SendByte(0x0a);
Data++;
break;
default:
Data++;
break;
}
}
else if(*Data=='%'){ //
switch (*++Data){
case 's': //字符串
s = va_arg(ap, const char *);
for ( ; *s; s++) {
UART2_SendByte(*s);
}
Data++;
break;
case 'd': //十进制
d = va_arg(ap, int);
UART2_itoa(d, buf, 10);
for (s = buf; *s; s++) {
UART2_SendByte(*s);
}
Data++;
break;
default:
Data++;
break;
}
}
else UART2_SendByte(*Data++);
}
}
上一篇:STM8 IAP笔记
下一篇:STM8 Timer1基本定时
推荐阅读最新更新时间:2024-03-16 16:09