UART 相關副程式
//========== uart.h
============================================
void UART_Init();
char UART_GetByte();
void UART_GetString(char *);
void UART_Put_Dec(unsigned int );
void UART_SendByte(char);
void UART_SendString(char *);
void UART_SendString_no_linefeed(char *);
//=========== uart.c
===========================================
// UART 函數
#include "SPCE061A.h"
#include "stdlib.h"
#include "string.h"
#include "uart.h"
//===============================================
void UART_Init() {
char ch;
// 注意: 特殊接腳時仍須設定 GPIO 暫存器, 否則可能因被強迫 pull-high/low 而不動作
*P_IOB_Dir=0x0400; // IOB10=output(TX), IOB7=input(RX)
*P_IOB_Attrib=0x0480; // IOB10=not invert, IOB7=float
*P_UART_Command1=0x20; // UART reset, 無同位元 *P_UART_Command1=0x00;
//*P_UART_BaudScalarHigh=0x00; // Baud=115200bps //*P_UART_BaudScalarLow=0x6B;
*P_UART_BaudScalarHigh=0x05; // Baud=9600bps *P_UART_BaudScalarLow=0x00;
*P_UART_Command2=0x00C0; // 致能 RX/TX
ch = *P_UART_Data; // 清除緩衝區 }
//===================================================
char UART_GetByte() {
while( ! (*P_UART_Command2 & 0x0080)) { //等待接收完畢 *P_Watchdog_Clear=C_WDTCLR;
}
return *P_UART_Data;
}
//===================================================
void UART_SendByte(char ch) {
while( !( *P_UART_Command2 & 0x0040)) { //等待前一次發射完畢 *P_Watchdog_Clear=C_WDTCLR;
}
*P_UART_Data = ch;
}
//===============================================
void UART_SendString_no_linefeed(char *str) //不跳行 {
while ( *str )
UART_SendByte(*str++);
}
//===================================================
void UART_SendString(char *str) //送出字串,跳行 {
while ( *str )
UART_SendByte(*str++);
UART_SendByte(0x0a);
UART_SendByte(0x0d);
}
//===================================================
void UART_Put_Dec(unsigned int value) //最多 5 位數
{
static const char ASCIITable[] = "0123456789";
unsigned int div_value=10000,base=10;
while (div_value > 1 && div_value > value ) //消除前導零 div_value /= base;
do {
UART_SendByte( ASCIITable[ value / div_value ] );
value %= div_value;
div_value /= base;
} while ( div_value );
}
//===================================================
void UART_GetString(char *str) {
char *str2 = str;
char c;
while ( ( c = UART_GetByte() ) != 0x0d ) {
if (c == 0x08) {
if ( (int) str2 < (int) str ) {
UART_SendByte(0x08);
UART_SendByte(0x20);
UART_SendByte(0x08);
str--;
} } else {
*str++ = c;
UART_SendByte(c);
} }
*str = '\0';
UART_SendByte(0x0a);
UART_SendByte(0x0d);
}