串口通信控制led灯

uart.c

#include"uart.h"void all_led_init(){RCC_GPIO |= (0X3<MODER &=(~(0X3<MODER |= (0X1<OTYPER &=(~(0x1<OSPEEDR &= (~(0x3<PUPDR &= (~(0x3<MODER &=(~(0X3<MODER |= (0X1<OTYPER &=(~(0x1<OSPEEDR &= (~(0x3<PUPDR &= (~(0x3<MODER &=(~(0X3<MODER |= (0X1<OTYPER &=(~(0x1<OSPEEDR &= (~(0x3PUPDR &= (~(0x3<ODR |= (0x1<ODR &= (~(0x1<ODR |= (0x1<ODR &= (~(0x1<ODR |= (0x1<ODR &= (~(0x1<MP_AHB4ENSETR |= (0x1<MP_AHB4ENSETR |= (0x1<MP_APB1ENSETR |= (0x1<MODER &= (~(0x3<MODER |= (0x2<AFRH &= (~(0xf<AFRH |= (0x6<MODER &= (~(0x3<MODER |= (0x2<AFRL &= (~(0xF<AFRL |= (0x8<CR1 &= (~0x1);//3.设置数据位宽为8位USART4->CR1 &= (~(0x1<CR1 &= (~(0x1<CR1 &= (~(0x1<CR1 &= (~(0x1<CR2 &= (~(0x3<PRESC &= (~0xf);//8.设置波特率为115200USART4->BRR=0X22B;//9.使能发送器USART4->CR1 |= (0x1<CR1 |= (0x1<CR1 |= (0x1);} //字符串比较int strcmp(const char *s1, const char *s2){for(int i=0; s1[i]!='\0' || s2[i] !='\0'; i++){if(s1[i]!=s2[i]){return -1;}}return 0;} void putchar(char a){//1.先判断发送器是否为空,不为空等待while(!(USART4->ISR &(0x1<TDR=a;//3.等待发送完成while(!(USART4->ISR &(0x1<ISR &(0x1<RDR;//3.返回return a;} //发送一个字符串void puts(char *s){while(*s){putchar(*s);s++;}putchar('\r');putchar('\n');} //接收一个字符串void gets(char *s){while(1){*s=getchar();putchar(*s);//键盘输入的内容在串口上回显if(*s=='\r'){*s='\0';break;}s++;}putchar('\n'); }

main.c

#include"uart.h"int main() { uart4_config(); all_led_init(); //char a; char buf[128]; while(1) { /*//接收一个字符数据a=getchar();//发送接收的字符+1putchar(a+1);putchar('\r'); putchar('\n'); */gets(buf); // 读取字符串 if(strcmp(buf,"led1_on") == 0) { //LED1亮 led1_on(); }if(strcmp(buf,"led1_off") == 0) { //LED1灭 led1_off(); } if(strcmp(buf,"led2_on") == 0) { //LED2亮 led2_on(); }if(strcmp(buf,"led2_off") == 0) { //LED2灭 led2_off(); } if(strcmp(buf,"led3_on") == 0) { //LED3亮 led3_on(); }if(strcmp(buf,"led3_off") == 0) { //LED3灭 led3_off(); } //puts(buf); // 输出字符串 } }

uart.h

#ifndef __UART4_H__#define __UART4_H__#include"stm32mp1xx_rcc.h"#include"stm32mp1xx_gpio.h"#include"stm32mp1xx_uart.h" #define RCC_GPIO (*(unsigned int*)0x50000a28) void all_led_init();void led1_on();void led1_off();void led2_on();void led2_off();void led3_on();void led3_off();int strcmp(const char *s1, const char *s2);void uart4_config();void putchar(char a);char getchar();void gets(char *s);void puts(char *s);#endif