Skip to content

Instantly share code, notes, and snippets.

@peltho
Created July 18, 2023 19:54
Show Gist options
  • Save peltho/65f48d7f15f8560ac20600e3b4b80191 to your computer and use it in GitHub Desktop.
Save peltho/65f48d7f15f8560ac20600e3b4b80191 to your computer and use it in GitHub Desktop.
IO with Arduino
package main
import (
"fmt"
"bufio"
"github.com/tarm/serial"
"log"
)
type Arduino struct {
config *serial.Config
}
func NewArduino () *Arduino {
return &Arduino{
config: &serial.Config{
Name: "/dev/ttyACM0",
Baud: 9600,
},
}
}
func (a *Arduino) NewPort() *serial.Port {
p, err := serial.OpenPort(a.config)
if err != nil {
log.Fatal("Cannot open port. ", err)
}
return p
}
func main() {
a := NewArduino()
p := a.NewPort()
a.write(p)
a.read(p)
}
func (a *Arduino) read(p *serial.Port) {
scanner := bufio.NewScanner(p)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if scanner.Err() != nil {
log.Fatal(scanner.Err())
}
}
func (a *Arduino) write(p *serial.Port) {
_, err := p.Write([]byte("....."))
if err != nil {
log.Fatal(err)
}
}
@peltho
Copy link
Author

peltho commented Jul 18, 2023

read allows you to read Serial output from the Arduino
write allows you to write to the Arduino through the Serial port

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment