Upgrade to Pro — share decks privately, control downloads, hide ads and more …

SwiftではじめるRaspberry Pi

SwiftではじめるRaspberry Pi

Satoshi Kobayashi

September 02, 2018
Tweet

Transcript

  1. -νΧ1BDLBHFKTPO import PackageDescription let package = Package( name: "led", dependencies:

    [ .Package(url: "https://github.com/uraimo/ SwiftyGPIO.git", majorVersion: 1), ] )
  2. -νΧNBJOTXJGU import SwiftyGPIO import Glibc let gpios = SwiftyGPIO.GPIOs(for:.RaspberryPi3) let

    gp = gpios[.P25]! gp.direction = .OUT gp.value = 1 repeat { gp.value = (gp.value == 0) ? 1 : 0 usleep(500 * 1000) } while (true)
  3. let gpios = SwiftyGPIO.GPIOs(for: .RaspberryPi3) let gpo = gpios[.P25]! gpo.direction

    = .OUT gpo.value = 0 let gpi = gpios[.P24]! gpi.direction = .IN gpi.pull = .down var ledState = false gpi.onRaising({(gpio) -> Void in ledState = !ledState if ledState { gpo.value = 1 } else { gpo.value = 0 } })
  4. CPVODFUJNF w31J(1*0 QZUIPO wHQJP[FSP QZUIPO # add rising edge detection

    on a channel, ignoring further edges for 200ms for switch bounce handling GPIO.add_event_detect(channel, GPIO.RISING, callback=my_callback, bouncetime=200) class gpiozero.Button(pin, *, pull_up=True, bounce_time=None, hold_time=1, hold_repeat=False, pin_factory=None)
  5. %J⒎ public class GPIO { + public var bounceTime: TimeInterval?

    - var intFuncFalling: ((GPIO) -> Void)? - var intFuncRaising: ((GPIO) -> Void)? - var intFuncChange: ((GPIO) -> Void)? + var intFalling: (func: ((GPIO) -> Void), lastCall: Date?)? + var intRaising: (func: ((GPIO) -> Void), lastCall: Date?)? + var intChange: (func: ((GPIO) -> Void), lastCall: Date?)? public func onRaising(_ closure: @escaping (GPIO) -> Void) { - intFuncRaising = closure + intRaising = (func: closure, lastCall: nil) if intThread == nil { intThread = makeInterruptThread() listening = true
  6. func interrupt(type: inout (func: ((GPIO) -> Void), lastCall: Date?)?) {

    guard let itype = type else { return } if let interval = self.bounceTime, let lastCall = itype.lastCall, Date().timeIntervalSince(lastCall) < interval { return } itype.func(self) type?.lastCall = Date() }
  7. while self.listening { let ready = poll(&pfd, 1, -1) if

    ready > -1 { … switch res { case “0": - self.intFuncFalling?(self) + self.interrupt(type: &(self.intFalling)) case “1": - self.intFuncRaising?(self) + self.interrupt(type: &(self.intRaising)) default: break } - self.intFuncChange?(self) + self.interrupt(type: &(self.intChange)) } }