Keyboard class is almost done

This commit is contained in:
2021-09-28 23:02:49 +02:00
commit 230d843457
10 changed files with 332 additions and 0 deletions
+103
View File
@@ -0,0 +1,103 @@
#include "Keyboard.h"
//#define DEBUG
#define PIN_WIRE_SDA D3
#define PIN_WIRE_SCL D4
Keyboard::Keyboard(uint8_t debounce)
{
this->debounce = debounce;
}
void Keyboard::begin(TwoWire *databus)
{
pcf8574 = new PCF8574(databus, 0x27, PIN_WIRE_SDA, PIN_WIRE_SCL);
pcf8574->pinMode(0, OUTPUT);
for (int i = 1; i < 8; i++)
{
if (i < 5)
pcf8574->pinMode(i, INPUT_PULLUP);
else
pcf8574->pinMode(i, OUTPUT);
}
Serial.print("Init pcf8574...");
if (pcf8574->begin())
Serial.println("OK");
else
Serial.println("KO");
pcf8574->digitalWrite(1, HIGH);
for (int i = 5; i < 8; i++)
pcf8574->digitalWrite(i, HIGH);
}
Keyboard::~Keyboard()
{
if (pcf8574 != nullptr)
delete pcf8574;
}
void Keyboard::scan()
{
if (millis() < timeElapsed + this->debounce)
return 0;
uint8_t key = 0;
for (int i = 7; i > 4; i--) // Columns
{
pcf8574->digitalWrite(i, LOW);
for (int j = 1; j < 5; j++)
{ // Rows
key++;
uint8_t val = pcf8574->digitalRead(j);
#ifdef DEBUG
Serial.println("i=" + String(i) + " j=" + String(j) + " v=" + String(val));
delay(500);
#endif
if (val == 0)
{
timeElapsed = millis();
this->lastKey = key;
this->buffer.push(mapChr(key));
}
}
pcf8574->digitalWrite(i, HIGH);
}
}
char Keyboard::mapChr(uint8_t key)
{
switch (key)
{
case 1:
return '1';
case 2:
return '4';
case 3:
return '7';
case 4:
return 'O';
case 5:
return '5';
case 6:
return '1';
case 7:
return '8';
case 8:
return '0';
case 9:
return '3';
case 10:
return '6';
case 11:
return '9';
case 12:
return 'X';
default:
return 'F';
}
}
char Keyboard::getChr()
{
return this->getChr(this->lastKey);
}
bool Keyboard::available(){
return (!this->buffer.empty());
}
+23
View File
@@ -0,0 +1,23 @@
#ifndef KEYBOARD_CLASS
#define KEYBOARD_CLASS
#include "PCF8574.h"
#include <bits/stdc++.h>
class Keyboard
{
private:
unsigned long timeElapsed;
std::queue<char> buffer;
uint8_t debounce;
PCF8574* pcf8574;
int lastKey;
/* data */
public:
Keyboard(uint8_t debounce);
~Keyboard();
void scan();
void begin(TwoWire *databus);
static char getChr(uint8_t key);
char getChr();
bool available();
};
#endif
+26
View File
@@ -0,0 +1,26 @@
#include <Arduino.h>
#include <Wire.h>
#include "Keyboard.h"
#define PIN_WIRE_SDA D3
#define PIN_WIRE_SCL D4
#include <LiquidCrystal_I2C.h>
TwoWire databus;
Keyboard keyboard(200);
void setup()
{
Serial.begin(9600);
Serial.print("Starting");
delay(500);
keyboard.begin(&databus);
}
void loop()
{
char key = keyboard.getKey();
if(key!=0)
Serial.println("Key " + String(key) + "was pressed");
}