用c语言完成题目【题目要求】1-基本功能描述模拟加油站自动加油机的工作流程:通过按键控制加油或停止;通过串口显示当前油价、出油量及总费用;通过 DS18B20 检测环境温度若温度过高则报警提示。2-设计任务1系统初始化 ① L0~L7 依次点亮再依次熄灭。② 通过串口发送当前油价92#为 78 元升95 号为 82 元升98 号为 89元升。发送格式为92# 78 95# 82 98# 89rn
以下是使用C语言完成题目的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 初始化函数
void init() {
// L0~L7 依次点亮,再依次熄灭
for (int i = 0; i <= 7; i++) {
printf("L%d 点亮\n", i);
}
for (int i = 7; i >= 0; i--) {
printf("L%d 熄灭\n", i);
}
// 发送当前油价信息
printf("92# : 7.8 95# : 8.2 98# : 8.9\n");
}
// 按键处理函数
void handleKeyPress(int key) {
static int oilType = 0; // 0表示未选择油号,1表示92#,2表示95#,3表示98#
static int startTimestamp = 0; // 加油开始时间戳
static int oilAmount = 0; // 加油量
// 根据按键选择油号
if (key == 0) {
oilType = 1;
printf("oil=92#\n");
} else if (key == 1) {
oilType = 2;
printf("oil=95#\n");
} else if (key == 2) {
oilType = 3;
printf("oil=98#\n");
}
// 加油键按下
if (key == 5) {
startTimestamp = time(NULL); // 记录开始时间戳
printf("L7 点亮\n");
}
// 停止键按下
if (key == 6) {
int endTimestamp = time(NULL); // 记录结束时间戳
int duration = endTimestamp - startTimestamp; // 计算加油时长
oilAmount = duration; // 油量 = 时长
int price = 0;
if (oilType == 1) {
price = 7.8;
} else if (oilType == 2) {
price = 8.2;
} else if (oilType == 3) {
price = 8.9;
}
int cost = oilAmount * price; // 总费用 = 油量 * 单价
printf("oil=%d total=%d price=%d cost=%d\n", oilType, oilAmount, price, cost);
}
// 付费键按下
if (key == 7) {
printf("所有 LED 点亮 2 秒钟\n");
printf("pay ok\n");
oilType = 0;
startTimestamp = 0;
oilAmount = 0;
}
}
// 温控函数
void temperatureControl(float temperature) {
// 发送当前环境温度
printf("temp=%.1f\n", temperature);
// 若温度超过40度,发送预警信息
if (temperature > 40) {
printf("warn:temp=%.1f!!\n", temperature);
}
}
int main() {
init();
int key; // 按键值
float temperature; // 环境温度
while (1) {
printf("请输入按键值:");
scanf("%d", &key);
handleKeyPress(key);
printf("请输入环境温度:");
scanf("%f", &temperature);
temperatureControl(temperature);
}
return 0;
}
在该代码中,使用了一个简单的循环来模拟程序的运行,每次循环中先接收用户输入的按键值和环境温度,然后分别调用处理按键和温控的函数进行相应的操作。其中,涉及到串口的输出部分直接使用了printf函数来模拟输出,具体的串口通信部分可以根据需要进行替换
原文地址: https://www.cveoy.top/t/topic/hUGI 著作权归作者所有。请勿转载和采集!