tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/examples/p1am/main.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "machine" 6 "time" 7 8 "tinygo.org/x/drivers/p1am" 9 ) 10 11 func main() { 12 for { 13 if err := loop(); err != nil { 14 fmt.Printf("loop failed, retrying: %v\n", err) 15 time.Sleep(500 * time.Millisecond) 16 } 17 } 18 } 19 func loop() error { 20 led := machine.LED 21 led.Configure(machine.PinConfig{Mode: machine.PinOutput}) 22 sw := machine.SWITCH 23 sw.Configure(machine.PinConfig{Mode: machine.PinInput}) 24 25 if err := p1am.Controller.Initialize(); err != nil { 26 return fmt.Errorf("initializing controller: %w", err) 27 } 28 29 version, err := p1am.Controller.Version() 30 if err != nil { 31 return fmt.Errorf("fetching base controller version: %w", err) 32 } 33 fmt.Printf("Base controller version: %d.%d.%d\n", version[0], version[1], version[2]) 34 35 for i := 1; i <= p1am.Controller.Slots; i++ { 36 slot := p1am.Controller.Slot(i) 37 fmt.Printf("Slot %d: ID 0x%08x, Props %+v\n", i, slot.ID, slot.Props) 38 } 39 40 slot1 := p1am.Controller.Slot(1) 41 var lastInput uint32 42 state := sw.Get() 43 for { 44 if active, err := p1am.Controller.Active(); err != nil || !active { 45 return fmt.Errorf("controller active %v: %v", active, err) 46 } 47 if state != sw.Get() { 48 state = sw.Get() 49 fmt.Printf("New switch state: %v\n", state) 50 if slot1.Props.DO > 0 { 51 if err := slot1.Channel(1).WriteDiscrete(state); err != nil { 52 return err 53 } 54 } 55 } 56 if slot1.Props.DI > 0 { 57 sstate, err := slot1.ReadDiscrete() 58 if err != nil { 59 return fmt.Errorf("reading slot: %w", err) 60 } 61 if sstate != lastInput { 62 lastInput = sstate 63 fmt.Printf("new DI state: %#b\n", sstate) 64 } 65 } 66 if state { 67 led.High() 68 } else { 69 led.Low() 70 } 71 time.Sleep(time.Millisecond * 10) 72 } 73 return nil 74 }