Using a rotary encoder... fast to code fast to run... Swift!

Using a rotary encoder... fast to code fast to run... Swift!



If you’ve ever written code for handling a rotary encoder before in another microcontroller IDE you’ll know it can be... complex.

A rotary encoder is the fancy name for one of those dials that can turn endlessly, unlike a potentiometer or rheostat. Think of the “jog wheels” on some DVD players.

They’re really cool but the code to handle them can be tricky. They give you two pins that turn on and off in a specific sequence depending if turned clockwise or counter clockwise (anti clockwise if you’re British).

So to code you need to know the current state of both pins and the previous stare of both pins and see what changed. From which there are about 9 possibilities, one being “no change” then 4 changes that indicate a turn one way and four that indicate a turn the other way. Does that sound like a switch statement in Swift? It sure does!

Look at this code!...

  let currentPinState = (digitalRead(pin: pin1), digitalRead(pin: pin2))

  switch (lastPinState, currentPinState) {

    case
      ((false, false), (true, false)),
      ((true, false), (true, true)),
      ((true, true), (false, true)),
      ((false, true), (false, false)) :

      clockwise()
      debounce()

    case
      ((false, false), (false, true)),
      ((false, true), (true, true)),
      ((true, true), (true, false)),
      ((true, false), (false, false)) :

      counterclockwise()
      debounce()

    default:

      break
  }

  lastPinState = currentPinState

Here’s a link to the examples/components library where you can see it in action.

https://github.com/swiftforarduino/community/tree/master/contributed%20examples

Look at the strobe-fan-sync example. Download the whole directory if you want to use it (it's a bundle like all swift for arduino documents).

The core code is in this library file, which you can add directly to your own s4a document if you prefer: https://github.com/swiftforarduino/community/blob/master/contributed%20libraries/rotaryEncoder.swift


Here are a couple of short videos demonstrating the code...

https://youtu.be/AgOF2tStIrs The video explaining the principles and demonstrating using a rotary encoder as a cool addition to the fan/strobe project.


And here’s videos of the strobe in the dark so you can really see the effect:

https://youtu.be/voY-VMM3nrg

https://youtu.be/T3GkFbEqJKk


If you haven't already got it, go to www.swiftforarduino.com and get coding in Swift on the Arduino platform today! You won't regret it!

Comments

Popular posts from this blog

Halloween LED lights on a plastic trick or treat cauldron

All about bootloaders

code signing, entitlements, bundles, sandboxes, hardened runtime, notarisation, app store security