# README
serialport-go
A Go package that allows you to easily access serial ports.
Usage
serialport
package provides some common serial port operations: Open
, Close
, Read
and Write
, etc.
First you should prepare a serial port configuration Config
:
type Config struct {
BaudRate int
DataBits int
StopBits int
Parity int
Timeout time.Duration
}
If you don't know much about serial port configuration, you can use the default configuration DefaultConfig
:
// DefaultConfig returns a default serial port configuration:
// 115200 bps baudrate
// 8 data bits
// 1 stop bit
// no parity
// 100 ms timeout
func DefaultConfig() Config {
return Config{
BaudRate: BR115200,
DataBits: DB8,
StopBits: SB1,
Parity: PN,
Timeout: 100 * time.Millisecond,
}
}
Then, call Open
to open a serial port:
func Open(name string, cfg Config) (sp *SerialPort, err error) {
/* Code ... */
}
When Open
is successful, it will return a *SerialPort
, which you can use to access the serial port.
Example
A simple serial port echo application:
package main
import (
"fmt"
"log"
"github.com/dsyx/serialport-go"
)
func main() {
sp, err := serialport.Open("COM3", serialport.DefaultConfig())
if err != nil {
log.Fatalln(err)
}
defer sp.Close()
buf := make([]byte, 64)
for {
n, _ := sp.Read(buf)
fmt.Printf("read(%d): %s\n", n, string(buf[:n]))
sp.Write(buf[:n])
}
}
# Functions
DefaultConfig returns a default serial port configuration: 115200 bps baudrate 8 data bits 1 stop bit no parity 100 ms timeout.
Open opens a serial port.
# Constants
110 bps.
115200 bps.
1200 bps.
128000 bps.
14400 bps.
19200 bps.
2400 bps.
256000 bps.
300 bps.
38400 bps.
4800 bps.
57600 bps.
600 bps.
9600 bps.
5 data bits.
6 data bits.
7 data bits.
8 data bits.
Even parity.
Mark parity.
No parity.
Odd parity.
Space parity.
1 stop bit.
1.5 stop bits.
2 stop bits.
# Structs
Config for serial port configuration: BaudRate is the baud rate of serial transmission DataBits is the number of bits per character StopBits is the number of stop bits Parity is a method of detecting errors in transmission Timeout is the serial port Read() timeout.
A SerialPort is a serial port.