TS-8100-4700 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 -o kpad  */

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

// The mpeek/mpoke functions are specific to the TS-47XX
volatile uint16_t *muxbus = 0;
int mem = 0;
uint16_t mpeek16(uint16_t addr) 
{
    uint16_t value;
    if (mem == 0)
        mem = open("/dev/mem", O_RDWR|O_SYNC);

    if(muxbus == 0)
        muxbus = mmap(0,
            getpagesize(),
            PROT_READ|PROT_WRITE,
            MAP_SHARED,
            mem,
            0x80008000);

    return muxbus[addr/2];
}

void mpoke16(uint16_t addr, uint16_t value)
{
    if (mem == 0)
        mem = open("/dev/mem", O_RDWR|O_SYNC);

    if(muxbus == 0)
        muxbus = mmap(0,
            getpagesize(),
            PROT_READ|PROT_WRITE,
            MAP_SHARED,
            mem,
            0x80008000);

    muxbus[addr/2] = value;
}

int main()
{
    uint8_t ddr = 0xf0;
    uint8_t out = 0x0f;
    int row, col;

    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
    mpoke16(0x8, ddr);
    mpoke16(0x4, out);

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

    return 0;
}