-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdirectMemory.swift
63 lines (51 loc) · 2.34 KB
/
directMemory.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/swift
import Foundation // for String(format, )
import Glibc // for mmap
func loopGPIO() {
let file = open("/dev/mem", O_RDWR | O_SYNC);
defer { close(file) }
// Open the /dev/mem file (all memory) with read and write
// privileges (we want to turn on output pins) at the proper
// offset (we don't care about the rest of the addresses)
// 0x3f200000
guard let rawPointer = mmap(nil, 1024 * 4, PROT_READ | PROT_WRITE, MAP_SHARED, file, 0x3f200000) else {
perror("Cannot mmap bytes for path")
return
}
// This is a typed pointer to the root of the GPIO configuration
// registers. Pointer math will increment by 4 bytes at a time.
let basePointer: UnsafeMutablePointer<UInt32> = rawPointer.bindMemory(to: UInt32.self, capacity: 30)
// Configure GPIO pin 4 & 6 as output (3 bits/pin)
// pin numbers: 8 7 6 5 4 3 2 1 0
// basePointer.pointee = 0b000001001000000000000000
guard let rawPointer2 = mmap(nil, 1024 * 4, PROT_READ | PROT_WRITE, MAP_SHARED, file, 0x3f200000) else {
perror("Cannot mmap bytes for path")
return
}
// let basePointer2: UnsafeMutabl ePointer<UInt32> = rawPointer2.bindMemory(to: UInt32.self, capacity: 30)
// pin numbers: 22 21 20 19 18 17 16 15 14 13 12 11 // 10 9 8 7 6 5 4 3 2 1 0
// basePointer2.pointee = 0b00001000000000000000000000000000 //000000000000001001000000000000000
// Set up set/clear pointer objects
// Offsets from docs were given in byte-size values
// since our pointers are smart and expecting word
// size values we convert
let setPointer = basePointer + 0x1C/4
let clearPointer = basePointer + 0x28/4
// Print the details for sanity sake
print("Configuration Details")
print(" address: \(basePointer)")
print(String(format: " format: 0x%X", basePointer.pointee))
print("Set pointer: \(setPointer)")
print("Clear pointer: \(clearPointer)")
// Loop through and show the LED turning on and off
for i in 0...5 {
print("High \(setPointer)")
setPointer.pointee = 0b100000100000000000001100000 // Pin 20, 6 & 5
usleep(500000)
print("Counter: \(i)")
print("Low \(clearPointer)")
clearPointer.pointee = 0b100000100000000000001100000 // Pin 20, 6 & 5
usleep(500000)
}
}
loopGPIO()