11.13hw

main

 
#include "uart.h"
 
int main()
{
    uart_init();
 
    sendchar('h');
    char c = getchar();
    sendchar(c);
    while (1) {
    }
 
    return 0;
}

h

#ifndef __UART_H__
#define __UART_H__
 
typedef struct {
    unsigned int MODER;
    unsigned int OTYPER;
    unsigned int OSPEEDR;
    unsigned int PUPDR;
    unsigned int IDR;
    unsigned int ODR;
    unsigned int BSRR;
    unsigned int LCKR;
    unsigned int AFRL;
    unsigned int AFRH;
} gpio_t;
 
typedef struct {
    unsigned int CR1;
    unsigned int CR2;
    unsigned int CR3;
    unsigned int BRR;
    unsigned int GTPR;
    unsigned int RTOR;
    unsigned int RQR;
    unsigned int ISR;
    unsigned int ICR;
    unsigned int RDR;
    unsigned int TDR;
} uart_t;
 
#define UART4 ((uart_t*)0x40010000)
#define GPIOG ((gpio_t*)0x50008000)
#define GPIOB ((gpio_t*)0x50003000)
 
#define RCC_MP_AHB4ENSETR (*(unsigned int*)0x50000A28)
#define RCC_MP_APB1ENSETR (*(unsigned int*)0x50000A00)
 
void uart_init();
 
void sendchar(char c);
void led_flash();
char getchar();
#endif

c

#include "uart.h"
 
void uart_init()
{
    // GPIOG GPIOB时钟使能
    RCC_MP_AHB4ENSETR |= (1 << 1);
    RCC_MP_AHB4ENSETR |= (1 << 6);
    // URT4时钟使能
    RCC_MP_APB1ENSETR |= (1 << 16);
 
    // 复用
    GPIOB->MODER |= (2 << 2);
    GPIOG->MODER |= (2 << 22);
    // 复用功能
    GPIOB->AFRL |= (0x1 << 11);
    GPIOG->AFRH |= (0x6 << 12);
    // 位宽8
    UART4->CR1 &= (~(1 << 12));
    UART4->CR1 &= (~(1 << 28));
    // 16倍采样
    UART4->CR1 &= (~(1 << 15));
    // 无校验
    UART4->CR1 &= (~(1 << 10));
    // 停止位
    UART4->CR2 &= (~(3 << 12));
    // 波特率
    UART4->BRR |= (0x22b);
    // 发送使能
    UART4->CR1 |= (1 << 3);
    // 接收使能
    UART4->CR1 |= (1 << 2);
    // 串口使能
    UART4->CR1 |= 1;
}
 
void sendchar(char c)
{
 
     while (!(UART4->ISR & (1 << 7)))
        ;
    UART4->TDR = c;
    while (!(UART4->ISR & (1 << 6)))
        ;
}
 
char getchar()
{
    while (!(UART4->ISR & (1 << 5)))
        ;
    return (char)UART4->RDR;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值