| 1 | = !SerialPort = |
| 2 | |
| 3 | Cobra's support for serial ports comes through the .NET standard library. See: |
| 4 | * [http://msmvps.com/blogs/coad/archive/2005/03/23/SerialPort-_2800_RS_2D00_232-Serial-COM-Port_2900_-in-C_2300_-.NET.aspx SerialPort (RS-232 Serial COM Port) in C# .NET] |
| 5 | * https://www.google.com/search?q=.net+rs-232 |
| 6 | * https://www.google.com/search?q=mono+rs-232 |
| 7 | |
| 8 | == Example == |
| 9 | |
| 10 | The following example comes from [http://msmvps.com/blogs/coad/archive/2005/03/23/SerialPort-_2800_RS_2D00_232-Serial-COM-Port_2900_-in-C_2300_-.NET.aspx SerialPort (RS-232 Serial COM Port) in C# .NET], converted to Cobra. |
| 11 | |
| 12 | {{{ |
| 13 | #!cobra |
| 14 | use System.IO.Ports |
| 15 | use System.Windows.Forms |
| 16 | |
| 17 | class SerPort |
| 18 | |
| 19 | shared |
| 20 | # Instantiate the communications port with some basic settings |
| 21 | var port = SerialPort("COM1", 9600, Parity.None, 8, StopBits.One) |
| 22 | |
| 23 | def main is shared |
| 24 | print 'serialPorts:' |
| 25 | for s in SerialPort.getPortNames |
| 26 | print s |
| 27 | |
| 28 | .sendSampleData |
| 29 | #.rcvSampleData |
| 30 | |
| 31 | def sendSampleData is shared |
| 32 | # Open the port for communications |
| 33 | try |
| 34 | .port.open |
| 35 | catch ioe as IOException |
| 36 | print ioe.message |
| 37 | CobraCore.exit(1) |
| 38 | |
| 39 | # Write a string |
| 40 | .port.write("Hello World") |
| 41 | # Write a set of bytes |
| 42 | .port.write(@[0x0A_u8, 0xE2_u8, 0xFF_u8], 0, 3) |
| 43 | |
| 44 | # Close the port |
| 45 | .port.close |
| 46 | |
| 47 | def rcvSampleData is shared |
| 48 | print "Incoming Data:" |
| 49 | |
| 50 | # Attach a method to be called when there is data waiting in the port's buffer |
| 51 | # C#: port.DataReceived += newSerialDataReceivedEventHandler( port_DataReceived ) |
| 52 | listen .port.dataReceived, SerialDataReceivedEventHandler(ref .port_DataReceived ) |
| 53 | # Begin communications |
| 54 | .port.open |
| 55 | # Enter an application loop to keep this thread alive - GUI program - otherwise use a reader Thread |
| 56 | Application.run |
| 57 | |
| 58 | def port_DataReceived(sender as Object, e as SerialDataReceivedEventArgs) is shared |
| 59 | # Show all the incoming data in the port's buffer |
| 60 | print .port.readExisting |
| 61 | }}} |
| 62 | |
| 63 | == See Also == |
| 64 | |
| 65 | * LibraryTopics |