github.com/f-secure-foundry/tamago@v0.0.0-20220307101044-d73fcdd7f11b/soc/imx6/gpio.go (about) 1 // NXP i.MX6 GPIO driver 2 // https://github.com/f-secure-foundry/tamago 3 // 4 // Copyright (c) F-Secure Corporation 5 // https://foundry.f-secure.com 6 // 7 // Use of this source code is governed by the license 8 // that can be found in the LICENSE file. 9 10 package imx6 11 12 import ( 13 "fmt" 14 15 "github.com/f-secure-foundry/tamago/internal/reg" 16 ) 17 18 // GPIO constants 19 const ( 20 GPIO1_BASE = 0x0209c000 21 GPIO2_BASE = 0x020a0000 22 GPIO3_BASE = 0x020a4000 23 GPIO4_BASE = 0x020a8000 24 25 GPIO_DR = 0x00 26 GPIO_GDIR = 0x04 27 28 GPIO_MODE = 5 29 ) 30 31 // GPIO instance 32 type GPIO struct { 33 Pad *Pad 34 35 num int 36 data uint32 37 dir uint32 38 } 39 40 // NewGPIO initializes a pad for GPIO mode. 41 func NewGPIO(num int, instance int, mux uint32, pad uint32) (gpio *GPIO, err error) { 42 var base uint32 43 44 if num > 31 { 45 return nil, fmt.Errorf("invalid GPIO number %d", num) 46 } 47 48 if instance < 1 || instance > 4 { 49 return nil, fmt.Errorf("invalid GPIO instance %d", instance) 50 } 51 52 switch instance { 53 case 1: 54 base = GPIO1_BASE 55 case 2: 56 base = GPIO2_BASE 57 case 3: 58 base = GPIO3_BASE 59 case 4: 60 base = GPIO4_BASE 61 } 62 63 gpio = &GPIO{ 64 num: num, 65 data: base + GPIO_DR, 66 dir: base + GPIO_GDIR, 67 } 68 69 gpio.Pad, err = NewPad(mux, pad, 0) 70 71 if !Native || err != nil { 72 return 73 } 74 75 gpio.Pad.Mode(GPIO_MODE) 76 77 return 78 } 79 80 // Out configures a GPIO as output. 81 func (gpio *GPIO) Out() { 82 reg.Set(gpio.dir, gpio.num) 83 } 84 85 // In configures a GPIO as input. 86 func (gpio *GPIO) In() { 87 reg.Clear(gpio.dir, gpio.num) 88 } 89 90 // High configures a GPIO signal as high. 91 func (gpio *GPIO) High() { 92 reg.Set(gpio.data, gpio.num) 93 } 94 95 // Low configures a GPIO signal as low. 96 func (gpio *GPIO) Low() { 97 reg.Clear(gpio.data, gpio.num) 98 } 99 100 // Value returns the GPIO signal level. 101 func (gpio *GPIO) Value() (high bool) { 102 return reg.Get(gpio.data, gpio.num, 1) == 1 103 }