msm8909矩阵按键驱动笔记

此文章仅作本人自己笔记使用,文章结束部分有本人调试过程,可以借鉴,由于没有仔细排版,所以可阅读性不高,读者见谅!

一般按键驱动有两种,一个是矩阵键盘驱动,一个是GPIO接口键盘驱动
矩阵键盘路径 : kernel/driers/input/keyboard/matrix_keypad.c 
    :一般用于多按键的情况 (手机)

GPIO接口键盘路径 :kernel/driers/input/keyboard/gpio_keys.c
    :一般用于少按键的情况

键盘属于输入子系统范围
adb shell
cat /proc/bus/input/devices 
 得到 matrix_keypad设备信息

修改 matrix_keypad 键盘相关设备树 msm8909-E8909-mtp.dtsi  matrix_keypad键盘相关参数

代码如下
//自定义矩阵按键 结构体
struct matrix_keypad {
const struct matrix_keypad_platform_data *pdata;
struct input_dev *input_dev;
unsigned int row_shift;

DECLARE_BITMAP(disabled_gpios, MATRIX_MAX_ROWS);

uint32_t last_key_state[MATRIX_MAX_COLS];
struct delayed_work work;
struct mutex lock;
bool scan_pending;
bool stopped;
bool gpio_all_disabled;
};

static void __activate_col(const struct matrix_keypad_platform_data *pdata,
           int col, bool on)
{
bool level_on = !pdata->active_low;

if (on) {
    gpio_direction_output(pdata->col_gpios[col], level_on);
} else {
    gpio_set_value_cansleep(pdata->col_gpios[col], !level_on);
    gpio_direction_input(pdata->col_gpios[col]);
}
}

static void activate_col(const struct matrix_keypad_platform_data *pdata,
         int col, bool on)
{
__activate_col(pdata, col, on);

if (on && pdata->col_scan_delay_us)
    udelay(pdata->col_scan_delay_us);
}

static void activate_all_cols(const struct matrix_keypad_platform_data *pdata,
              bool on)
{
int col;

for (col = 0; col < pdata->num_col_gpios; col++)
    __activate_col(pdata, col, on);
}


static bool row_asserted(const struct matrix_keypad_platform_data *pdata,
         int row)
{
return gpio_get_value_cansleep(pdata->row_gpios[row]) ?
        !pdata->active_low : pdata->active_low;
}

//使能中断
static void enable_row_irqs(struct matrix_keypad *keypad)
{
const struct matrix_keypad_platform_data *pdata = keypad->pdata;
int i;

if (pdata->clustered_irq > 0)
    enable_irq(pdata->clustered_irq);
else {
    for (i = 0; i < pdata->num_row_gpios; i++)
        //使能中断
        enable_irq(gpio_to_irq(pdata->row_gpios[i]));
}
}

//关闭中断
static void disable_row_irqs(struct matrix_keypad *keypad)
{
const struct matrix_keypad_platform_data *pdata = keypad->pdata;
int i;

if (pdata->clustered_irq > 0)
    disable_irq_nosync(pdata->clustered_irq);
else {
    for (i = 0; i < pdata->num_row_gpios; i++)
        //关闭中断
        disable_irq_nosync(gpio_to_irq(pdata->row_gpios[i]));
}
}

//按键扫描,中断处理机制下半部,用于扫描矩阵按键
/* 按列扫描矩阵按键,矩阵按键的扫描原理请自行百度,此处不做详细说明 
 * 此函数功能是 :
 * 1 :扫描矩阵按键,并且将每一列按键的状态 按照按键所在行数 左移row位,
 * 这样每一列的按键状态都可以用一个数值表示,最终将多个列的按键状态(处理后的数值)
 * 存储在一个数组中,
 * 2 :将扫描处理后的矩阵按键状态数值 上报
 *
 */
