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);
60 // PB13 = SCK2 (pulled up)
61 // PB15 = MOSI2 (pulled up)
62 gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_PULL_UPDOWN, GPIO13);
63 gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_PULL_UPDOWN, GPIO15);
64 gpio_set(GPIOB, GPIO13 | GPIO15);
66 // PA8 = IR remote control
67 gpio_clear(GPIOA, GPIO8);
68 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO8);
71 static void usart_init(void)
73 usart_set_baudrate(USART1, 115200);
74 usart_set_databits(USART1, 8);
75 usart_set_stopbits(USART1, USART_STOPBITS_1);
76 usart_set_mode(USART1, USART_MODE_TX_RX);
77 usart_set_parity(USART1, USART_PARITY_NONE);
78 usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
83 /*** System ticks ***/
85 static volatile u32 ms_ticks;
87 void sys_tick_handler(void)
92 static void tick_init(void)
94 systick_set_frequency(1000, CPU_CLOCK_MHZ * 1000000);
95 systick_counter_enable();
96 systick_interrupt_enable();
99 static void delay_ms(uint ms)
101 u32 start_ticks = ms_ticks;
102 while (ms_ticks - start_ticks < ms)
106 /*** Emulated TM1618 LED Driver ***/
109 * Theory of operation:
111 * TM1618 communicates using a bi-directional SPI-like protocol.
112 * The AC unit is sending a stream of commands like this once per ca. 4 ms:
114 * 00 - set mode: 4 grids, 8 segments
115 * 44 - will write to display memory, no auto-increment
116 * Cx - set memory address to x
117 * yy - data to write, two most-significant bits are always zero
118 * 8B - display ON, duty cycle 10/16
120 * No read commands are issued, so we can simulate TM1618 using a pure SPI slave.
122 * Commands are delimited using the STB* (strobe) pin, but since our opto-couplers
123 * are negating, we cannot route this pin to SS (slave select) of our SPI.
124 * We tried triggering an external interrupt by this pin, but it turned out
125 * that the latency is too high.
127 * Instead, we ignore STB* completely and implement a self-synchronizing receiver:
129 * - The only byte which can have top 2 bits both set is the Cx command,
130 * so we can use this to find memory addresses and data in the stream.
131 * We can ignore all other commands.
133 * - Whenever 1 ms passes since the last byte was received, we reset the SPI.
134 * This allows us to recover from misaligned bytes.
137 static void tm_init(void)
139 // Configure SPI2 to receive
140 spi_set_receive_only_mode(SPI2);
141 spi_enable_software_slave_management(SPI2);
142 spi_set_nss_low(SPI2);
143 spi_send_lsb_first(SPI2);
144 spi_set_clock_polarity_0(SPI2);
145 spi_set_clock_phase_1(SPI2);
146 spi_enable_rx_buffer_not_empty_interrupt(SPI2);
147 nvic_enable_irq(NVIC_SPI2_IRQ);
150 // TIM3 will handle receive timeout
151 timer_set_prescaler(TIM3, CPU_CLOCK_MHZ-1); // 1 tick = 1 μs
152 timer_set_mode(TIM3, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_DOWN);
153 timer_update_on_overflow(TIM3);
154 timer_disable_preload(TIM3);
155 timer_one_shot_mode(TIM3);
156 timer_enable_irq(TIM3, TIM_DIER_UIE);
157 nvic_enable_irq(NVIC_TIM3_IRQ);
161 * Data memory of TM1618:
163 * [0] . . . - - - - -
164 * [1] . . - - HEAT . . .
165 * [2] . . . DRY - SLP MED LOW
166 * [3] . . HIGH AUTO COOL . . .
167 * [4] . . . B2 - G2 D2 C2
168 * [5] . . E2 F2 A2 . . .
169 * [6] . . . B1 - G1 D1 C1
170 * [7] . . E1 F1 A1 . . .
172 * "." is an always-zero bit not defined by TM1618, "-" is defined, but not used by AC.
174 static volatile byte tm_data[8];
175 static volatile uint tm_overruns;
177 static volatile byte tm_buffer[256];
178 static volatile uint tm_len;
205 static const u16 tm_digits[10] = {
206 [0] = SEGa | SEGb | SEGc | SEGd | SEGe | SEGf,
208 [2] = SEGa | SEGb | SEGd | SEGe | SEGg,
209 [3] = SEGa | SEGb | SEGc | SEGd | SEGg,
210 [4] = SEGb | SEGc | SEGf | SEGg,
211 [5] = SEGa | SEGc | SEGd | SEGf | SEGg,
212 [6] = SEGa | SEGc | SEGd | SEGe | SEGf | SEGg,
213 [7] = SEGa | SEGb | SEGc,
214 [8] = SEGa | SEGb | SEGc | SEGd | SEGe | SEGf | SEGg,
215 [9] = SEGa | SEGb | SEGc | SEGd | SEGf | SEGg,
218 static volatile uint tm_timeouts;
222 if (SPI_SR(SPI2) & SPI_SR_OVR)
224 if (SPI_SR(SPI2) & SPI_SR_RXNE) {
225 byte x = SPI_DR(SPI2) ^ 0xff;
227 if (tm_len < ARRAY_SIZE(tm_buffer))
228 tm_buffer[tm_len++] = x;
230 static byte tm_address;
232 tm_data[tm_address & 7] = x;
234 } else if ((x & 0xc0) == 0xc0) {
237 timer_set_period(TIM3, 999);
238 timer_generate_event(TIM3, TIM_EGR_UG);
239 timer_enable_counter(TIM3);
245 if (TIM_SR(TIM3) & TIM_SR_UIF) {
246 TIM_SR(TIM3) &= ~TIM_SR_UIF;
248 spi_set_nss_high(SPI2);
249 spi_set_nss_low(SPI2);
253 static void tm_show(void)
256 for (uint i=0; i<8; i++)
257 debug_printf(" %02x", tm_data[i]);
258 debug_printf(" o=%d t=%d", tm_overruns, tm_timeouts);
261 if (tm_data[1] & 0x08)
262 debug_printf(" HEAT");
263 if (tm_data[2] & 0x10)
264 debug_printf(" DRY");
265 if (tm_data[2] & 0x04)
266 debug_printf(" SLEEP");
267 if (tm_data[2] & 0x02)
268 debug_printf(" MED");
269 if (tm_data[2] & 0x01)
270 debug_printf(" LOW");
271 if (tm_data[3] & 0x20)
272 debug_printf(" HIGH");
273 if (tm_data[3] & 0x10)
274 debug_printf(" AUTO");
275 if (tm_data[3] & 0x08)
276 debug_printf(" COOL");
279 for (int i=0; i<2; i++) {
280 uint x = (tm_data[7-2*i] << 8) | tm_data[6-2*i];
282 while (j < 10 && tm_digits[j] != x)
293 static byte tm_dumped;
294 if (!tm_dumped && tm_len == ARRAY_SIZE(tm_buffer)) {
295 for (uint i=0; i < tm_len; i++)
296 debug_printf("%02x ", tm_buffer[i]);
304 /*** Infra-red remote control simulator ***/
307 * The AC unit expects demodulated IR signal. The RC sends 52-bit messages
308 * (plus leader and trailer). The last 4 bits are a complement of checksum
311 * We represent the messages as two 32-bit words, the upper word containing
314 #define RC_POWER_OFF_HI 0b00000000000000000000
315 #define RC_POWER_OFF_LO 0b00000000000000010000000010100100
317 #define RC_DEFAULT_HI 0b00000011000000000000
319 // Cooling with different fan settings. Combines with a temperature setting (17-30).
320 #define RC_COOL_AUTO 0b00000000000000010000000000000000
321 #define RC_COOL_HIGH 0b00000000000000010000100000000000
322 #define RC_COOL_MED 0b00000000000000010001000100000000
323 #define RC_COOL_LOW 0b00000000000000010010001000000000
325 static const u32 rc_cool_fan[4] = {
332 // Heating with fixed fan setting. Combines with a temperature setting (15-25).
333 #define RC_WARM 0b00000000000000010000001100000000
335 // Dehumidifying with fixed fan setting. This is always sent with temperature=17.
336 #define RC_DEHUMIDIFY 0b00000000000000010010010000000000
338 // This can be added to any command to enable sleep mode, but we do not issue it yet.
339 #define RC_SLEEP 0b00000000000010000000000000000000
348 static byte rc_mode = MODE_COOL; // MODE_xxx
349 static byte rc_fan; // 0-3
350 static byte rc_temp = 17; // 15-30
352 static void rc_init(void)
354 // TIM4 runs at 1 MHz and it is used for timing of RC pulses
355 timer_set_prescaler(TIM4, CPU_CLOCK_MHZ - 1);
356 timer_set_mode(TIM4, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP);
357 timer_update_on_overflow(TIM4);
358 timer_disable_preload(TIM4);
359 timer_one_shot_mode(TIM4);
360 timer_enable_irq(TIM4, TIM_DIER_UIE);
361 nvic_enable_irq(NVIC_TIM4_IRQ);
364 static u32 rc_pattern[2];
367 static void rc_encode(void)
369 if (rc_mode == MODE_OFF) {
370 rc_pattern[0] = RC_POWER_OFF_HI;
371 rc_pattern[1] = RC_POWER_OFF_LO;
375 rc_pattern[0] = RC_DEFAULT_HI;
378 if (rc_mode == MODE_COOL) {
379 rc_pattern[1] = rc_cool_fan[rc_fan];
384 } else if (rc_mode == MODE_WARM) {
385 rc_pattern[1] = RC_WARM;
391 rc_pattern[1] = RC_DEHUMIDIFY;
395 // Encode temperature
396 rc_pattern[1] |= (t - 15) << 4;
400 for (uint i=0; i<2; i++)
401 for (uint j=0; j<32; j+=4)
402 sum += (rc_pattern[i] >> j) & 0x0f;
403 rc_pattern[1] |= (sum & 0x0f) ^ 0x0f;
408 if (TIM_SR(TIM4) & TIM_SR_UIF) {
409 TIM_SR(TIM4) &= ~TIM_SR_UIF;
411 bool val; // 1=pulse, 0=break
412 uint duration; // in μs
420 // Initial / final marker
441 // Even ticks 4 to 106 transmit 52 bits of data
442 uint i = 12 + (rc_tick - 4) / 2;
444 if (rc_pattern[i>>5] & (0x80000000 >> (i & 31))) {
457 gpio_set(GPIOA, GPIO8);
459 gpio_clear(GPIOA, GPIO8);
461 timer_set_period(TIM4, duration - 1);
462 timer_generate_event(TIM4, TIM_EGR_UG);
463 timer_enable_counter(TIM4);
467 static void rc_send(void)
473 debug_printf("RC sending: %05x %08x (mode=%d, fan=%d, temp=%d)\n",
474 (uint) rc_pattern[0], (uint) rc_pattern[1],
475 rc_mode, rc_fan, rc_temp);
478 timer_set_period(TIM4, 1);
479 timer_generate_event(TIM4, TIM_EGR_UG);
480 timer_enable_counter(TIM4);
483 static bool rc_key(char key)
489 } else if (key == 'c') {
493 } else if (key == 'w') {
497 } else if (key == 'd') {
498 rc_mode = MODE_DEHUMIDIFY;
501 } else if (key == 'a') {
505 } else if (key == 'l') {
509 } else if (key == 'm') {
513 } else if (key == 'h') {
517 } else if (key >= '7' && key <= '9') {
518 rc_temp = key - '0' + 10;
521 } else if (key >= '0' && key <= '6') {
522 rc_temp = key - '0' + 20;
525 } else if (key == '&') {
529 } else if (key == '*') {
533 } else if (key == '(') {
537 } else if (key == ')') {
547 static usbd_device *usbd_dev;
550 STR_MANUFACTURER = 1,
555 static char usb_serial_number[13];
557 static const char *usb_strings[] = {
558 "United Computer Wizards",
559 "Sinclair Air Conditioner",
563 static const struct usb_device_descriptor device = {
564 .bLength = USB_DT_DEVICE_SIZE,
565 .bDescriptorType = USB_DT_DEVICE,
567 .bDeviceClass = 0xFF,
568 .bDeviceSubClass = 0,
569 .bDeviceProtocol = 0,
570 .bMaxPacketSize0 = 64,
574 .iManufacturer = STR_MANUFACTURER,
575 .iProduct = STR_PRODUCT,
576 .iSerialNumber = STR_SERIAL,
577 .bNumConfigurations = 1,
580 static const struct usb_endpoint_descriptor endpoints[] = {{
581 // Bulk end-point for sending values to the display
582 .bLength = USB_DT_ENDPOINT_SIZE,
583 .bDescriptorType = USB_DT_ENDPOINT,
584 .bEndpointAddress = 0x01,
585 .bmAttributes = USB_ENDPOINT_ATTR_BULK,
586 .wMaxPacketSize = 64,
590 static const struct usb_interface_descriptor iface = {
591 .bLength = USB_DT_INTERFACE_SIZE,
592 .bDescriptorType = USB_DT_INTERFACE,
593 .bInterfaceNumber = 0,
594 .bAlternateSetting = 0,
596 .bInterfaceClass = 0xFF,
597 .bInterfaceSubClass = 0,
598 .bInterfaceProtocol = 0,
600 .endpoint = endpoints,
603 static const struct usb_dfu_descriptor dfu_function = {
604 .bLength = sizeof(struct usb_dfu_descriptor),
605 .bDescriptorType = DFU_FUNCTIONAL,
606 .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
607 .wDetachTimeout = 255,
608 .wTransferSize = 1024,
609 .bcdDFUVersion = 0x0100,
612 static const struct usb_interface_descriptor dfu_iface = {
613 .bLength = USB_DT_INTERFACE_SIZE,
614 .bDescriptorType = USB_DT_INTERFACE,
615 .bInterfaceNumber = 1,
616 .bAlternateSetting = 0,
618 .bInterfaceClass = 0xFE,
619 .bInterfaceSubClass = 1,
620 .bInterfaceProtocol = 1,
623 .extra = &dfu_function,
624 .extralen = sizeof(dfu_function),
627 static const struct usb_interface ifaces[] = {{
629 .altsetting = &iface,
632 .altsetting = &dfu_iface,
635 static const struct usb_config_descriptor config = {
636 .bLength = USB_DT_CONFIGURATION_SIZE,
637 .bDescriptorType = USB_DT_CONFIGURATION,
640 .bConfigurationValue = 1,
642 .bmAttributes = 0x80,
643 .bMaxPower = 50, // multiplied by 2 mA
647 static byte usb_configured;
648 static uint8_t usbd_control_buffer[64];
650 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
652 // Reset to bootloader, which implements the rest of DFU
653 debug_printf("Switching to DFU\n");
658 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
659 struct usb_setup_data *req,
660 uint8_t **buf UNUSED,
661 uint16_t *len UNUSED,
662 void (**complete)(usbd_device *dev, struct usb_setup_data *req))
664 if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
665 return USBD_REQ_NOTSUPP;
667 *complete = dfu_detach_complete;
668 return USBD_REQ_HANDLED;
671 static void ep01_cb(usbd_device *dev, uint8_t ep UNUSED)
673 // We received a frame from the USB host
675 uint len = usbd_ep_read_packet(dev, 0x01, buf, 8);
676 debug_printf("USB: Host sent %u bytes\n", len);
679 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
681 usbd_register_control_callback(
683 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
684 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
686 usbd_ep_setup(dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, ep01_cb);
690 static void reset_cb(void)
692 debug_printf("USB: Reset\n");
696 static volatile bool usb_event_pending;
698 void usb_lp_can_rx0_isr(void)
701 * We handle USB in the main loop to avoid race conditions between
702 * USB interrupts and other code. However, we need an interrupt to
703 * up the main loop from sleep.
705 * We set up only the low-priority ISR, because high-priority ISR handles
706 * only double-buffered bulk transfers and isochronous transfers.
708 nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
709 usb_event_pending = 1;
712 static void usb_init(void)
714 // Simulate USB disconnect
715 gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
716 gpio_clear(GPIOA, GPIO11 | GPIO12);
719 usbd_dev = usbd_init(
720 &st_usbfs_v1_usb_driver,
724 ARRAY_SIZE(usb_strings),
726 sizeof(usbd_control_buffer)
728 usbd_register_reset_callback(usbd_dev, reset_cb);
729 usbd_register_set_config_callback(usbd_dev, set_config_cb);
730 usb_event_pending = 1;
742 desig_get_unique_id_as_dfu(usb_serial_number);
744 debug_printf("Hello, world!\n");
753 if (ms_ticks - last_blink >= 1000) {
755 last_blink = ms_ticks;
759 if (usart_get_flag(USART1, USART_SR_RXNE)) {
760 uint ch = usart_recv(USART1);
763 gpio_set(GPIOA, GPIO8);
765 gpio_clear(GPIOA, GPIO8);
774 if (usb_event_pending) {
776 usb_event_pending = 0;
777 nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
778 nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
781 wait_for_interrupt();