-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArduinoHandler.cs
More file actions
101 lines (80 loc) · 2.57 KB
/
Copy pathArduinoHandler.cs
File metadata and controls
101 lines (80 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Threading;
namespace ArduinoTesterTemplate
{
public enum ArduinoCommand : byte
{
EXAMPLECOMMAND,
EXAMPLEPINREAD,
EXAMPLEWITHPARAMS
}
public class ArduinoHandler
{
private const char COMMAND_TERMINATOR = '$';
private Dictionary<ArduinoCommand, string> _arduinoCommands;
public SerialPort SerialPort { get; private set; }
public ArduinoHandler(string portName)
{
InitSerialPort(portName);
InitCommandDictionary();
}
private void InitSerialPort(string portName)
{
SerialPort = new SerialPort(portName, 9600, Parity.None, 8, StopBits.One);
SerialPort.WriteTimeout = 2000;
SerialPort.ReadTimeout = 2000;
}
public void Open()
{
if (SerialPort.IsOpen) return;
SerialPort.Open();
}
public void Close()
{
if (!SerialPort.IsOpen) return;
SerialPort.Close();
}
private void InitCommandDictionary()
{
_arduinoCommands = new Dictionary<ArduinoCommand, string>();
_arduinoCommands.Add(ArduinoCommand.EXAMPLECOMMAND, "EXAMPLECOMMAND");
_arduinoCommands.Add(ArduinoCommand.EXAMPLEPINREAD, "EXAMPLEPINREAD");
_arduinoCommands.Add(ArduinoCommand.EXAMPLEWITHPARAMS, "EXAMPLEWITHPARAMS");
}
public void SendCommand(ArduinoCommand command, params string[] parameters)
{
if (!SerialPort.IsOpen) return;
StringBuilder commandBuilder = new StringBuilder();
commandBuilder.Append(_arduinoCommands[command]);
foreach(var parameter in parameters)
{
commandBuilder.Append(",");
commandBuilder.Append(parameter);
}
commandBuilder.Append(COMMAND_TERMINATOR);
SerialPort.Write(commandBuilder.ToString());
}
public string ReadMessage()
{
string response = "";
try
{
response = SerialPort.ReadExisting();
}
catch (Exception)
{
// Handle it as you wish
}
return response;
}
public string Query(ArduinoCommand command, params string[] parameters)
{
SendCommand(command, parameters);
Thread.Sleep(1000);
return ReadMessage();
}
}
}