static void matrix_keypad_scan(struct work_struct *work)
{
struct matrix_keypad *keypad =
    container_of(work, struct matrix_keypad, work.work);
struct input_dev *input_dev = keypad->input_dev;
const unsigned short *keycodes = input_dev->keycode;
const struct matrix_keypad_platform_data *pdata = keypad->pdata;
uint32_t new_state[MATRIX_MAX_COLS];
int row, col, code;
/* de-activate all columns for scanning */
activate_all_cols(pdata, false); //把所有的列线改为输入功能  电压0
memset(new_state, 0, sizeof(new_state));

/* assert each column and read the row status out */
for (col = 0; col < pdata->num_col_gpios; col++) {

activate_col(pdata, col, true);  //把指定的列线改为输出

    for (row = 0; row < pdata->num_row_gpios; row++)
    {
        new_state[col] |= row_asserted(pdata, row) ? (1 << row) : 0;
    }
activate_col(pdata, col, false);  //把所有的列线改为输入功能
}

//检查按键状态,如果和上一次不一样 则上报事件                    
for (col = 0; col < pdata->num_col_gpios; col++) {
    uint32_t bits_changed;

    bits_changed = keypad->last_key_state[col] ^ new_state[col];
    if (bits_changed == 0)
        continue;

    for (row = 0; row < pdata->num_row_gpios; row++) {
        if ((bits_changed & (1 << row)) == 0)
            continue;


            code = MATRIX_SCAN_CODE(row, col, keypad->row_shift);
//提交输入事件
input_event(input_dev, EV_MSC, MSC_SCAN, code);

//提交按键值
input_report_key(input_dev,
    keycodes[code],
    new_state[col] & (1 << row));

    }
}

//同步
input_sync(input_dev);

memcpy(keypad->last_key_state, new_state, sizeof(new_state));

activate_all_cols(pdata, true);

mutex_lock(&keypad->lock);
keypad->scan_pending = false;
enable_row_irqs(keypad);
mutex_unlock(&keypad->lock);
}


//中断函数 中断处理机制上半部
static irqreturn_t matrix_keypad_interrupt(int irq, void *id)

{
struct matrix_keypad *keypad = id;
mutex_lock(&keypad->lock);

/*
 * See if another IRQ beaten us to it and scheduled the
 * scan already. In that case we should not try to
 * disable IRQs again.
 */
if (unlikely(keypad->scan_pending || keypad->stopped))
    goto out;

disable_row_irqs(keypad);
keypad->scan_pending = true;
//中断处理机制上半部,上半部处理后 调度一个延后的工作队列(下半部)
schedule_delayed_work(&keypad->work,msecs_to_jiffies(keypad->pdata->debounce_ms));

out:
mutex_unlock(&keypad->lock);
return IRQ_HANDLED;
}

static int matrix_keypad_start(struct input_dev *dev)
{
struct matrix_keypad *keypad = input_get_drvdata(dev);

keypad->stopped = false;
mb();

//调度一个延后的工作队列用来扫描矩阵键盘
schedule_delayed_work(&keypad->work, 0);

return 0;
}

static void matrix_keypad_stop(struct input_dev *dev)
{
struct matrix_keypad *keypad = input_get_drvdata(dev);

keypad->stopped = true;
mb();
flush_work(&keypad->work.work);
/*
 * matrix_keypad_scan() will leave IRQs enabled;
 * we should disable them now.
 */
disable_row_irqs(keypad);
}

#ifdef CONFIG_PM_SLEEP
static void matrix_keypad_enable_wakeup(struct matrix_keypad *keypad)

{
const struct matrix_keypad_platform_data *pdata = keypad->pdata;
unsigned int gpio;
int i;

if (pdata->clustered_irq > 0) {
    if (enable_irq_wake(pdata->clustered_irq) == 0)
        keypad->gpio_all_disabled = true;
} else {

    for (i = 0; i < pdata->num_row_gpios; i++) {
        if (!test_bit(i, keypad->disabled_gpios)) {
            gpio = pdata->row_gpios[i];

            if (enable_irq_wake(gpio_to_irq(gpio)) == 0)
                __set_bit(i, keypad->disabled_gpios);
        }
    }
}

}

static void matrix_keypad_disable_wakeup(struct matrix_keypad *keypad)
{
    const struct matrix_keypad_platform_data *pdata = keypad->pdata;
unsigned int gpio;
int i;

if (pdata->clustered_irq > 0) {
    if (keypad->gpio_all_disabled) {
        disable_irq_wake(pdata->clustered_irq);
        keypad->gpio_all_disabled = false;
    }
} else {
    for (i = 0; i < pdata->num_row_gpios; i++) {
        if (test_and_clear_bit(i, keypad->disabled_gpios)) {
            gpio = pdata->row_gpios[i];
            disable_irq_wake(gpio_to_irq(gpio));
        }
    }
}
}

