/* ============================================
  code is placed under the MIT license
  Copyright (c) 2024 J-M-L
  For the Arduino Forum : https://forum.arduino.cc/u/j-m-l

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
  ===============================================
*/

#include <Wire.h>
#include <hd44780.h>                        // main hd44780 header
#include <hd44780ioClass/hd44780_I2Cexp.h>  // i2c expander i/o class header
#include <Encoder.h>                        // https://www.pjrc.com/teensy/td_libs_Encoder.html

const byte encoderCLKPin = 2;
const byte encoderDTPin = 3;
Encoder encoder(encoderDTPin, encoderCLKPin);
long encoderPosition = 0;

const uint8_t nbCols = 16;
const uint8_t nbRows = 2;
hd44780_I2Cexp lcd;

bool encoderChanged() {
  long newPosition = encoder.read() >> 2; // divide by 4 as the rotary sends 4 ticks per click
  if (newPosition != encoderPosition) {
    encoderPosition = newPosition;
    return true;
  }
  return false;
}

void encoder0() {
  encoder.write(encoder.read() & 0b11); // keep the sub ticks
  encoderPosition = 0;
}

void encoder255() {
  long newPos = (0xFFL << 2) | (encoder.read() & 0b11L); // // keep the sub ticks
  encoder.write(newPos);
  encoderPosition = 255;
}

void showCode(uint8_t number) {
  lcd.setCursor(8, 0);
  if (number < 10) lcd.write('0');
  lcd.print(number, HEX);
  lcd.setCursor(14, 0);
  lcd.write((char) number);
}

void setup() {
  Serial.begin(115200);

  int result = lcd.begin(nbCols, nbRows);
  if (result) {
    Serial.print("LCD initialization failed: ");
    Serial.println(result);
    hd44780::fatalError(result);
  }
  lcd.clear();
  lcd.print("byte: 0x00 -> ");
  showCode(encoderPosition);
}

void loop() {
  if (encoderChanged()) {
    if (encoderPosition > 255) encoder0();
    else if (encoderPosition < 0) encoder255();
    showCode(encoderPosition);
  }
}