STM32F103VCT编写程序,在串口助手中输入电压值,电压值返回到stm32并在OLED屏幕上显示相应电压
时间: 2024-03-14 21:45:55 浏览: 59
好的,这是一个涉及到串口通信和OLED屏幕的程序,需要涉及到以下几个部分:
1. 初始化串口和OLED屏幕
2. 从串口中读取电压值
3. 将电压值转换为实际电压
4. 将实际电压显示在OLED屏幕上
下面是一个大致的程序框架,你可以参考这个框架完成程序的编写:
```c
#include "stm32f10x.h" //包含STM32头文件
#include "OLED.h" //包含OLED屏幕驱动程序
#include <stdio.h> //包含标准输入输出库
#include <string.h> //包含字符串库
//定义串口和OLED屏幕的端口和引脚
#define USART1_PORT GPIOA
#define USART1_TX_PIN GPIO_Pin_9
#define USART1_RX_PIN GPIO_Pin_10
#define OLED_PORT GPIOB
#define OLED_SCL_PIN GPIO_Pin_10
#define OLED_SDA_PIN GPIO_Pin_11
//定义串口和OLED屏幕的初始化函数
void USART1_Init(void)
{
//初始化USART1的GPIO口
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
GPIO_InitStructure.GPIO_Pin = USART1_TX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(USART1_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = USART1_RX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(USART1_PORT, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 9600;
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_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void OLED_Init(void)
{
//初始化OLED的GPIO口
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = OLED_SCL_PIN | OLED_SDA_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(OLED_PORT, &GPIO_InitStructure);
OLED_Init();
}
//定义电压转换函数
float getVoltage(uint16_t adcValue)
{
float voltage = 0;
voltage = (float)adcValue * 3.3 / 4096; //假设ADC使用的是3.3V参考电压
return voltage;
}
int main(void)
{
//初始化串口和OLED屏幕
USART1_Init();
OLED_Init();
while(1)
{
//从串口中读取电压值
char buffer[10];
uint16_t adcValue = 0;
while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET);
USART_ReceiveData(USART1, &adcValue);
//转换实际电压
float voltage = getVoltage(adcValue);
//将电压值显示在OLED屏幕上
char voltageStr[10];
sprintf(voltageStr, "%.2fV", voltage);
OLED_ShowString(0, 0, voltageStr);
}
}
```
需要注意的是,上面的程序只是一个框架,具体实现可能需要根据你的硬件和软件环境进行一些调整。
阅读全文