RGBController/RGBController2/Boards/ArduinoBoard.cs

76 lines
2.5 KiB
C#
Raw Normal View History

2020-11-08 13:08:52 +00:00
using System.IO.Ports;
2020-10-25 19:52:14 +00:00
using System.Text;
namespace RGBController2.Boards
{
2020-11-08 13:08:52 +00:00
/// <summary>
/// ArduinoBoard used for communicating with a sigle Arduino device.
/// </summary>
2020-10-25 19:52:14 +00:00
public class ArduinoBoard : IBoard
{
2020-11-08 13:08:52 +00:00
/// <summary>
/// True is communication has been established with the Arduino, false otherwise.
/// </summary>
2020-10-27 20:07:26 +00:00
public bool Connected { get; }
2020-11-08 13:08:52 +00:00
/// <summary>
/// The serial port object for communicating with the Arduino.
/// </summary>
2020-10-25 19:52:14 +00:00
private SerialPort _serialPort;
2020-11-08 13:08:52 +00:00
/// <summary>
/// Constructs an ArduinoBoard object for controlling the Arduino.
/// </summary>
/// <param name="portName">The COM port name of the arduino.</param>
/// <param name="baudRate">The baud rate at which to communicate with the arduion. Default 9600.</param>
2020-10-25 19:52:14 +00:00
public ArduinoBoard(string portName, int baudRate = 9600)
{
2020-10-27 20:07:26 +00:00
Connected = false;
2020-10-25 19:52:14 +00:00
_serialPort = new SerialPort();
_serialPort.PortName = portName;
_serialPort.BaudRate = baudRate;
_serialPort.Open();
if (_serialPort.IsOpen)
2020-10-27 20:07:26 +00:00
Connected = true;
2020-10-25 19:52:14 +00:00
}
2020-11-08 13:08:52 +00:00
/// <summary>
/// Sets all of the LEDs to the chosen RGB colour.
/// </summary>
/// <param name="red">The red value</param>
/// <param name="green">The green value</param>
/// <param name="blue">The blue value</param>
2020-10-25 19:52:14 +00:00
public void SetAllLeds(byte red, byte green, byte blue)
{
string command = "a";
command += ByteToHexString(red);
command += ByteToHexString(green);
command += ByteToHexString(blue);
command += ';';
_serialPort.WriteLine(command);
}
2020-11-08 13:08:52 +00:00
/// <summary>
/// Turns off all of the LEDs connected to the board.
/// </summary>
2020-10-25 19:52:14 +00:00
public void TurnOffAllLeds()
{
string command = "a000000;";
_serialPort.WriteLine(command);
}
2020-11-08 13:08:52 +00:00
/// <summary>
/// Helper function to convert as byte to a hex string used by the arduino.
/// e.g: 255 would become FF
/// </summary>
/// <param name="b">The byte to be converted.</param>
/// <returns></returns>
2020-10-25 19:52:14 +00:00
private static string ByteToHexString(byte b)
{
StringBuilder hex = new StringBuilder(2);
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
}
}