76 lines
2.5 KiB
C#
76 lines
2.5 KiB
C#
using System.IO.Ports;
|
|
using System.Text;
|
|
|
|
namespace RGBController2.Boards
|
|
{
|
|
/// <summary>
|
|
/// ArduinoBoard used for communicating with a sigle Arduino device.
|
|
/// </summary>
|
|
public class ArduinoBoard : IBoard
|
|
{
|
|
/// <summary>
|
|
/// True is communication has been established with the Arduino, false otherwise.
|
|
/// </summary>
|
|
public bool Connected { get; }
|
|
|
|
/// <summary>
|
|
/// The serial port object for communicating with the Arduino.
|
|
/// </summary>
|
|
private SerialPort _serialPort;
|
|
|
|
/// <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>
|
|
public ArduinoBoard(string portName, int baudRate = 9600)
|
|
{
|
|
Connected = false;
|
|
_serialPort = new SerialPort();
|
|
_serialPort.PortName = portName;
|
|
_serialPort.BaudRate = baudRate;
|
|
_serialPort.Open();
|
|
if (_serialPort.IsOpen)
|
|
Connected = true;
|
|
}
|
|
|
|
/// <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>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Turns off all of the LEDs connected to the board.
|
|
/// </summary>
|
|
public void TurnOffAllLeds()
|
|
{
|
|
string command = "a000000;";
|
|
_serialPort.WriteLine(command);
|
|
}
|
|
|
|
/// <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>
|
|
private static string ByteToHexString(byte b)
|
|
{
|
|
StringBuilder hex = new StringBuilder(2);
|
|
hex.AppendFormat("{0:x2}", b);
|
|
return hex.ToString();
|
|
}
|
|
}
|
|
}
|