我正在开发一个项目,允许我通过串口将DHT11传感器数据发送到我的PC。在我的PC中,我用C#代码捕获数据。问题是显然传感器记录仍然在串口中累积。像这样的25; 40
[温度和湿度]应该每2秒到达一次,但我得到类似的东西:25; 4026; 4323; 54
我可以做一次一次阅读?谢谢你的帮助。
Arduino代码:
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11
String temperatura;
String humedad;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
delay(1000);
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
float hif = dht.computeHeatIndex(f, h);
float hic = dht.computeHeatIndex(t, h, false);
String temperatura = String(t);
String humedad = String(h);
Serial.print(temperatura + ";" + humedad + "");
}
C# code:
async void getSerialData() {
var date = DateTime.Now;
string temperature;
string humidity;
bool getDataNow = false;
serialPort = new SerialPort();
// serialPort.PortName = "COM5";//Set your board COM
serialPort.BaudRate = 9600;
string portNumber = "COMXX";
ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mbs = new ManagementObjectSearcher("Select * From Win32_SerialPort");
mbsList = mbs.Get();
if (mbsList.Count > 0) {
foreach (ManagementObject mo in mbsList) {
Console.WriteLine("Description:{0}", mo["Description"].ToString());
Console.WriteLine("Puerto:{0}", mo["DeviceID"].ToString());
if (mo["Description"].ToString().Contains("duino")) {
portNumber = mo["DeviceID"].ToString();
serialPort.PortName = mo["DeviceID"].ToString();
serialPort.Open();
getDataNow = true;
button2.BackColor = Color.FromArgb(56, 228, 6);
button2.Text = "Synchro OK";
button2.Enabled = false;
}
}
if (portNumber == "COMXX") {
getDataNow = false;
MessageBox.Show("Ninguno de los dispositivos conectados se identifico como sensor syncro", "syncro", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
} else {
getDataNow = false;
MessageBox.Show("Ningun dispositivo ha sido conectado", "synchro", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
while (getDataNow) {
string a = "";
if (serialPort.IsOpen == true) {
a = serialPort.ReadExisting();
} else {
MessageBox.Show("El dispositivo ha sido desconectado", "synchro", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
getDataNow = false;
}
await Task.Delay(4000);
Console.Write("datos sensor " + a.Length);
Console.Write("datos sensor " + a);
if (a.Length > 0) {
getDataSensor(a, out temperature, out humidity);
lblHum.Text = "";
lblTemp.Text = "";
lblHum.Text = humidity;
lblTemp.Text = temperature;
}
}
}
答案 0 :(得分:0)
变化:
Serial.print(temperatura + ";" + humedad + "");
要:
Serial.println(temperatura + ";" + humedad + "");
这样读数就会显示为不同的线条。