Created
July 18, 2023 19:54
-
-
Save peltho/65f48d7f15f8560ac20600e3b4b80191 to your computer and use it in GitHub Desktop.
IO with Arduino
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
readallows you to read Serial output from the Arduinowriteallows you to write to the Arduino through the Serial port