CSharp
From Cricut Hacking Wiki
Revision as of 02:04, 30 January 2014 by Cricutwikiadmin (Talk | contribs)
C# Code Sample
The following class and code sample should get any C# programmer started communicating with the Cricut.
This sets up the Serial Communication for both First and Second Generation Cricut Hardware. The error handler here can have either the WinForms Error or the Console Error.
public class CricutCommunication { public CricutCommunication(short portNumber) { this.PortNumber = portNumber; } public short PortNumber { get; set; } public byte[] SendRecv(byte[] sendBytes) { if (sendBytes.Length > 0) { using (SerialPort port = new SerialPort("COM" + PortNumber, 198347, Parity.None, 8, StopBits.One)) { port.Handshake = Handshake.None; port.ErrorReceived += new SerialErrorReceivedEventHandler(PortErrorReceived); port.ReadTimeout = 5000; port.WriteTimeout = -1; port.Open(); port.Write(sendBytes, 0, sendBytes.Length); while (ExpectResults) { if (port.BytesToRead > 0) { byte[] readResults = new byte[port.BytesToRead]; port.Read(readResults, 0, port.BytesToRead); return readResults; } Thread.Sleep(5); } } } return new byte[0]; } static void PortErrorReceived(object sender, SerialErrorReceivedEventArgs e) { ConsoleColor saveColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine(e.EventType.ToString()); Console.ForegroundColor = saveColor; // MessageBox.Show(e.EventType); } public static byte[] GetStringToBytes(string value) { SoapHexBinary shb = SoapHexBinary.Parse(value); return shb.Value; } public static string GetBytesToString(byte[] value) { SoapHexBinary shb = new SoapHexBinary(value); return shb.ToString(); } }
Call the method like so...
short port = 8; byte[] results = new CricutCommunication(port).SendRecv(new byte[] { 0x04, 0x12, 0x00, 0x00, 0x00 }, true);