Skip to content

Instantly share code, notes, and snippets.

@chrishannam
Created June 2, 2020 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrishannam/2de1f44177c68d24d7e93ed07f5d3010 to your computer and use it in GitHub Desktop.
Save chrishannam/2de1f44177c68d24d7e93ed07f5d3010 to your computer and use it in GitHub Desktop.
Read from a serial port and extract JSON.
package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"github.com/tarm/serial"
)
func main() {
c := &serial.Config{Name: "/dev/cu.usbserial-14120", Baud: 9600}
ser, err := serial.OpenPort(c)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(ser)
for scanner.Scan() {
output := scanner.Bytes()
var f interface{}
err := json.Unmarshal(output, &f)
if err != nil {
fmt.Println("Trying again")
} else {
m := f.(map[string]interface{})
fmt.Println(m["light"])
fmt.Println(m["temperature"])
fmt.Println(m["humidity"])
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case float64:
fmt.Println(k, "is float64", vv)
case []interface{}:
fmt.Println(k, "is an array:")
for i, u := range vv {
fmt.Println(i, u)
}
default:
fmt.Println(k, "is of a type I don't know how to handle")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment