基于stm32设计一个计算器,通过键盘输入 0~9 的数字,以及运算法则加减乘除,能通过串口在电脑端串口调试软件上显示运算结果。写出完成此功能的所有代码
时间: 2023-12-06 18:45:03 浏览: 210
用stm32实现简单计算器
以下是基于STM32设计的计算器代码,可以通过串口在电脑端串口调试软件上显示运算结果:
```c
#include "stm32f10x.h"
#include "stdio.h"
USART_InitTypeDef USART_InitStructure;
void GPIO_config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
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);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void USART_config(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
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 USART_send_char(char c)
{
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
USART_SendData(USART1, c);
}
void USART_send_string(char* s)
{
while (*s)
{
USART_send_char(*s++);
}
}
char USART_receive_char(void)
{
while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET);
return USART_ReceiveData(USART1);
}
int main(void)
{
GPIO_config();
USART_config();
char buffer[50];
char ch;
int i = 0;
while (1)
{
ch = USART_receive_char();
if (ch != '\r')
{
buffer[i++] = ch;
}
else
{
buffer[i] = '\0';
i = 0;
int result = 0;
int num1 = 0;
int num2 = 0;
char op;
int flag = 0;
for (int j = 0; buffer[j] != '\0'; j++)
{
if (buffer[j] >= '0' && buffer[j] <= '9')
{
if (flag == 0)
{
num1 = num1 * 10 + (buffer[j] - '0');
}
else
{
num2 = num2 * 10 + (buffer[j] - '0');
}
}
else if (buffer[j] == '+' || buffer[j] == '-' || buffer[j] == '*' || buffer[j] == '/')
{
op = buffer[j];
flag = 1;
}
}
switch (op)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
break;
}
sprintf(buffer, "%d\n", result);
USART_send_string(buffer);
}
}
}
```
请注意,此代码仅为示例,仅支持简单的加减乘除运算,未做错误处理和输入检查。在实际应用中,需要根据具体要求进行修改和完善。
阅读全文