static int matrix_keypad_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct matrix_keypad *keypad = platform_get_drvdata(pdev);

matrix_keypad_stop(keypad->input_dev);

if (device_may_wakeup(&pdev->dev))
    matrix_keypad_enable_wakeup(keypad);

return 0;}

static int matrix_keypad_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct matrix_keypad *keypad = platform_get_drvdata(pdev);

if (device_may_wakeup(&pdev->dev))
    matrix_keypad_disable_wakeup(keypad);

matrix_keypad_start(keypad->input_dev);

return 0;
}
#endif

static SIMPLE_DEV_PM_OPS(matrix_keypad_pm_ops,
         matrix_keypad_suspend, matrix_keypad_resume);


/* 初始化矩阵按键GPIO,假设矩阵按键由 n行,m列 个GPIO组成
 * 此函数先对 所有(m)列GPIO进行request申请,并且使用 gpio_derectout_output把所有(m)列GPIO
 * 端口设置成输出端,输出高电平,然后对所有行(n)GPIO进行request申请,并且使用gpio_derectout_input
 * 将GPIO设置成输入口,并且使用request_irq() 就所有(n)行GPIO设置为外部中断。
 */
static int matrix_keypad_init_gpio(struct platform_device *pdev,
               struct matrix_keypad *keypad)
{
const struct matrix_keypad_platform_data *pdata = keypad->pdata;
int i, err;

/* initialized strobe lines as outputs, activated */
for (i = 0; i < pdata->num_col_gpios; i++) {
    err = gpio_request(pdata->col_gpios[i], "matrix_kbd_col");
    if (err) {
        dev_err(&pdev->dev,
    lia     "failed to request GPIO%d for COL%d\n",
            pdata->col_gpios[i], i);
        goto err_free_cols;
    }

    gpio_direction_output(pdata->col_gpios[i], !pdata->active_low);
}

for (i = 0; i < pdata->num_row_gpios; i++) {
    err = gpio_request(pdata->row_gpios[i], "matrix_kbd_row");
    if (err) {
        dev_err(&pdev->dev,
            "failed to request GPIO%d for ROW%d\n",
            pdata->row_gpios[i], i);
        goto err_free_rows;
    }

    gpio_direction_input(pdata->row_gpios[i]);
}

if (pdata->clustered_irq > 0) {
    err = request_irq(pdata->clustered_irq,
            matrix_keypad_interrupt,
            pdata->clustered_irq_flags,
            "matrix-keypad", keypad);
    if (err < 0) {
        dev_err(&pdev->dev,
            "Unable to acquire clustered interrupt\n");
        goto err_free_rows;
    }
} else {
    for (i = 0; i < pdata->num_row_gpios; i++) {
        err = request_threaded_irq(
                gpio_to_irq(pdata->row_gpios[i]),
                NULL,
                matrix_keypad_interrupt,
                IRQF_DISABLED | IRQF_ONESHOT |
                IRQF_TRIGGER_RISING |
                IRQF_TRIGGER_FALLING,
                "matrix-keypad", keypad);
        if (err < 0) {
            dev_err(&pdev->dev,
                "Unable to acquire interrupt for GPIO line %i\n",
                pdata->row_gpios[i]);
            goto err_free_irqs;
        }
    }
}

/* initialized as disabled - enabled by input->open */
disable_row_irqs(keypad);
return 0;

err_free_irqs:
while (--i >= 0)
    free_irq(gpio_to_irq(pdata->row_gpios[i]), keypad);
i = pdata->num_row_gpios;
err_free_rows:
while (--i >= 0)
    gpio_free(pdata->row_gpios[i]);
i = pdata->num_col_gpios;
err_free_cols:
while (--i >= 0)
    gpio_free(pdata->col_gpios[i]);

return err;
}


