A projectben azt vizsgáltam, hogy a szenzor által mért értékeket hogyan tudom egy Arduino-tól független asztali appban feldolgozni. A szükséges anyagok:

A szenzor VCC-re 3.3V-ot, a GND-re 0V-ot kell kötni. A mért adatok a DQ PIN-en érhetőek el, amit az alaplap valamelyik GPIO PIN-jére kell csatlakoztatni, én a 2. PIN-t használtam.

using System.IO;
using System.IO.Ports;
using System.Text;
using System.Windows;
namespace IndoorThermometer.Classes
{
public class ThermoMeter
{
private SerialPort _serialPort;
static StringBuilder _buffer = new StringBuilder();
public double temperature { get; set; }
public ThermoMeter(string portName, int speed)
{
_serialPort = new SerialPort(portName, speed);
_serialPort.DataReceived += SerialPort_DataReceived;
_serialPort.Open();
}
public void ClosePort() { _serialPort.Close(); }
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int count = 0;
try
{
SerialPort sp = (SerialPort)sender;
string data = sp.ReadExisting();
_buffer.Append(data);
// Soronként dolgozzuk fel
string content = _buffer.ToString();
int index;
while ((index = content.IndexOf('\n')) >= 0)
{
string line = content.Substring(0, index).Trim();
if (!string.IsNullOrEmpty(line))
{
if (double.TryParse(line,
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture,
out double tempValue))
{
temperature = tempValue;
count++;
}
}
content = content.Substring(index + 1);
}
_buffer.Clear();
if (content.Length > 500) { content = content.Substring(0, 500); }
_buffer.Append(content);
}
catch (IOException ioEx)
{
MessageBox.Show(ioEx.Message, "I/O Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (InvalidOperationException invEx)
{
MessageBox.Show(invEx.Message, "Port is not available!", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}