aboutsummaryrefslogtreecommitdiffstats
path: root/keyboards/hotdox/left.c
blob: 970d36f1b561e554f09cfdbf33f2cdbeb906c4ba (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include "action.h"
#include "left.h"
#include "wait.h"

bool i2c_initialized = false;

void left_config(void);
uint8_t left_write(uint8_t reg, uint8_t data);
uint8_t left_read(uint8_t reg, uint8_t *data);

uint8_t init_mcp23017(void)
{
    i2c_initialized = false;

    if (i2c_initialized == 0)
    {
        i2c_init();  // on pins D(1,0)
        _delay_ms(1000);
    }

    return 0;
}
void left_init(void)
{
    init_mcp23017();
    left_scan();
#if 0
    while (1)
    {
        print("wait\n");
        wait_us(1000000);
    }
#endif
}

void left_scan(void)
{
    uint8_t ret = i2c_start(I2C_ADDR_WRITE, HOTDOX_I2C_TIMEOUT);

    if (ret == 0)
    {
        i2c_stop();

        if (!i2c_initialized)
        {
            i2c_initialized = true;
            left_config();
            clear_keyboard();
            print("mcp23017 attached!!!\n");
        }
    }
    else
    {
        if (i2c_initialized)
        {
            i2c_initialized = false;
            clear_keyboard();
            print("mcp23017 deattached!!!\n");
        }
    }

    return;
}

uint8_t left_read_cols(void)
{
    uint8_t data = 0;

    left_read(MCP23017_B0_GPIOA, &data);

    return data;
}

void left_unselect_rows(void)
{
    left_write(MCP23017_B0_IODIRB, 0x3F);
}

void left_select_row(uint8_t row)
{
    left_write(MCP23017_B0_IODIRB, ~(1 << row));
}

void left_config(void)
{
  left_write(MCP23017_B0_IODIRA, 0x7F);
  left_write(MCP23017_B0_IPOLA,  0x7F);
  left_write(MCP23017_B0_GPPUA,  0x7F);

  left_write(MCP23017_B0_IODIRB, 0xFF);
  left_write(MCP23017_B0_GPIOB,  0xC0);
}

uint8_t left_write(uint8_t reg, uint8_t data)
{
  if (!i2c_initialized)
  {
    return 0;
  }

  uint8_t ret;

  ret = i2c_start(I2C_ADDR_WRITE, HOTDOX_I2C_TIMEOUT);     if (ret) goto out;
  ret = i2c_write(reg, HOTDOX_I2C_TIMEOUT);                if (ret) goto out;
  ret = i2c_write(data, HOTDOX_I2C_TIMEOUT);

out:
  i2c_stop();
  return ret;
}

uint8_t left_read(uint8_t reg, uint8_t *data)
{
  if (!i2c_initialized)
  {
    return 0;
  }

  uint8_t ret = 0;

  ret = i2c_start(I2C_ADDR_WRITE, HOTDOX_I2C_TIMEOUT);     if (ret) goto out;
  ret = i2c_write(reg, HOTDOX_I2C_TIMEOUT);                if (ret) goto out;
  ret = i2c_start(I2C_ADDR_READ, HOTDOX_I2C_TIMEOUT);      if (ret) goto out;

  *data = i2c_read_nack(HOTDOX_I2C_TIMEOUT);

out:
  i2c_stop();
  return ret;
}