//释放GPIO
static void matrix_keypad_free_gpio(struct matrix_keypad *keypad)
{
const struct matrix_keypad_platform_data *pdata = keypad->pdata;
int i;

if (pdata->clustered_irq > 0) {
    free_irq(pdata->clustered_irq, keypad);
} else {
    for (i = 0; i < pdata->num_row_gpios; i++)
        free_irq(gpio_to_irq(pdata->row_gpios[i]), keypad);
}

for (i = 0; i < pdata->num_row_gpios; i++)
    gpio_free(pdata->row_gpios[i]);

for (i = 0; i < pdata->num_col_gpios; i++)
    gpio_free(pdata->col_gpios[i]);
}

#ifdef CONFIG_OF
static struct matrix_keypad_platform_data *
matrix_keypad_parse_dt(struct device *dev)
{
struct matrix_keypad_platform_data *pdata;
struct device_node *np = dev->of_node;
unsigned int *gpios;
int i, nrow, ncol;

if (!np) {
    dev_err(dev, "device lacks DT data\n");
    return ERR_PTR(-ENODEV);
}

pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata) {
    dev_err(dev, "could not allocate memory for platform data\n");
    return ERR_PTR(-ENOMEM);
}

pdata->num_row_gpios = nrow = of_gpio_named_count(np, "row-gpios");
pdata->num_col_gpios = ncol = of_gpio_named_count(np, "col-gpios");
if (nrow <= 0 || ncol <= 0) {
    dev_err(dev, "number of keypad rows/columns not specified\n");
    return ERR_PTR(-EINVAL);
}

if (of_get_property(np, "linux,no-autorepeat", NULL))
    pdata->no_autorepeat = true;
if (of_get_property(np, "linux,wakeup", NULL))
    pdata->wakeup = true;
if (of_get_property(np, "gpio-activelow", NULL))
    pdata->active_low = true;

of_property_read_u32(np, "debounce-delay-ms", &pdata->debounce_ms);
of_property_read_u32(np, "col-scan-delay-us",
                    &pdata->col_scan_delay_us);

gpios = devm_kzalloc(dev,
             sizeof(unsigned int) *
            (pdata->num_row_gpios + pdata->num_col_gpios),
             GFP_KERNEL);
if (!gpios) {
    dev_err(dev, "could not allocate memory for gpios\n");
    return ERR_PTR(-ENOMEM);
}

for (i = 0; i < pdata->num_row_gpios; i++)
    gpios[i] = of_get_named_gpio(np, "row-gpios", i);

for (i = 0; i < pdata->num_col_gpios; i++)
    gpios[pdata->num_row_gpios + i] =
        of_get_named_gpio(np, "col-gpios", i);

pdata->row_gpios = gpios;
pdata->col_gpios = &gpios[pdata->num_row_gpios];

return pdata;
}
#else
static inline struct matrix_keypad_platform_data *
matrix_keypad_parse_dt(struct device *dev)
{
dev_err(dev, "no platform data defined\n");

return ERR_PTR(-EINVAL);
}
#endif

