1 /* Copyright 2018 Mike Roberts
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 #include "lib/lufa/LUFA/Drivers/Peripheral/TWI.h"
19 #include "lib/lufa/LUFA/Drivers/Peripheral/AVR8/TWI_AVR8.c"
24 uint8_t bit_for_pin(uint8_t pin);
26 uint8_t expander_write(uint8_t reg, uint8_t data);
28 uint8_t expander_read(uint8_t reg, uint8_t *data);
30 void expander_config(void);
32 static const char *twi_err_str(uint8_t res) {
34 case TWI_ERROR_NoError:
36 case TWI_ERROR_BusFault:
38 case TWI_ERROR_BusCaptureTimeout:
40 case TWI_ERROR_SlaveResponseTimeout:
41 return "SLAVETIMEOUT";
42 case TWI_ERROR_SlaveNotReady:
43 return "SLAVENOTREADY";
44 case TWI_ERROR_SlaveNAK:
51 void expander_init(void) {
52 TWI_Init(TWI_BIT_PRESCALE_1, TWI_BITLENGTH_FROM_FREQ(1, 400000));
56 void expander_unselect_all() {
57 expander_write(EXPANDER_REG_IODIRA, 0xff);
58 expander_write(EXPANDER_REG_IODIRB, 0xff);
59 expander_write(EXPANDER_REG_OLATA, 0xff);
60 expander_write(EXPANDER_REG_OLATB, 0xff);
61 wait_us(EXPANDER_PAUSE);
65 void expander_select(uint8_t pin) {
66 const uint8_t mask = 0xff & ~(1 << bit_for_pin(pin));
68 expander_write(EXPANDER_REG_IODIRA, mask);
69 expander_write(EXPANDER_REG_OLATA, mask);
71 expander_write(EXPANDER_REG_IODIRB, mask);
72 expander_write(EXPANDER_REG_OLATB, mask);
74 wait_us(EXPANDER_PAUSE);
77 void expander_config() {
78 // set everything to input
79 expander_write(EXPANDER_REG_IODIRA, 0xff);
80 expander_write(EXPANDER_REG_IODIRB, 0xff);
83 expander_write(EXPANDER_REG_GPPUA, 0xff);
84 expander_write(EXPANDER_REG_GPPUB, 0xff);
87 expander_write(EXPANDER_REG_GPINTENA, 0x0);
88 expander_write(EXPANDER_REG_GPINTENB, 0x0);
91 expander_write(EXPANDER_REG_IPOLA, 0x0);
92 expander_write(EXPANDER_REG_IPOLB, 0x0);
95 uint8_t bit_for_pin(uint8_t pin) {
99 uint8_t expander_write(uint8_t reg, unsigned char val) {
101 uint8_t result = TWI_WritePacket(EXPANDER_ADDR << 1, I2C_TIMEOUT, &addr, sizeof(addr), &val, sizeof(val));
103 xprintf("mcp: set_register %d = %d failed: %s\n", reg, val, twi_err_str(result));