#PS/2 Keyboard to Bluetooth with ESP32
1 messages · Page 1 of 1 (latest)
First is to understand the PS2 protocol https://www.burtonsys.com/ps2_chapweske.htm on the electrical side. BTW is a steep learning curve.
Also need to step down the 5v signal to 3.3v
So I deduce that there is still no library for PS/2 devices (similar to PS2Keyboard.h)
this is not a problem, I already have a small stepdonw circuit for that
no that i know off
You may then try something like this :
using System;
using System.Device.Gpio;
using System.Threading;
public class Ps2Keyboard
{
private const int ClockPin = 18; // Adjust to your wiring
private const int DataPin = 19; // Adjust to your wiring
private GpioController _gpio;
private GpioPin _clock;
private GpioPin _data;
private int _bitCount = 0;
private int _currentByte = 0;
private bool _reading = false;
public Ps2Keyboard()
{
_gpio = new GpioController();
_clock = _gpio.OpenPin(ClockPin);
_data = _gpio.OpenPin(DataPin);
_clock.SetDriveMode(GpioPinDriveMode.InputPullUp);
_data.SetDriveMode(GpioPinDriveMode.InputPullUp);
_clock.ValueChanged += OnClockFallingEdge;
}
private void OnClockFallingEdge(object sender, PinValueChangedEventArgs args)
{
if (args.Edge != GpioPinEdge.FallingEdge) return;
int bit = _data.Read() == PinValue.High ? 1 : 0;
if (_bitCount == 0)
{
if (bit == 0) _reading = true; // Start bit
}
else if (_bitCount >= 1 && _bitCount <= 8)
{
_currentByte |= (bit << (_bitCount - 1));
}
else if (_bitCount == 9)
{
// Parity bit (can be checked if needed)
}
else if (_bitCount == 10)
{
if (_reading)
{
ProcessScanCode((byte)_currentByte);
}
_currentByte = 0;
_reading = false;
_bitCount = -1;
}
_bitCount++;
}
private void ProcessScanCode(byte scanCode)
{
char key = DecodeScanCode(scanCode);
Debug.WriteLine($"ScanCode: 0x{scanCode:X2} → Key: {key}");
}
private char DecodeScanCode(byte scanCode)
{
return scanCode switch
{
0x1C => 'A',
0x32 => 'B',
0x21 => 'C',
0x23 => 'D',
0x24 => 'E',
0x2B => 'F',
0x34 => 'G',
0x33 => 'H',
0x43 => 'I',
0x3B => 'J',
0x42 => 'K',
0x4B => 'L',
0x3A => 'M',
0x31 => 'N',
0x44 => 'O',
0x4D => 'P',
0x15 => 'Q',
0x2D => 'R',
0x1B => 'S',
0x2C => 'T',
0x3C => 'U',
0x2A => 'V',
0x1D => 'W',
0x22 => 'X',
0x35 => 'Y',
0x1A => 'Z',
0x45 => '0',
0x16 => '1',
0x1E => '2',
0x26 => '3',
0x25 => '4',
0x2E => '5',
0x36 => '6',
0x3D => '7',
0x3E => '8',
0x46 => '9',
_ => '?'
};
}
}
Adjust a bit the pins as needed
public class Program
{
public static void Main()
{
var keyboard = new Ps2Keyboard();
Thread.Sleep(Timeout.Infinite);
}
}