static int matrix_keypad_probe(struct platform_device *pdev)
{
    //平台提供的 platform_data
const struct matrix_keypad_platform_data *pdata; 

struct matrix_keypad *keypad;
//输入设备结构体
struct input_dev *input_dev; 
int err;

//获取 platform_device->device->device_private.driver_data 平台设备私有数据
pdata = dev_get_platdata(&pdev->dev);
if (!pdata) {
    pdata = matrix_keypad_parse_dt(&pdev->dev);
    if (IS_ERR(pdata)) {
        dev_err(&pdev->dev, "no platform data defined\n");
        return PTR_ERR(pdata);
    }
} else if (!pdata->keymap_data) {
    dev_err(&pdev->dev, "no keymap data defined\n");
    return -EINVAL;
}

//申请 keypad 按键设备结构体,可以将指针保存到 platform_device->device->device_private.driver_data 
//作为平台设备的私有指针
keypad = kzalloc(sizeof(struct matrix_keypad), GFP_KERNEL);

//将会分配一个 input_dev 设备结构体,并且在 /sys/class/input/input-n 下创建设备属性文件
input_dev = input_allocate_device();
if (!keypad || !input_dev) {
    err = -ENOMEM;
    goto err_free_mem;
}

//设置 keypad 结构体
keypad->input_dev = input_dev; //初始化 矩阵按键 input_dev 结构体 为当前申请的input_dev
keypad->pdata = pdata;
keypad->row_shift = get_count_order(pdata->num_col_gpios);
keypad->stopped = true;
//初始化 延时工作队列
INIT_DELAYED_WORK(&keypad->work, matrix_keypad_scan);

//初始化互斥体
mutex_init(&keypad->lock);

//初始化 input 输入设备结构体
input_dev->name     = pdev->name;
input_dev->id.bustype   = BUS_HOST;
input_dev->dev.parent   = &pdev->dev;
input_dev->open     = matrix_keypad_start;
input_dev->close    = matrix_keypad_stop;

//从 keymap_data 里面分解出行列键对应的码值
err = matrix_keypad_build_keymap(pdata->keymap_data, NULL,
                 pdata->num_row_gpios,
                 pdata->num_col_gpios,
                 NULL, input_dev);
if (err) {
    dev_err(&pdev->dev, "failed to build keymap\n");
    goto err_free_mem;
}

if (!pdata->no_autorepeat)
    __set_bit(EV_REP, input_dev->evbit);
input_set_capability(input_dev, EV_MSC, MSC_SCAN);

//保存 keypad 矩阵按键指针 到 input
input_set_drvdata(input_dev, keypad);

/* 初始化矩阵按键GPIO,假设矩阵按键由 n行,m列 个GPIO组成
 * 此函数先对 所有(m)列GPIO进行request申请,并且使用 gpio_derectout_output把所有(m)列GPIO
 * 端口设置成输出端,输出高电平,然后对所有行(n)GPIO进行request申请,并且使用gpio_derectout_input
 * 将GPIO设置成输入口,并且使用request_irq() 就所有(n)行GPIO设置为外部中断。
 */
err = matrix_keypad_init_gpio(pdev, keypad);
if (err)
    goto err_free_mem;

//注册 input输入设备
err = input_register_device(keypad->input_dev);
if (err)
    goto err_free_gpio;

device_init_wakeup(&pdev->dev, pdata->wakeup);

//将 keypad矩阵按键指针 保存到 platform_device->device->device_private.driver_data 作为平台设备私有成员
platform_set_drvdata(pdev, keypad);

return 0;

err_free_gpio:
matrix_keypad_free_gpio(keypad);
err_free_mem:
input_free_device(input_dev);
kfree(keypad);
return err;
}

static int matrix_keypad_remove(struct platform_device *pdev)
{

/* platform_get_drvdata()用于调用 设备的局部(私有)变量
 * 该局部变量是 platform_set_drvdata()函数 保存到 
 * platform_device->device->device_private.driver_data 变成设备私有数据
 * 
 *
 */
struct matrix_keypad *keypad = platform_get_drvdata(pdev);

device_init_wakeup(&pdev->dev, 0);

matrix_keypad_free_gpio(keypad);

mutex_destroy(&keypad->lock);
//注销input输入设备
input_unregister_device(keypad->input_dev);

//释放 platform_get_drvdata/platform_set_drvdata 函数所操作的指针所指内存
kfree(keypad);
//platform_set_drvdata()用于保存局部变量,最终将 data 赋值给 platform_device->device->device_private.driver_data
//将设备 保存的局部变量(私有数据)清零
platform_set_drvdata(pdev, NULL);

return 0;

}

#ifdef CONFIG_OF
static const struct of_device_id matrix_keypad_dt_match[] = {
{ .compatible = "gpio-matrix-keypad" },
{ }
};
MODULE_DEVICE_TABLE(of, matrix_keypad_dt_match);
#endif

static struct platform_driver matrix_keypad_driver = {
.probe      = matrix_keypad_probe,
.remove     = matrix_keypad_remove,
.driver     = {
    .name   = "matrix-keypad",
    .owner  = THIS_MODULE,
    .pm = &matrix_keypad_pm_ops,
    .of_match_table = of_match_ptr(matrix_keypad_dt_match),
},
};
module_platform_driver(matrix_keypad_driver);//注册 矩阵按键驱动 为平台设备

MODULE_AUTHOR("Marek Vasut ");
MODULE_DESCRIPTION("GPIO Driven Matrix Keypad Driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:matrix-keypad");

