自学内容网 自学内容网

4.15 day6 ARM

uart.c

#include "uart4.h"
void uart4_config()
{
    RCC->MP_AHB4ENSETR |= (0X1 << 6);//G
    RCC->MP_AHB4ENSETR |= (0X1 << 1);//B
    RCC->MP_APB1ENSETR |= (0X1 << 16);//UART4
//管脚复用
    GPIOG->MODER  &= (~(0X3 << 22));
    GPIOG->MODER |= (0X2 << 22);
    GPIOB->MODER &= (~(0X3 << 4));
    GPIOB->MODER |= (0X2 << 4);
    GPIOG->AFRH &= (~(0XF << 12));//UART4_TX
    GPIOG->AFRH |= (0X6 << 12);
    GPIOB->AFRL &= (~(0XF << 8));//UART4_RX
    GPIOB->AFRL |= (0X8 << 8);

//USART设置
    USART4->CR1 &= (~(0X1));//使能禁用
    USART4->CR1 &= (~(0X1 << 28));//设置数据位
    USART4->CR1 &= (~(0X1 << 12));
    USART4->CR1 &= (~(0x1 << 15));//设置过采样倍数
    USART4->CR1 &= (~(0x1 << 10));//设置无奇偶校验位
    USART4->CR1 |= (0X1 << 3);//发送器使能位
    USART4->CR1 |= (0X1 << 2);//接收器使能位

    USART4->CR2 &= (~(0X1 << 12));
    USART4->BRR = (0X22B);
    USART4->PRESC &= (~(0XF));//设置不分频

    USART4->CR1 |= (0X1 << 0);//串口工作使能位

}

void putchar(char dat)
{
    while (!(USART4->ISR & (0X1 << 7)));
    USART4->TDR = dat;
    while (!(USART4->ISR & (0X1 << 6)));
    
}

char getchar()
{
    while (!(USART4->ISR & (0X1 << 5)));
    return USART4->RDR;
    
}

void puts(char *a)
{
    int i=0;
    while (a[i] != '\0')
    {
        putchar(a[i]);
        i++;
    }
    putchar('\n');
    putchar('\r');
}

char * gets(char *b)
{
    int i=0;
    for(;(b[i]=getchar()) != '\r';i++)
    {
        putchar(b[i]);
    }
    putchar('\r');
    putchar('\n');
    b[i]='\0';

    //  for (int i = 0; i < 128; i++)
    // {
    //     b[i] = getchar(); // 将接收到的字符放入str中
    //     putchar(b[i]); // 将接收到的字符串发送回串口调试助手
    //     if (b[i] == '\r') // 如果接收到了换行符
    //     {
    //         putchar('\n'); // 将接收到的字符串发送回串口调试助手
    //         b[i+1] = '\0';
    //         break;
    //     }
        
    return b;
}

uart.h

#ifndef  __UART4_H__
#define __UART4_H__
#include  "stm32mp1xx_gpio.h" 
#include  "stm32mp1xx_rcc.h" 
#include  "stm32mp1xx_uart.h" 

void uart4_config();
void putchar(char dat);
char getchar();
char * gets(char *b);
void puts(char *a);

#endif

main.c

#include "uart4.h"

int main()
{
    char dat[128];
    while(1)

    {
       gets(dat);
       puts(dat);
    }
    return 0;

}

 


原文地址:https://blog.csdn.net/2301_80793165/article/details/137798238

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!