2 * Testing Communication with Sinclair Air Conditioner
4 * (c) 2023 Martin Mareš <mj@ucw.cz>
9 #include <libopencm3/cm3/cortex.h>
10 #include <libopencm3/cm3/nvic.h>
11 #include <libopencm3/cm3/systick.h>
12 #include <libopencm3/cm3/scb.h>
13 #include <libopencm3/stm32/rcc.h>
14 #include <libopencm3/stm32/desig.h>
15 #include <libopencm3/stm32/gpio.h>
16 #include <libopencm3/stm32/usart.h>
17 #include <libopencm3/stm32/spi.h>
18 #include <libopencm3/stm32/timer.h>
19 #include <libopencm3/usb/dfu.h>
20 #include <libopencm3/usb/usbd.h>
24 /*** Hardware init ***/
26 static void clock_init(void)
28 rcc_clock_setup_pll(&rcc_hse_configs[RCC_CLOCK_HSE8_72MHZ]);
30 rcc_periph_clock_enable(RCC_GPIOA);
31 rcc_periph_clock_enable(RCC_GPIOB);
32 rcc_periph_clock_enable(RCC_GPIOC);
33 rcc_periph_clock_enable(RCC_SPI2);
34 rcc_periph_clock_enable(RCC_USART1);
35 rcc_periph_clock_enable(RCC_USB);
36 rcc_periph_clock_enable(RCC_TIM3);
37 rcc_periph_clock_enable(RCC_TIM4);
39 rcc_periph_reset_pulse(RST_GPIOA);
40 rcc_periph_reset_pulse(RST_GPIOB);
41 rcc_periph_reset_pulse(RST_GPIOC);
42 rcc_periph_reset_pulse(RST_SPI2);
43 rcc_periph_reset_pulse(RST_USART1);
44 rcc_periph_reset_pulse(RST_USB);
45 rcc_periph_reset_pulse(RST_TIM3);
46 rcc_periph_reset_pulse(RST_TIM4);
49 static void gpio_init(void)
51 // PA9 = TXD1 for debugging console
52 // PA10 = RXD1 for debugging console
53 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO9);
54 gpio_set_mode(GPIOA, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO10);
56 // PC13 = BluePill LED
57 gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
58 gpio_clear(GPIOC, GPIO13);
62 gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO13);
63 gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO15);
65 // PA8 = IR remote control
66 gpio_clear(GPIOA, GPIO8);
67 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO8);
70 static void usart_init(void)
72 usart_set_baudrate(USART1, 115200);
73 usart_set_databits(USART1, 8);
74 usart_set_stopbits(USART1, USART_STOPBITS_1);
75 usart_set_mode(USART1, USART_MODE_TX_RX);
76 usart_set_parity(USART1, USART_PARITY_NONE);
77 usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
82 /*** System ticks ***/
84 static volatile u32 ms_ticks;
86 void sys_tick_handler(void)
91 static void tick_init(void)
93 systick_set_frequency(1000, CPU_CLOCK_MHZ * 1000000);
94 systick_counter_enable();
95 systick_interrupt_enable();
98 static void delay_ms(uint ms)
100 u32 start_ticks = ms_ticks;
101 while (ms_ticks - start_ticks < ms)
105 /*** Emulated TM1618 LED Driver ***/
108 * Theory of operation:
110 * TM1618 communicates using a bi-directional SPI-like protocol.
111 * The AC unit is sending a stream of commands like this once per ca. 4 ms:
113 * 00 - set mode: 4 grids, 8 segments
114 * 44 - will write to display memory, no auto-increment
115 * Cx - set memory address to x
116 * yy - data to write, two most-significant bits are always zero
117 * 8B - display ON, duty cycle 10/16
119 * No read commands are issued, so we can simulate TM1618 using a pure SPI slave.
121 * Commands are delimited using the STB* (strobe) pin, but since our opto-couplers
122 * are negating, we cannot route this pin to SS (slave select) of our SPI.
123 * We tried triggering an external interrupt by this pin, but it turned out
124 * that the latency is too high.
126 * Instead, we ignore STB* completely and implement a self-synchronizing receiver:
128 * - The only byte which can have top 2 bits both set is the Cx command,
129 * so we can use this to find memory addresses and data in the stream.
130 * We can ignore all other commands.
132 * - Whenever 1 ms passes since the last byte was received, we reset the SPI.
133 * This allows us to recover from misaligned bytes.
136 static void tm_init(void)
138 // Configure SPI2 to receive
139 spi_set_receive_only_mode(SPI2);
140 spi_enable_software_slave_management(SPI2);
141 spi_set_nss_low(SPI2);
142 spi_send_lsb_first(SPI2);
143 spi_set_clock_polarity_0(SPI2);
144 spi_set_clock_phase_1(SPI2);
145 spi_enable_rx_buffer_not_empty_interrupt(SPI2);
146 nvic_enable_irq(NVIC_SPI2_IRQ);
149 // TIM3 will handle receive timeout
150 timer_set_prescaler(TIM3, CPU_CLOCK_MHZ-1); // 1 tick = 1 μs
151 timer_set_mode(TIM3, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_DOWN);
152 timer_update_on_overflow(TIM3);
153 timer_disable_preload(TIM3);
154 timer_one_shot_mode(TIM3);
155 timer_enable_irq(TIM3, TIM_DIER_UIE);
156 nvic_enable_irq(NVIC_TIM3_IRQ);
160 * Data memory of TM1618:
162 * [0] . . . - - - - -
163 * [1] . . - - HEAT . . .
164 * [2] . . . DRY - SLP MED LOW
165 * [3] . . HIGH AUTO COOL . . .
166 * [4] . . . B2 - G2 D2 C2
167 * [5] . . E2 F2 A2 . . .
168 * [6] . . . B1 - G1 D1 C1
169 * [7] . . E1 F1 A1 . . .
171 * "." is an always-zero bit not defined by TM1618, "-" is defined, but not used by AC.
173 static volatile byte tm_data[8];
174 static volatile uint tm_overruns;
176 static volatile byte tm_buffer[256];
177 static volatile uint tm_len;
204 static const u16 tm_digits[10] = {
205 [0] = SEGa | SEGb | SEGc | SEGd | SEGe | SEGf,
207 [2] = SEGa | SEGb | SEGd | SEGe | SEGg,
208 [3] = SEGa | SEGb | SEGc | SEGd | SEGg,
209 [4] = SEGb | SEGc | SEGf | SEGg,
210 [5] = SEGa | SEGc | SEGd | SEGf | SEGg,
211 [6] = SEGa | SEGc | SEGd | SEGe | SEGf | SEGg,
212 [7] = SEGa | SEGb | SEGc,
213 [8] = SEGa | SEGb | SEGc | SEGd | SEGe | SEGf | SEGg,
214 [9] = SEGa | SEGb | SEGc | SEGd | SEGf | SEGg,
217 static volatile uint tm_timeouts;
221 if (SPI_SR(SPI2) & SPI_SR_OVR)
223 if (SPI_SR(SPI2) & SPI_SR_RXNE) {
224 byte x = SPI_DR(SPI2) ^ 0xff;
226 if (tm_len < ARRAY_SIZE(tm_buffer))
227 tm_buffer[tm_len++] = x;
229 static byte tm_address;
231 tm_data[tm_address & 7] = x;
233 } else if ((x & 0xc0) == 0xc0) {
236 timer_set_period(TIM3, 999);
237 timer_generate_event(TIM3, TIM_EGR_UG);
238 timer_enable_counter(TIM3);
244 if (TIM_SR(TIM3) & TIM_SR_UIF) {
245 TIM_SR(TIM3) &= ~TIM_SR_UIF;
247 spi_set_nss_high(SPI2);
248 spi_set_nss_low(SPI2);
252 static void tm_show(void)
255 for (uint i=0; i<8; i++)
256 debug_printf(" %02x", tm_data[i]);
257 debug_printf(" o=%d t=%d", tm_overruns, tm_timeouts);
260 if (tm_data[1] & 0x08)
261 debug_printf(" HEAT");
262 if (tm_data[2] & 0x10)
263 debug_printf(" DRY");
264 if (tm_data[2] & 0x04)
265 debug_printf(" SLEEP");
266 if (tm_data[2] & 0x02)
267 debug_printf(" MED");
268 if (tm_data[2] & 0x01)
269 debug_printf(" LOW");
270 if (tm_data[3] & 0x20)
271 debug_printf(" HIGH");
272 if (tm_data[3] & 0x10)
273 debug_printf(" AUTO");
274 if (tm_data[3] & 0x08)
275 debug_printf(" COOL");
278 for (int i=0; i<2; i++) {
279 uint x = (tm_data[7-2*i] << 8) | tm_data[6-2*i];
281 while (j < 10 && tm_digits[j] != x)
292 static byte tm_dumped;
293 if (!tm_dumped && tm_len == ARRAY_SIZE(tm_buffer)) {
294 for (uint i=0; i < tm_len; i++)
295 debug_printf("%02x ", tm_buffer[i]);
303 /*** Infra-red remote control simulator ***/
305 #define RC_POWER_OFF_HI 0b00000000000000000000
306 #define RC_POWER_OFF_LO 0b00000000000000010000000010100100
308 #define RC_DEFAULT_HI 0b00000011000000000000
310 // Various temperatures
311 #define RC_17_COOL_AUTO 0b00000000000000010000000000101001
312 #define RC_18_COOL_AUTO 0b00000000000000010000000000111000
313 #define RC_19_COOL_AUTO 0b00000000000000010000000001000111
314 #define RC_20_COOL_AUTO 0b00000000000000010000000001010110
315 #define RC_21_COOL_AUTO 0b00000000000000010000000001100101
316 #define RC_22_COOL_AUTO 0b00000000000000010000000001110100
317 #define RC_23_COOL_AUTO 0b00000000000000010000000010000011
318 #define RC_24_COOL_AUTO 0b00000000000000010000000010010010
319 #define RC_25_COOL_AUTO 0b00000000000000010000000010100001
320 #define RC_26_COOL_AUTO 0b00000000000000010000000010110000
321 #define RC_27_COOL_AUTO 0b00000000000000010000000011001111
322 #define RC_28_COOL_AUTO 0b00000000000000010000000011011110
323 #define RC_29_COOL_AUTO 0b00000000000000010000000011101101
324 #define RC_30_COOL_AUTO 0b00000000000000010000000011111100
326 // Various fan settings
327 #define RC_17_COOL_HI 0b00000000000000010000100000100001
328 #define RC_17_COOL_MED 0b00000000000000010001000100100111
329 #define RC_17_COOL_LO 0b00000000000000010010001000100101
331 // Stand-alone, no temperature nor fan setting
332 #define RC_DEHUMIDIFY 0b00000000000000010010010000100011
334 // Combines with a temperature setting, but no fan setting
335 #define RC_17_WARM 0b00000000000000010000001100100110
337 // All modes have a sleep variant, which we do not use yet
338 #define RC_17_COOL_AUTO_SLEEP 0b00000000000010010000000000100001
340 static const u32 rc_fan_settings[4] = {
342 RC_17_COOL_LO ^ RC_17_COOL_AUTO,
343 RC_17_COOL_MED ^ RC_17_COOL_AUTO,
344 RC_17_COOL_HI ^ RC_17_COOL_AUTO,
347 static const u32 rc_temp_settings[14] = {
348 #define X(t) RC_##t##_COOL_AUTO ^ RC_17_COOL_AUTO
373 static byte rc_mode = MODE_COOL; // MODE_xxx
374 static byte rc_fan; // 0-3
375 static byte rc_temp = 17; // 17-30
377 static void rc_init(void)
379 // TIM4 runs at 1 MHz and it is used for timing of RC pulses
380 timer_set_prescaler(TIM4, CPU_CLOCK_MHZ - 1);
381 timer_set_mode(TIM4, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP);
382 timer_update_on_overflow(TIM4);
383 timer_disable_preload(TIM4);
384 timer_one_shot_mode(TIM4);
385 timer_enable_irq(TIM4, TIM_DIER_UIE);
386 nvic_enable_irq(NVIC_TIM4_IRQ);
389 static u32 rc_pattern[2];
392 static void rc_encode(void)
394 if (rc_mode == MODE_OFF) {
395 rc_pattern[0] = RC_POWER_OFF_HI;
396 rc_pattern[1] = RC_POWER_OFF_LO;
400 rc_pattern[0] = RC_DEFAULT_HI;
401 uint t = rc_temp, f = rc_fan;
403 if (rc_mode == MODE_COOL) {
404 rc_pattern[1] = RC_17_COOL_AUTO;
405 } else if (rc_mode == MODE_WARM) {
406 rc_pattern[1] = RC_17_WARM;
409 rc_pattern[1] = RC_DEHUMIDIFY;
413 rc_pattern[1] ^= rc_fan_settings[f];
415 if (t >= 17 && t < 17 + ARRAY_SIZE(rc_temp_settings))
416 rc_pattern[1] ^= rc_temp_settings[t - 17];
421 if (TIM_SR(TIM4) & TIM_SR_UIF) {
422 TIM_SR(TIM4) &= ~TIM_SR_UIF;
424 bool val; // 1=pulse, 0=break
425 uint duration; // in μs
433 // Initial / final marker
454 // Even ticks 4 to 106 transmit 52 bits of data
455 uint i = 12 + (rc_tick - 4) / 2;
457 if (rc_pattern[i>>5] & (0x80000000 >> (i & 31))) {
470 gpio_set(GPIOA, GPIO8);
472 gpio_clear(GPIOA, GPIO8);
474 timer_set_period(TIM4, duration - 1);
475 timer_generate_event(TIM4, TIM_EGR_UG);
476 timer_enable_counter(TIM4);
480 static void rc_send(void)
486 debug_printf("RC sending: %05x %08x (mode=%d, fan=%d, temp=%d)\n",
487 (uint) rc_pattern[0], (uint) rc_pattern[1],
488 rc_mode, rc_fan, rc_temp);
491 timer_set_period(TIM4, 1);
492 timer_generate_event(TIM4, TIM_EGR_UG);
493 timer_enable_counter(TIM4);
496 static bool rc_key(char key)
502 } else if (key == 'c') {
506 } else if (key == 'w') {
510 } else if (key == 'd') {
511 rc_mode = MODE_DEHUMIDIFY;
514 } else if (key == 'a') {
518 } else if (key == 'l') {
522 } else if (key == 'm') {
526 } else if (key == 'h') {
530 } else if (key >= '7' && key <= '9') {
531 rc_temp = key - '0' + 10;
534 } else if (key >= '0' && key <= '6') {
535 rc_temp = key - '0' + 20;
538 } else if (key == '&') {
542 } else if (key == '*') {
546 } else if (key == '(') {
550 } else if (key == ')') {
560 static usbd_device *usbd_dev;
563 STR_MANUFACTURER = 1,
568 static char usb_serial_number[13];
570 static const char *usb_strings[] = {
571 "United Computer Wizards",
572 "Sinclair Air Conditioner",
576 static const struct usb_device_descriptor device = {
577 .bLength = USB_DT_DEVICE_SIZE,
578 .bDescriptorType = USB_DT_DEVICE,
580 .bDeviceClass = 0xFF,
581 .bDeviceSubClass = 0,
582 .bDeviceProtocol = 0,
583 .bMaxPacketSize0 = 64,
587 .iManufacturer = STR_MANUFACTURER,
588 .iProduct = STR_PRODUCT,
589 .iSerialNumber = STR_SERIAL,
590 .bNumConfigurations = 1,
593 static const struct usb_endpoint_descriptor endpoints[] = {{
594 // Bulk end-point for sending values to the display
595 .bLength = USB_DT_ENDPOINT_SIZE,
596 .bDescriptorType = USB_DT_ENDPOINT,
597 .bEndpointAddress = 0x01,
598 .bmAttributes = USB_ENDPOINT_ATTR_BULK,
599 .wMaxPacketSize = 64,
603 static const struct usb_interface_descriptor iface = {
604 .bLength = USB_DT_INTERFACE_SIZE,
605 .bDescriptorType = USB_DT_INTERFACE,
606 .bInterfaceNumber = 0,
607 .bAlternateSetting = 0,
609 .bInterfaceClass = 0xFF,
610 .bInterfaceSubClass = 0,
611 .bInterfaceProtocol = 0,
613 .endpoint = endpoints,
616 static const struct usb_dfu_descriptor dfu_function = {
617 .bLength = sizeof(struct usb_dfu_descriptor),
618 .bDescriptorType = DFU_FUNCTIONAL,
619 .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
620 .wDetachTimeout = 255,
621 .wTransferSize = 1024,
622 .bcdDFUVersion = 0x0100,
625 static const struct usb_interface_descriptor dfu_iface = {
626 .bLength = USB_DT_INTERFACE_SIZE,
627 .bDescriptorType = USB_DT_INTERFACE,
628 .bInterfaceNumber = 1,
629 .bAlternateSetting = 0,
631 .bInterfaceClass = 0xFE,
632 .bInterfaceSubClass = 1,
633 .bInterfaceProtocol = 1,
636 .extra = &dfu_function,
637 .extralen = sizeof(dfu_function),
640 static const struct usb_interface ifaces[] = {{
642 .altsetting = &iface,
645 .altsetting = &dfu_iface,
648 static const struct usb_config_descriptor config = {
649 .bLength = USB_DT_CONFIGURATION_SIZE,
650 .bDescriptorType = USB_DT_CONFIGURATION,
653 .bConfigurationValue = 1,
655 .bmAttributes = 0x80,
656 .bMaxPower = 50, // multiplied by 2 mA
660 static byte usb_configured;
661 static uint8_t usbd_control_buffer[64];
663 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
665 // Reset to bootloader, which implements the rest of DFU
666 debug_printf("Switching to DFU\n");
671 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
672 struct usb_setup_data *req,
673 uint8_t **buf UNUSED,
674 uint16_t *len UNUSED,
675 void (**complete)(usbd_device *dev, struct usb_setup_data *req))
677 if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
678 return USBD_REQ_NOTSUPP;
680 *complete = dfu_detach_complete;
681 return USBD_REQ_HANDLED;
684 static void ep01_cb(usbd_device *dev, uint8_t ep UNUSED)
686 // We received a frame from the USB host
688 uint len = usbd_ep_read_packet(dev, 0x01, buf, 8);
689 debug_printf("USB: Host sent %u bytes\n", len);
692 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
694 usbd_register_control_callback(
696 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
697 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
699 usbd_ep_setup(dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, ep01_cb);
703 static void reset_cb(void)
705 debug_printf("USB: Reset\n");
709 static volatile bool usb_event_pending;
711 void usb_lp_can_rx0_isr(void)
714 * We handle USB in the main loop to avoid race conditions between
715 * USB interrupts and other code. However, we need an interrupt to
716 * up the main loop from sleep.
718 * We set up only the low-priority ISR, because high-priority ISR handles
719 * only double-buffered bulk transfers and isochronous transfers.
721 nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
722 usb_event_pending = 1;
725 static void usb_init(void)
727 // Simulate USB disconnect
728 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
729 gpio_clear(GPIOA, GPIO11 | GPIO12);
732 usbd_dev = usbd_init(
733 &st_usbfs_v1_usb_driver,
737 ARRAY_SIZE(usb_strings),
739 sizeof(usbd_control_buffer)
741 usbd_register_reset_callback(usbd_dev, reset_cb);
742 usbd_register_set_config_callback(usbd_dev, set_config_cb);
743 usb_event_pending = 1;
755 desig_get_unique_id_as_dfu(usb_serial_number);
757 debug_printf("Hello, world!\n");
766 if (ms_ticks - last_blink >= 1000) {
768 last_blink = ms_ticks;
772 if (usart_get_flag(USART1, USART_SR_RXNE)) {
773 uint ch = usart_recv(USART1);
776 gpio_set(GPIOA, GPIO8);
778 gpio_clear(GPIOA, GPIO8);
787 if (usb_event_pending) {
789 usb_event_pending = 0;
790 nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
791 nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
794 wait_for_interrupt();