librfn
An ad-hoc utility library
rotenc.c
Go to the documentation of this file.
1 /*
2  * rotenc.c
3  *
4  * Part of librfn (a general utility library from redfelineninja.org.uk)
5  *
6  * Copyright (C) 2016 Daniel Thompson <daniel@redfelineninja.org.uk>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as published
10  * by the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  */
13 
14 #include "librfn/rotenc.h"
15 
16 void rotenc_decode(rotenc_t *r, uint8_t state)
17 {
18 #define FROM(x, y) (((!!x) << 3) + ((!!y) << 2))
19 #define TO(x, y) (((!!x) << 1) + (!!y))
20  uint8_t fromto = (r->last_state << 2) + state;
21 
22  switch (fromto) {
23  /* clockwise */
24  case FROM(0, 0) | TO(0, 1):
25  case FROM(0, 1) | TO(1, 1):
26  case FROM(1, 1) | TO(1, 0):
27  case FROM(1, 0) | TO(0, 0):
28  r->internal_count++;
29  break;
30 
31  /* anticlockwise */
32  case FROM(0, 0) | TO(1, 0):
33  case FROM(1, 0) | TO(1, 1):
34  case FROM(1, 1) | TO(0, 1):
35  case FROM(0, 1) | TO(0, 0):
36  r->internal_count--;
37  break;
38  }
39 
40  r->last_state = state;
41  if (!state)
42  r->count = r->internal_count >> 2;
43 }
44 
46 {
47  return ((r->internal_count >> 2) & 0x3f00) + r->count;
48 }
49 
uint8_t last_state
Definition: rotenc.h:31
void rotenc_decode(rotenc_t *r, uint8_t state)
Handle a state update.
Definition: rotenc.c:16
fibre_state_t state
Definition: fibre.c:30
#define FROM(x, y)
uint16_t internal_count
Definition: rotenc.h:33
#define TO(x, y)
uint16_t rotenc_count14(rotenc_t *r)
Read a 14-bit count of the current knob position.
Definition: rotenc.c:45
uint8_t count
Definition: rotenc.h:32
Rotary encoder click counts and state tracking.
Definition: rotenc.h:30