基于Visual Studio 2019编写出关于温湿度的上位机代码
时间: 2024-01-13 14:03:33 浏览: 58
温湿度模块代码
好的,以下是一个简单的基于Visual Studio 2019编写的温湿度上位机代码:
```c++
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <Windows.h>
#include <conio.h>
#include <iomanip>
#include <sstream>
using namespace std;
HANDLE hcom;
DCB dcb;
COMMTIMEOUTS timeouts;
int baudRate = 9600;
int dataBits = 8;
int stopBits = ONESTOPBIT;
int parity = NOPARITY;
int flowControl = 0;
void OpenPort()//打开端口
{
hcom = CreateFile("COM3", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hcom == INVALID_HANDLE_VALUE)
{
cout << "打开串口失败!" << endl;
exit(0);
}
dcb.DCBlength = sizeof(dcb);
GetCommState(hcom, &dcb);//获取当前DCB
dcb.BaudRate = baudRate;//波特率
dcb.ByteSize = dataBits;//数据位
dcb.StopBits = stopBits;//停止位
dcb.Parity = parity;//奇偶校验
SetCommState(hcom, &dcb);//配置当前DCB
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
SetCommTimeouts(hcom, &timeouts);//配置超时
}
void ClosePort()//关闭端口
{
CloseHandle(hcom);
}
void SendData()//发送数据
{
DWORD dwBytesWrite;
char sendData[] = "1";//发送数据
WriteFile(hcom, sendData, sizeof(sendData), &dwBytesWrite, NULL);
}
string ReadData()//读取并返回数据
{
DWORD dwBytesRead;
char readData[50];
ReadFile(hcom, readData, sizeof(readData), &dwBytesRead, NULL);
string str(readData);
return str;
}
int main()
{
OpenPort();//打开端口
while (true)
{
SendData();//发送数据
string data = ReadData();//读取数据
stringstream ss(data);
float temp, humid;
ss >> temp >> humid;//解析温湿度数据
cout << fixed << setprecision(2) << "温度:" << temp << "℃,湿度:" << humid << "%" << endl;
Sleep(1000);
}
ClosePort();//关闭端口
return 0;
}
```
注意:代码中的串口号需要根据实际情况进行修改。
阅读全文