[Newbies] serial port access
ned at bike-nomad.com
Sun Oct 15 05:41:53 UTC 2006
Juliano Mercantil wrote:
> I'm a newbie in Squeak, and i'm in a desperate need to use a serial port
> to comunicate with an external device.
> I've found the System-Serial Port, but i really need to see a working
> code example.
> Can anyone help? I just need to send some bytes and read the answer.
Yes, I've used it with some success.
* The meaning of the port numbers depend on the platform. You don't say
what your platform is; on Windows, port 0 is COM1: (as I recall); on
Linux, it's /dev/ttyS0 (this I recall because I wrote it), and I'm not
really sure what it would be on the Mac at this point. It used to have
something to do with the MIDI ports on the Mac (really!) but I don't
know what it is in Mac OS X, where serial devices have names like
"/dev/cu.usbserial0" and so on.
* The open will return nil if it fails for some reason.
* Close the port when you're done with it.
* You have to set the parameters before you open the port. The default
is 9600bps/8 bits/no parity/1 stop bit/no flow control in or out. If you
need anything different, you have to set it:
port := (SerialPort new) baudRate: 2400; yourself.
port := port openPort: 0. "or whatever number you need"
port ifNil: [ "something went wrong with the open" ]
"send some bytes"
port nextPutAll: 'stuff'.
port nextPutAll: String cr.
* If you read the port and there are no characters available, you'll
just get an empty string back. So you'll have to poll for bytes and
assemble them as they come in. Use a stream or queue for this. Or use
the #readInto:startingAt: method. And delay within your polling loop so
you don't eat all the CPU time.
So a read with timeout until a CR is seen looks something like this
(from memory; I haven't used Squeak in a long time, so there may be some
bytesRead := 0.
response := String new: 100.
d := Delay forMilliseconds: 300.
started := Time millisecondClockValue.
timeout := 5000. "milliseconds"
[ Time millisecondClockValue - started < timeout ] whileTrue: [
nRead := port readInto: response startingAt: bytesRead + 1.
nRead isZero ifTrue: [ d wait ]
bytesRead := bytesRead + nRead.
(response endsWith: String cr) ifTrue: [
^ response copyFrom: 1 to: bytesRead - 1 ].
ned at bike-nomad.com
More information about the Beginners