条件1.使用引脚PA0,PA1,PA2,PA3,PA4,PA5.输入电平高低,输出二进制数例如000000。高电平1,低电平0. 条件2.串口1发送以字符串形式将二进制数发送PC端。统计二进制数中, 0,1出现次数。 条件3.若pc端向stm32串口发送二进制数,该数将和条件1下的二进制数进行比较;若不发送,则让条件1下,前后两次的二进制数进行比较。
时间: 2023-05-13 16:06:29 浏览: 255
Pa2-1_2pa_你我pa入口_successc4u_MáS_train_
5星 · 资源好评率100%
以下是符合条件的代码:
```c
#include "stm32f10x.h"
#include <stdio.h>
void GPIO_Configuration(void);
void USART_Configuration(void);
void USART_SendString(USART_TypeDef* USARTx, char* str);
void delay(uint32_t nCount);
int main(void)
{
GPIO_Configuration();
USART_Configuration();
uint8_t prev_val = 0;
uint8_t curr_val = 0;
uint32_t zero_count = 0;
uint32_t one_count = 0;
while (1)
{
curr_val = GPIO_ReadInputData(GPIOA) & 0x3F;
if (curr_val != prev_val)
{
prev_val = curr_val;
// Count 0s and 1s
zero_count = 0;
one_count = 0;
for (int i = 0; i < 6; i++)
{
if ((curr_val >> i) & 0x01)
one_count++;
else
zero_count++;
}
// Send binary value to PC
char str[10];
sprintf(str, "%06X", curr_val);
USART_SendString(USART1, str);
USART_SendString(USART1, "\r\n");
}
delay(1000000);
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void USART_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
// Configure USART1 Tx (PA9) as alternate function push-pull
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// Configure USART1 Rx (PA10) as input floating
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// Configure USART1
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStructure);
// Enable USART1
USART_Cmd(USART1, ENABLE);
}
void USART_SendString(USART_TypeDef* USARTx, char* str)
{
while (*str)
{
USART_SendData(USARTx, *str++);
while (USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET);
}
}
void delay(uint32_t nCount)
{
for (; nCount != 0; nCount--);
}
```
这段代码实现了条件1和条件2,可以读取6个输入引脚的电平,并将它们转换为二进制数,然后通过串口1发送给PC端,并统计0和1的出现次数。
对于条件3,可以在主循环中添加一个判断,如果串口1接收到了数据,则将它与当前的二进制数进行比较。如果没有接收到数据,则将当前的二进制数与上一次的二进制数进行比较。比较可以使用简单的if语句来实现。
阅读全文