Wiki
Version 1 (modified by Charles, 11 years ago)

--

SerialPort

Cobra's support for serial ports comes through the .NET standard library. See:

Example

The following example comes from  SerialPort (RS-232 Serial COM Port) in C# .NET, converted to Cobra.

use System.IO.Ports
use System.Windows.Forms

class SerPort

    shared
        # Instantiate the communications port with some basic settings 
        var port = SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)

    def main is shared
        print 'serialPorts:'
        for s in SerialPort.getPortNames 
            print s
        
        .sendSampleData
        #.rcvSampleData
            
    def sendSampleData is shared
        # Open the port for communications 
        try 
            .port.open
        catch ioe as IOException
            print ioe.message
            CobraCore.exit(1)

        # Write a string 
        .port.write("Hello World")
        # Write a set of bytes 
        .port.write(@[0x0A_u8, 0xE2_u8, 0xFF_u8], 0, 3) 

        # Close the port
        .port.close
        
    def rcvSampleData is shared
        print "Incoming Data:"

        # Attach a method to be called when there is data waiting in the port's buffer 
        # C#:   port.DataReceived += newSerialDataReceivedEventHandler( port_DataReceived )
        listen .port.dataReceived, SerialDataReceivedEventHandler(ref .port_DataReceived )
        # Begin communications 
        .port.open 
        # Enter an application loop to keep this thread alive - GUI program - otherwise use a reader Thread 
        Application.run 
        
    def port_DataReceived(sender as Object, e as SerialDataReceivedEventArgs) is shared
        # Show all the incoming data in the port's buffer 
        print .port.readExisting

See Also