设备树:   高高字节用于存储行号,高低字节用于存储列号,低高和低低字节用于保存值

 matrix_keypad: matrix_keypad@0 {
               compatible = "gpio-matrix-keypad";
               debounce-delay-ms = <50>;
               col-scan-delay-us = <5000>;
               pinctrl-names = "tlmm_gpio_key_active","tlmm_gpio_key_suspend";
               pinctrl-0 = <&gpio_key_active>;
               pinctrl-1 = <&gpio_key_suspend>;

               row-gpios = <&msm_gpio 9 0
                        &msm_gpio 11 0
                        &msm_gpio 94 0
                        &msm_gpio 95 0
                        &msm_gpio 22 0>;

               col-gpios = <&msm_gpio 91 0
                        &msm_gpio 92 0
                        &msm_gpio 98 0
                        &msm_gpio 97 0>;

               linux,keymap = <0x00000004           /* (0,0) KEY_3 */
                        0x00010007                                 /* (1,0) KEY_6 */
                        0x0002000a                                 /* (2,0) KEY_9 */
                        0x0003020b                                 /* (3,0) KEY_NUMERIC_POUND */

                        0x01000003                                 /* (0,1) KEY_2 */
                        0x01010006                                 /* (1,1) KEY_5 */
                        0x01020009                                 /* (2,1) KEY_8 */
                        0x0103000b                                 /* (3,1) KEY_0 */

                        0x02000002                                 /* (0,2) KEY_1 */
                        0x02010005                                 /* (1,2) KEY_4 */
                        0x02020008                                 /* (2,2) KEY_7 */
                        0x0203020a                                 /* (3,2) KEY_NUMERIC_STAR */

                        0x0300009e                                 /* (0,3) KEY_BACK */
                        0x0301007f                                 /* (1,3) KEY_MENU */
                        0x0302001c                                 /* (2,3) KEY_OK */
                        0x0303006a                                 /* (3,3) KEY_RIGHT */

                        0x040000a9                                 /* (0,4) KEY_DIAL */
                        0x04010069                                 /* (1,4) KEY_LEFT */
                        0x04020067                                 /* (2,4) KEY_up */
                        0x0403006c>;                    /* (3,4) KEY_down */
     };

调试命令:
cat /proc/bus/input/devices 查看输入设备

//hexdump命令一般用来查看“二进制”文件的十六进制编码,但实际上它能查看任何文件,而不只限于二进制文件
busybox hexdump /dev/input/event0  ---按 按键查看按键扫描码
/system/usr/keylayout/qwerty.kl  查看按键映射
getevent -l /dev/input/event7   event7是触摸屏的input设备
        :格式是event type、event code、event value,至于这些所代表的含义可以参考input设备相关的东西。
getevent:查看有多少输入子系统
getevent -l /dev/input/event0  查看event0事件(msm8909 是矩阵按键事件)//最常用 

调试总结:一般先确认设备树中按键码值正确,再排除引脚复用即可;引脚复用先检查kernel 再检查bootloader
今天终于把手机矩阵按键彻底调通了,经历了近半个月,中间现象调试历程如下:
第一阶段:按键没反映 :解决方式:修改设备树中 按键码 
第二阶段:个别按键有问题,现象是 2 5 8 0 这一列按键无论按下哪一个 都是全部反应,比如按下 2 ,那么 2 5 8 0 全部都会上报
            :解决方式:在kernel中找到了 矩阵按键的引脚复用,注释之
第三阶段:2 5 8 0 这一列按键 偶尔会出现 第二阶段问题, 解决方式:通过打印按键引脚 发现这一列按键的 列中断引脚gpio11在
开机的时候有异常,其他引脚都是默认低电平,只有这个引脚是默认高,说明有一个地方把它复用并且拉高了,排除kernel 那就剩下bootloader
了,在bootloader中搜索关键字 “11” ,没错。你没有看错,就是搜索11,搜索出非常非常非常多的代码。。。,一个一个的看。
要说明的是:如果真的是 在kernel bootloader中都没有复用的话,接下来的解决方式就是 看内核log,把所有的error都解决了也许冲突就解决了
还有一种方式是 裁剪 XXX_defconfig文件。前提是你对配置文件比较熟悉。以上。 

你可能感兴趣的:(Linux驱动)