Skip to content

Instantly share code, notes, and snippets.

@ricobeck
Created April 1, 2024 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricobeck/c95711817251427750e188990e448018 to your computer and use it in GitHub Desktop.
Save ricobeck/c95711817251427750e188990e448018 to your computer and use it in GitHub Desktop.
Detecting shake of playdate device
//
// Shaker.swift
//
//
// Created by Rico Becker on 30.03.24.
//
import PlaydateKit
struct Shaker {
let gravity: Float = 9.80665
enum Sensitivity: CInt {
case low = 10
case medium = 15
case high = 20
}
let threshold: Float
let sensitivity: Shaker.Sensitivity
let sampleSize: UInt32
var samples: [Float]
private var index: UInt32 = 0
var isTriggering = false
init(threshold: Float = 0.75, sensitivity: Shaker.Sensitivity = .medium, sampleSize: UInt32 = 20) {
self.threshold = threshold
self.sensitivity = sensitivity
self.sampleSize = sampleSize
samples = Array(repeating: 0, count: Int(sampleSize))
reset()
System.accelerometerIsEnabled = true
}
mutating func reset() {
isTriggering = false
index = 0
samples = Array(repeating: 0, count: Int(sampleSize))
}
mutating func sample() {
var (x, y, z) = System.accelerometer
x *= gravity
y *= gravity
z *= gravity
let acceleration = x * x + y * y + z * z
let sensitivityValue = Float(sensitivity.rawValue)
let isAccelerating = acceleration > (sensitivityValue * sensitivityValue)
index = (index + 1) % sampleSize
samples[Int(index)] = isAccelerating ? 1 : 0
test()
}
mutating func test() {
let avg = samples.reduce(0, +) / Float(sampleSize)
if avg > threshold {
System.log("Trigger shake")
isTriggering = true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment