Last active
December 20, 2015 09:19
-
-
Save stianeikeland/6107207 to your computer and use it in GitHub Desktop.
This file contains 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" | |
"os" | |
"reflect" | |
"syscall" | |
"unsafe" | |
) | |
type Direction uint8 | |
type Pin uint8 | |
type State uint8 | |
// http://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf | |
const ( | |
Bcm2835_Base = 0x20000000 | |
Gpio_Base = Bcm2835_Base + 0x200000 | |
) | |
const ( | |
INPUT Direction = iota | |
OUTPUT | |
) | |
const ( | |
LOW State = iota | |
HIGH | |
) | |
const PINMASK uint32 = 7 // 0b111 | |
var ( | |
mem []uint32 | |
mem8 []uint8 | |
) | |
func (pin Pin) Mode(dir Direction) { | |
PinMode(uint8(pin), dir) | |
} | |
func (pin Pin) Write(state State) { | |
WritePin(uint8(pin), state) | |
} | |
func (pin Pin) Read() { | |
ReadPin(uint8(pin)) | |
} | |
func PinMode(pin uint8, direction Direction) { | |
fsel := pin / 10 | |
shift := (pin % 10) * 3 | |
fmt.Println(pin, fsel, shift) | |
fmt.Printf("0b%b \n", mem[fsel]) | |
if direction == INPUT { | |
fmt.Printf("0b%b\n\n", mem[fsel]&^(PINMASK<<shift)) | |
} else { | |
fmt.Printf("0b%b\n\n", mem[fsel]&^(PINMASK<<shift)|(1<<shift)) | |
} | |
} | |
func WritePin(pin uint8, state State) { | |
clearReg := pin/32 + 10 | |
setReg := pin/32 + 7 | |
if state == LOW { | |
fmt.Printf("0b%b \n", mem[clearReg]) | |
fmt.Printf("0b%b\n\n", 1<<(pin&31)) | |
} else { | |
fmt.Printf("0b%b \n", mem[setReg]) | |
fmt.Printf("0b%b\n\n", 1<<(pin&31)) | |
} | |
} | |
func ReadPin(pin uint8) { | |
} | |
func Open() (err error) { | |
var file *os.File | |
// Open fd for rw mem access | |
file, err = os.OpenFile("/dev/mem", os.O_RDWR|os.O_SYNC, 0) | |
if err != nil { | |
return | |
} | |
// Can be closed after memory mapping | |
defer file.Close() | |
// Memory map GPIO registers to byte array | |
mem8, err = syscall.Mmap(int(file.Fd()), Gpio_Base, 4*1024, syscall.PROT_READ, syscall.MAP_SHARED) | |
if err != nil { | |
return | |
} | |
// Convert mapped byte memory to unsafe []uint32 pointer, adjust length as needed | |
header := *(*reflect.SliceHeader)(unsafe.Pointer(&mem8)) | |
header.Len /= (32 / 8) // (32 bit = 4 bytes) | |
header.Cap /= (32 / 8) | |
mem = *(*[]uint32)(unsafe.Pointer(&header)) | |
return nil | |
} | |
func Close() { | |
// Unmap memory | |
syscall.Munmap(mem8) | |
} | |
func main() { | |
if err := Open(); err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
defer Close() | |
var pin4 Pin = 4 | |
pin4.Mode(OUTPUT) | |
pin4.Mode(INPUT) | |
pin4.Write(HIGH) | |
pin4.Write(LOW) | |
PinMode(1, OUTPUT) | |
PinMode(1, INPUT) | |
WritePin(1, HIGH) | |
WritePin(1, LOW) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment