That's pretty handy. Wouldn't it be nice to have some code run whenever you do a shake? Well yes it is handy but how does it actually work? Sniff doesn't have shake detection built in, but its really easy to add it. By doing it in Sniff we actually get to see how it works, rather than it being buried away in a C++ module. In general its better to do the work in Sniff than having a "magic feature" (much as Sniff can handle scrolling text in the language without requiring specific runtime support). While this might look a little complex, its actually far simpler than the way it has to be done in the Microbit runtime.
make i2c device
make sensor mma8652 device
make accX number
make accY number
make accZ number
make shakeStart number
make shakeCounter number
when start
.set shakeCounter to 0
.forever
..set shakeStart to timer
..repeat until accX > 0.5
...tell sensor to "read"
..repeat until accX< -0.5
...tell sensor to "read"
..if timer-shakeStart<0.5
...change shakeCounter by 1
...if shakeCounter>2
....broadcast shake
..else
...set shakeCounter to 0
Firstly we set up the accelerometer. We're going to need two extra variables - one to count the shakes, and another to time them. We initialise both (to zero and the current time respectively). Then we wait for the shakes to start. We read the sensor until the acceleration is greater than 0.5 then wait for it to be less than -0.5. This represents one cycle of a vigorous shake.
Then we use the timer to see how long that took. If it was less than 0.5 seconds then it was actually proper back and forth shake rather than just a couple of separate movements, so we count that as one step of a shake sequence. If we ever get more than two of these, each within 0.5 seconds of the previous ones then we actually have a real shake, so we broadcast shake, telling the rest of the code that something happened. If a single shake takes more than 0.5 seconds then the sequence is broken so we reset the count.
make display microbitDisplay device
make displayX number
make displayY number
make displayColor number
when start
.forever
..tell display to "tick"
when shake
.set displayColor to 777
.tell display to "clear"
.wait 1 secs
.set displayColor to 000
.tell display to "clear"
Here we have some code that waits for the shake. When it gets it, it flashes the screen for one second.
By coding the shake in Sniff we gain lot of benefits - its now maintainable, and customisable by Sniff programers, so if for example you find the shake requires to vigorous a movement for your liking, you can reduce the acceleration threshold. If you'd prefer a vertical or an in/out shake then change the axis. If your getting false triggers you can increase the number of cycles required to count as a proper shake.
Best of all we can see exactly how it works. There's no hidden magic function that just makes it happen. After all isn't the point that we might actually learn something?
No comments:
Post a Comment