/// <summary> /// Sends the specified command to the ardunino interface /// and reads the output sent back. /// </summary> /// <param name="command">The command to send.</param> /// <returns> /// The output sent back from the arduino /// </returns> public string SendRead(Command command) { // send out the command byte[] buffer = GetBuffer(command); Debug.WriteLine( string.Format("Sending command: - {0}|{1}|{2}|{3}", friendlyNumber, command.CommandNumber, command.Pin, command.Value, backupNumber)); this.serialPort.Write(buffer, 0, buffer.Length); Thread.Sleep(500); // wait a sec // read it back int count = this.serialPort.BytesToRead; string returnMessage = ""; int intReturnASCII = 0; while (count > 0) { intReturnASCII = this.serialPort.ReadByte(); returnMessage = returnMessage + Convert.ToChar(intReturnASCII); count--; } Debug.WriteLine("Arduino sent back: " + returnMessage); return returnMessage; }
/// <summary> /// Takes a command and generates a buffer of bytes from it. /// </summary> /// <param name="command">The command to parse.</param> /// <returns>A byte array to send to arduino.</returns> private byte[] GetBuffer(Command command) { byte[] buffer = new byte[5]; buffer[0] = Convert.ToByte(friendlyNumber); buffer[1] = Convert.ToByte(command.CommandNumber); buffer[2] = Convert.ToByte(command.Pin); buffer[3] = Convert.ToByte(command.Value); buffer[4] = Convert.ToByte(backupNumber); return buffer; }
/// <summary> /// Sends the specified command to the arduino interface. /// </summary> /// <param name="command">The command to send to the arduino.</param> public void Send(Command command) { byte[] buffer = GetBuffer(command); Debug.WriteLine( string.Format("Sending command - {0}|{1}|{2}|{3}", friendlyNumber, command.CommandNumber, command.Pin, command.Value, backupNumber)); this.serialPort.Write(buffer, 0, buffer.Length); }