本文整理汇总了Golang中github.com/tarm/serial.OpenPort函数的典型用法代码示例。如果您正苦于以下问题:Golang OpenPort函数的具体用法?Golang OpenPort怎么用?Golang OpenPort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了OpenPort函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: connect
func connect() (io.ReadWriter, error) {
if *baud == 0 {
return net.Dial("tcp", *dst)
}
c := &serial.Config{Name: *dst, Baud: *baud}
return serial.OpenPort(c)
}
示例2: main
func main() {
config := &serial.Config{Name: "/dev/tty.usbmodem1411", Baud: 57600}
s, err := serial.OpenPort(config)
if err != nil {
panic(err)
}
opts := MQTT.NewClientOptions().AddBroker("tcp://46.101.145.61:1883")
opts.SetClientID("meteo-studio")
// Connect MQTT client
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
// Loop over serial port lines
scanner := bufio.NewScanner(s)
for scanner.Scan() {
parts := strings.Split(scanner.Text(), "|")
if parts[0] == "6" {
// if command is "6" (meteo data payload), push it to the broker
token := c.Publish("studio/meteo", 0, false, parts[1])
token.Wait()
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
}
示例3: main
func main() {
sp, err := serial.OpenPort(&serial.Config{Name: "/dev/ttyACM0", Baud: 57600})
if err != nil {
panic(err)
}
board := client.New()
fmt.Println("connecting.....")
err = board.Connect(sp)
defer board.Disconnect()
if err != nil {
panic(err)
}
fmt.Println("firmware name:", board.FirmwareName)
fmt.Println("firmata version:", board.ProtocolVersion)
pin := 13
if err = board.SetPinMode(pin, client.Output); err != nil {
panic(err)
}
level := 0
for {
level ^= 1
if err := board.DigitalWrite(pin, level); err != nil {
panic(err)
}
fmt.Println("level:", level)
time.Sleep(500 * time.Millisecond)
}
}
示例4: Connect
// Connect starts a connection to the board
func (megaPi *MegaPiAdaptor) Connect() (errs []error) {
if megaPi.connection == nil {
sp, err := serial.OpenPort(megaPi.serialConfig)
if err != nil {
return []error{err}
}
// sleeping is required to give the board a chance to reset
time.Sleep(2 * time.Second)
megaPi.connection = sp
}
// kick off thread to send bytes to the board
go func() {
for {
select {
case bytes := <-megaPi.writeBytesChannel:
megaPi.connection.Write(bytes)
time.Sleep(10 * time.Millisecond)
case <-megaPi.finalizeChannel:
megaPi.finalizeChannel <- struct{}{}
return
default:
time.Sleep(10 * time.Millisecond)
}
}
}()
return
}
示例5: OnClick
func (l *leds) OnClick(button string) {
totalClicks := l.btns.Clicks()[button]
l.hub.Broadcast <- fmt.Sprintf(`{"event":"processing","data":{"button":%s}}`, button)
c := &serial.Config{Name: "/dev/ttyAMA0", Baud: 9600}
s, err := serial.OpenPort(c)
if err != nil {
log.Fatal(err)
}
btnNum, err := strconv.Atoi(button)
n, err := s.Write([]byte{byte(btnNum), byte(totalClicks)})
if err != nil {
log.Fatal(err)
}
buf := make([]byte, 128)
n, err = s.Read(buf)
if err != nil {
log.Fatal(err)
}
log.Printf("Response from arduino: %q", buf[:n])
l.hub.Broadcast <- fmt.Sprintf(`{"event":"click","data":{"button":%s,"count":%d}}`, button, totalClicks)
}
示例6: uploadFirmware
//------------------------------------------------------------------------------
// Purpose: Uploads the firmware to the devices via xmodem.
//
// Param dev_path: The device path to commmunicate on.
// Param firmware_path: The location on disk of the firmware that is to be
// installed.
// Param wg : The waitgroup that is needed to sync the goroutines together with
// all the other instances of this function.
//------------------------------------------------------------------------------
func uploadFirmware(devPath, firmwarePath string, wg *sync.WaitGroup) {
logDebug("Reading binary file")
data, err := ioutil.ReadFile(firmwarePath)
check(err)
infoLog.Println("Opening", devPath)
config := &serial.Config{Name: devPath, Baud: 115200, ReadTimeout: time.Second * 5}
logDebug("Opening serial port")
port, err := serial.OpenPort(config)
check(err)
logDebug("Sending xmodem request to serial")
_, err = port.Write([]byte("U"))
check(err)
verifyWrite(port)
_, err = port.Write([]byte("u"))
check(err)
verifyWrite(port)
logDebug("Done sending xmodem request to serial")
startTime := time.Now()
infoLog.Println("Starting XMODEM transfer for", devPath)
check(xmodem.ModemSend(port, data))
infoLog.Println("Finished XMODEM transfer for", devPath, "in", time.Since(startTime))
wg.Done()
}
示例7: changeGPSBaudRate
func changeGPSBaudRate(config *serial.Config, newRate int) error {
if config.Baud == newRate {
return nil
}
p, err := serial.OpenPort(config)
if err != nil {
return err
}
defer p.Close()
baud_cfg := createChecksummedNMEASentence([]byte(fmt.Sprintf("PMTK251,%d", newRate)))
_, err = p.Write(baud_cfg)
if err != nil {
return err
}
config.Baud = newRate
valid, err := detectGPS(config)
if !valid {
err = fmt.Errorf("Set GPS to new rate, but unable to detect it at that new rate!")
}
return err
}
示例8: main
func main() {
serialPort := flag.String("port", "", "Port to use for serial communication (COM4, COM5, /path/to/serial/file, etc)")
baudRate := flag.Int("baud", 115200, "Baud rate for serial port")
httpHost := flag.String("httpHost", "", "HTTP host")
httpPort := flag.Int("httpPort", 8752, "HTTP port")
websocketUrl := flag.String("webUrl", "/scary", "Url for websocket communication")
flag.Parse()
if *serialPort == "" {
log.Fatalln("Serial port is required! Use --help for more info")
}
c := &serial.Config{Name: *serialPort, Baud: *baudRate}
fmt.Println(c)
p, err := serial.OpenPort(c)
if err != nil {
log.Fatal(err)
}
// pr, pw := io.Pipe()
server := &Server{From: p}
server.init()
go server.keepAlive()
go server.proxy()
// go testCommands(pw)
log.Printf("Proxying from serial port %s to websocket url %s:%d%s \n", *serialPort, *httpHost, *httpPort, *websocketUrl)
http.HandleFunc(*websocketUrl, server.handleClientConnection)
err = http.ListenAndServe(fmt.Sprintf("%s:%d", *httpHost, *httpPort), nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}
示例9: connectArduinoSerialBT
func (acq *Acquisition) connectArduinoSerialBT() {
// config the comm port for serial via BT
commPort := &serial.Config{Name: commDevName, Baud: bauds}
// open the serial comm with the arduino via BT
acq.serialPort, _ = serial.OpenPort(commPort)
//defer acq.serialPort.Close()
log.Printf("Open serial device %s", commDevName)
}
示例10: Open
// Open is used to open serial ports of the device. This should be used first.
// The method returns error if open was not succeed, i.e. if device is absent.
func (d *Device) Open() (err error) {
cmdPortCfg := serial.Config{
Name: d.CommandPort,
Baud: BaudRate,
}
notifyPortCfg := serial.Config{
Name: d.NotifyPort,
Baud: BaudRate,
}
if d.cmdPort, err = serial.OpenPort(&cmdPortCfg); err != nil {
return
}
if d.notifyPort, err = serial.OpenPort(¬ifyPortCfg); err != nil {
return
}
return
}
示例11: Open
// Open attempts to detect and run a numato device at the provided location.
func Open(serialName string) (*Numato, error) {
c := &serial.Config{Name: serialName, Baud: 9600, ReadTimeout: time.Millisecond * 10}
s, err := serial.OpenPort(c)
if err != nil {
return nil, err
}
return &Numato{s}, nil
}
示例12: Init
//Setup allows to configure the sensor conexion
func (s *Sensor) Init(c *serial.Config) {
s.Address = 0xFFFFFFFF
var err error
s.port, err = serial.OpenPort(c)
if err != nil {
panic(err)
}
}
示例13: main
func main() {
log.Printf("Establishing the serial connection...")
c := &serial.Config{Name: "/dev/ttyACM0", Baud: 9600}
s, err := serial.OpenPort(c)
if err != nil {
log.Fatal(err)
}
time.Sleep(2 * time.Second) // needed to give Arduino some time to initialise as it is reset when the port is opened
cloud, err := NewdbusWrapper("/com/devicehive/cloud", "com.devicehive.cloud")
if err != nil {
log.Panic(err)
}
cloudHandlers := make(map[string]cloudCommandHandler)
cloudHandlers["led/on"] = func(p map[string]interface{}) (map[string]interface{}, error) {
log.Printf("Turning the LED on...")
_, err := s.Write([]byte("1"))
return map[string]interface{}{"led": "on"}, err
}
cloudHandlers["led/off"] = func(p map[string]interface{}) (map[string]interface{}, error) {
log.Printf("Turning the LED off...")
_, err := s.Write([]byte("0"))
return map[string]interface{}{"led": "off"}, err
}
cloud.RegisterHandler("CommandReceived", func(args ...interface{}) {
id := args[0].(uint32)
command := args[1].(string)
params := args[2].(string)
log.Printf("Got command %d with name \"%s\" and parameters %s", id, command, params)
var param_data map[string]interface{}
b := []byte(params)
json.Unmarshal(b, ¶m_data)
//log.Printf("param_data %s", param_data)
if h, ok := cloudHandlers[command]; ok {
//At this point the client notifies the cloud about the success/failure of the command
res, err := h(param_data)
if err != nil {
cloud.CloudUpdateCommand(id, fmt.Sprintf("ERROR: %s", err.Error()), nil)
} else {
cloud.CloudUpdateCommand(id, "success", res)
}
} else {
log.Printf("Unhandled command: %s", command)
}
})
select {}
}
示例14: Open
// Open opens a serial port to the undelying device
func (c *Conn) Open() error {
p, err := serial.OpenPort(&c.device)
if err != nil {
return err
}
c.port = p
c.isOpen = true
return nil
}
示例15: NewAdaptor
// NewAdaptor creates a neurosky adaptor with specified port
func NewAdaptor(port string) *Adaptor {
return &Adaptor{
name: "Neurosky",
port: port,
connect: func(n *Adaptor) (io.ReadWriteCloser, error) {
return serial.OpenPort(&serial.Config{Name: n.Port(), Baud: 57600})
},
}
}