📄 uart.c
字号:
#include "uart.h"
int UART_BASE;
int uart_get;
void irq_handler(void);
void uart_init(unsigned channel, unsigned long baud)
{
unsigned instruction;
/* ARM irq exception vector addr is 0x00000018 */
unsigned *irq_vec_addr = ( unsigned *) 0x18;
/* this is isr entry address, could be another address like 0x3c, 0x58... */
unsigned *isr_entry_addr = ( unsigned *) 0x58;
*(unsigned *) (channel + UBRDIV) = baud;
*(unsigned *) (channel + ULCON) = (ULCR8bits);
UART_BASE = channel;
/* set the ISR entry at 0x58 */
*isr_entry_addr = (unsigned)irq_handler;
/* make an instruction: it is machine-code for "ldr pc, [pc, #(58-18-8)]" */
instruction = ((unsigned) isr_entry_addr - (unsigned)irq_vec_addr - 0x08) | 0xe59ff000;
/* set this instruction at 0x18 */
*irq_vec_addr = instruction;
// unmask the uart0 TX interrupt
INTMSK &= ~((1<<21) | (1 << 5) | (1 << 7));
}
int uart_putchar(int ch)
{
while ( TX_READY(GET_STATUS(UART_BASE))==0)
;
PUT_CHAR(UART_BASE, ch);
return 0;
}
char uart_getchar(void)
{
while ( (RX_DATA(GET_STATUS(UART_BASE)))==0 )
;
return(GET_CHAR(UART_BASE));
}
int uart_puts(const char *str)
{
int i;
char ch;
if (!str)
return -1;
for (i = 0; str[i] != '\0'; i++)
{
ch = str[i];
while ( TX_READY(GET_STATUS(UART_BASE))==0)
;
PUT_CHAR(UART_BASE, ch);
}
return 0;
}
static void uart0_irq_handler(void)
{
while ( (RX_DATA(GET_STATUS(UART_BASE)))==0 )
;
uart_get = GET_CHAR(UART_BASE);
INTPND |= UART0_MASK;
}
static void uart1_irq_handler(void)
{
while ( (RX_DATA(GET_STATUS(UART_BASE)))==0 )
;
uart_get = GET_CHAR(UART_BASE);
INTPND |= UART1_MASK;
}
void do_isr(void)
{
void (*current_pc)(void) = 0;
if (INTPND & UART0_MASK)
current_pc = uart0_irq_handler;
if (INTPND & UART1_MASK)
current_pc = uart1_irq_handler;
if (INTPND & INT0_MASK)
current_pc = int0_irq_handler;
if (INTPND & TIMER0_MASK)
current_pc = timer0_irq_handler;
current_pc();
}
void uart0demo( void )
{
uart_get = -(~0);
uart_init(UART0_BASE, BAUD_19200);
uart_puts("Now input any char to begin uart0 demo.\r\nThe char you input will echo on the host screen.\r\n");
uart_puts("Press 'Enter' to quit\r\n");
for (; ;)
{
while (uart_get == -(~0))
;
if (uart_get == '\r' || uart_get == '\n')
break;
uart_putchar(uart_get);
uart_get = -(~0);
}
return;
}
void uart1demo( void )
{
uart_get = -(~0);
uart_init(UART1_BASE, BAUD_19200);
uart_puts("Now input any char to begin uart1 demo.\r\nThe char you input will echo on the host screen.\r\n");
uart_puts("Press 'Enter' to quit\r\n");
for (; ;)
{
while (uart_get == -(~0))
;
if (uart_get == '\r' || uart_get == '\n')
break;
uart_putchar(uart_get);
uart_get = -(~0);
}
return;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -