From 5c49f7c2e46d6fced0763094ec05bba41298cbed Mon Sep 17 00:00:00 2001 From: Julian Blake Kongslie Date: Thu, 25 Jul 2024 13:28:55 -0700 Subject: Initial working version. --- rivulet.cpp | 118 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 rivulet.cpp (limited to 'rivulet.cpp') diff --git a/rivulet.cpp b/rivulet.cpp new file mode 100644 index 0000000..5b18bb0 --- /dev/null +++ b/rivulet.cpp @@ -0,0 +1,118 @@ +#include +#include +#include +#include + +constexpr const unsigned int PERIOD_MS = 3000; + +enum { + PIN_CLOCK, + + PIN_DATA, + + PIN_CS0, + PIN_CS1, + PIN_CS2, + PIN_CS3, + PIN_CS4, + PIN_CS5, + PIN_CS6, + PIN_CS7, + + PIN_LED = 25, +}; + +constexpr unsigned int MASK(unsigned int pin) { return 1 << pin; } + +enum { + MASK_CLOCK = MASK(PIN_CLOCK), + + MASK_DATA = MASK(PIN_DATA), + + MASK_CS0 = MASK(PIN_CS0), + MASK_CS1 = MASK(PIN_CS1), + MASK_CS2 = MASK(PIN_CS2), + MASK_CS3 = MASK(PIN_CS3), + MASK_CS4 = MASK(PIN_CS4), + MASK_CS5 = MASK(PIN_CS5), + MASK_CS6 = MASK(PIN_CS6), + MASK_CS7 = MASK(PIN_CS7), + + MASK_LED = MASK(PIN_LED), + + MASK_CSALL = MASK_CS0 | MASK_CS1 | MASK_CS2 | MASK_CS3 | MASK_CS4 | MASK_CS5 | MASK_CS6 | MASK_CS7, + MASK_IN = MASK_DATA, + MASK_OUT = MASK_CLOCK | MASK_CSALL | MASK_LED, + MASK_ALL = MASK_IN | MASK_OUT, +}; + +unsigned int read_bit() { + gpio_set_mask(MASK_CLOCK); + sleep_us(1); + gpio_clr_mask(MASK_CLOCK); + auto bit = gpio_get(PIN_DATA); + sleep_us(1); + return bit; +} + +unsigned int read_sensor(unsigned int i) { + unsigned int cs; + switch (i) { + case 0: cs = PIN_CS0; break; + case 1: cs = PIN_CS1; break; + case 2: cs = PIN_CS2; break; + case 3: cs = PIN_CS3; break; + case 4: cs = PIN_CS4; break; + case 5: cs = PIN_CS5; break; + case 6: cs = PIN_CS6; break; + case 7: cs = PIN_CS7; break; + default: return 0; + } + + gpio_clr_mask(MASK(cs)); + sleep_us(1); + + // 3 leading zero bits + for (unsigned int i = 0; i < 3; ++i) + read_bit(); + + // 12 data bits; big endian + unsigned int result = 0; + for (unsigned int i = 0; i < 12; ++i) + result = (result << 1) | read_bit(); + + gpio_set_mask(MASK(cs)); + sleep_us(1); + + return result; +} + +int main() { + stdio_usb_init(); + gpio_init_mask(MASK_ALL); + gpio_set_dir_in_masked(MASK_IN); + gpio_set_dir_out_masked(MASK_OUT); + gpio_set_mask(MASK_CSALL); + gpio_clr_mask(MASK_CLOCK | MASK_LED); + + while (true) { + if (!stdio_usb_connected()) { + sleep_ms(1000); + continue; + } + + gpio_set_mask(MASK_LED); + + while (stdio_usb_connected()) { + printf("["); + for (unsigned int i = 0; i < 8; ++i) + printf(" %u", read_sensor(i)); + printf(" ]\n"); + sleep_ms(PERIOD_MS); + } + + gpio_clr_mask(MASK_LED); + } + + return 0; +} -- cgit v1.2.3