From 88122612dc3752ccbad1ad6be767616671756048 Mon Sep 17 00:00:00 2001
From: schneider <schneider@blinkenlichts.net>
Date: Sat, 22 Jun 2019 01:02:37 +0200
Subject: [PATCH] feat(lib/card10): Initial port expander support

---
 lib/card10/card10.c       |  3 +++
 lib/card10/meson.build    |  1 +
 lib/card10/portexpander.c | 40 +++++++++++++++++++++++++++++++++++++++
 lib/card10/portexpander.h |  9 +++++++++
 4 files changed, 53 insertions(+)
 create mode 100644 lib/card10/portexpander.c
 create mode 100644 lib/card10/portexpander.h

diff --git a/lib/card10/card10.c b/lib/card10/card10.c
index df141a29..cf377e39 100644
--- a/lib/card10/card10.c
+++ b/lib/card10/card10.c
@@ -1,6 +1,7 @@
 #include "pmic.h"
 #include "bosch.h"
 #include "display.h"
+#include "portexpander.h"
 
 #include "bhy_uc_driver.h"
 #include "Bosch_PCB_7183_di03_BMI160_BMM150-7183_di03.2.1.11696_170103.h"
@@ -92,6 +93,8 @@ void card10_init(void)
         float sic_array[9] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0};
         bhy_set_sic_matrix(sic_array);
     }
+
+    portexpander_init();
 }
 
 static uint32_t ecg_read_reg(uint8_t reg)
diff --git a/lib/card10/meson.build b/lib/card10/meson.build
index 8e6ce61f..9797d7bf 100644
--- a/lib/card10/meson.build
+++ b/lib/card10/meson.build
@@ -7,6 +7,7 @@ sources = files(
   'card10.c',
   'leds.c',
   'pmic.c',
+  'portexpander.c',
 )
 
 deps = [
diff --git a/lib/card10/portexpander.c b/lib/card10/portexpander.c
new file mode 100644
index 00000000..60dbfc61
--- /dev/null
+++ b/lib/card10/portexpander.c
@@ -0,0 +1,40 @@
+#include "portexpander.h"
+
+#include "i2c.h"
+
+#include <stdio.h>
+#include <stdint.h>
+#include <string.h>
+
+void portexpander_init(void)
+{
+    uint8_t addr = 0x21;
+
+    // Enable pull-ups for buttons
+    uint8_t command[] = {0x43, 0x68};
+    I2C_MasterWrite(MXC_I2C1_BUS0, addr << 1, command, 2, 0);
+
+    // Set _all_ outputs to open-drain to support the high side p-channel transistors.
+    command[0] = 0x4F; command[1] = 0x01;
+    I2C_MasterWrite(MXC_I2C1_BUS0, addr << 1, command, 2, 0);
+
+    // Enable outputs for transistors and the LED
+    command[0] = 0x03; command[1] = 0x68;
+    I2C_MasterWrite(MXC_I2C1_BUS0, addr << 1, command, 2, 0);
+
+    // Set outputs to high (i.e. open-drain)
+    command[0] = 0x01; command[1] = 0x97;
+    I2C_MasterWrite(MXC_I2C1_BUS0, addr << 1, command, 2, 0);
+}
+
+uint8_t portexpander_get(void)
+{
+    uint8_t addr = 0x21;
+    uint8_t command[] = {0x00};
+    I2C_MasterWrite(MXC_I2C1_BUS0, addr << 1, command, 1, 1);
+    uint8_t buf;
+    I2C_MasterRead(MXC_I2C1_BUS0, addr << 1, &buf, 1, 0);
+    return buf;
+}
+
+
diff --git a/lib/card10/portexpander.h b/lib/card10/portexpander.h
new file mode 100644
index 00000000..a2532cc3
--- /dev/null
+++ b/lib/card10/portexpander.h
@@ -0,0 +1,9 @@
+#ifndef PORTEXPANDER_H
+#define PORTEXPANDER_H
+
+#include <stdint.h>
+
+void portexpander_init(void);
+uint8_t portexpander_get(void);
+
+#endif
-- 
GitLab