上位机C语言 温度检测
时间: 2023-06-19 13:08:28 浏览: 77
以下是一个简单的上位机C语言程序,可以通过串口接收来自温度传感器的数据,并将其显示在计算机屏幕上。
```c
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
HANDLE hSerial;
DCB dcbSerialParams = {0};
COMMTIMEOUTS timeouts = {0};
char port[] = "COM3"; // 更改为具体的串口号
char buffer[256];
DWORD bytesRead, dwEventMask;
// 打开串口
hSerial = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hSerial == INVALID_HANDLE_VALUE)
{
fprintf(stderr, "无法打开串口 %s\n", port);
return 1;
}
// 配置串口参数
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams))
{
fprintf(stderr, "无法获取串口参数\n");
return 1;
}
dcbSerialParams.BaudRate = CBR_9600;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if (!SetCommState(hSerial, &dcbSerialParams))
{
fprintf(stderr, "无法设置串口参数\n");
return 1;
}
// 设置串口读取超时时间
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
if (!SetCommTimeouts(hSerial, &timeouts))
{
fprintf(stderr, "无法设置串口超时时间\n");
return 1;
}
// 读取串口数据并显示
while(1)
{
if (WaitCommEvent(hSerial, &dwEventMask, NULL))
{
if (ReadFile(hSerial, buffer, sizeof(buffer), &bytesRead, NULL))
{
buffer[bytesRead] = '\0';
printf("温度:%s\n", buffer);
}
}
}
// 关闭串口
CloseHandle(hSerial);
return 0;
}
```
此程序中使用了Windows API中的串口操作函数,需要在Windows操作系统上运行。在使用前需要将程序中的“COM3”更改为实际的串口号。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)