TS-8100-4500 kpad

From embeddedTS Manuals

This header is designed to connect to the KPAD accessory which uses the odd DIO on this header to scan a 4x4 keypad. This example scans the KPAD and prints out the pressed character.

/* KPAD 4x4 keypad example code
 *
 * To compile, copy to the board and run:
 *  gcc kpad.c sbus.c -o kpad  */

#include <stdio.h>
#include <stdint.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "sbus.h"

int main()
{
    uint8_t ddr = 0xf0;
    uint8_t out = 0x0f;
    int row, col;
    sbuslock();
    winpoke16(0x20000, 0x181);
    sbusunlock();

    char *keys[4][4] = {
        { "1", "2", "3", "UP" },
        { "4", "5", "6", "DOWN" },
        { "7", "8", "9", "2ND" },
        { "CLEAR", "0", "HELP", "ENTER" }
    };

    //set first 4 as outputs, last 4 as inputs
    sbuslock();
    winpoke16(0x8, ddr);
    winpoke16(0x4, out);
    sbusunlock();

    while(1) {
        for(row = 0; row < 4; row++) {
            sbuslock();
            winpoke16(0x8, ddr | (1 << row));
            winpoke16(0x4, out | (1 << row));
            sbusunlock();
            usleep(50000);
            sbuslock();
            uint16_t in = winpeek16(0xc);
            sbusunlock();
            for(col = 4; col < 8; col++) {
                if(in & (1 << col)) {
                    // If we read it, sleep and read again to debounce
                    usleep(1000);
                    sbuslock();
                    in = winpeek16(0xc);
                    sbusunlock();
                    if(in & (1 << col)) {
                        printf("%s\n", keys[row][col - 4]);
                        fflush(stdout);
                    }
                }
            }
        }
    }

    return 0;
}