]> mj.ucw.cz Git - home-hw.git/blob - test-display2/main.c
test-display2: More IR decoding
[home-hw.git] / test-display2 / main.c
1 /*
2  *      Workshop Clock
3  *
4  *      (c) 2020-2023 Martin Mareš <mj@ucw.cz>
5  */
6
7 #include "util.h"
8
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/i2c.h>
18 #include <libopencm3/stm32/timer.h>
19 #include <libopencm3/usb/dfu.h>
20 #include <libopencm3/usb/usbd.h>
21
22 #include <string.h>
23
24 /*** Hardware init ***/
25
26 static void clock_init(void)
27 {
28         rcc_clock_setup_pll(&rcc_hse_configs[RCC_CLOCK_HSE8_72MHZ]);
29
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_I2C1);
34         rcc_periph_clock_enable(RCC_USART1);
35         rcc_periph_clock_enable(RCC_USB);
36         rcc_periph_clock_enable(RCC_TIM1);
37
38         rcc_periph_reset_pulse(RST_GPIOA);
39         rcc_periph_reset_pulse(RST_GPIOB);
40         rcc_periph_reset_pulse(RST_GPIOC);
41         rcc_periph_reset_pulse(RST_I2C1);
42         rcc_periph_reset_pulse(RST_USART1);
43         rcc_periph_reset_pulse(RST_USB);
44         rcc_periph_reset_pulse(RST_TIM1);
45 }
46
47 static void gpio_init(void)
48 {
49         // PA9 = TXD1 for debugging console
50         // PA10 = RXD1 for debugging console
51         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO9);
52         gpio_set_mode(GPIOA, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO10);
53
54         // PC13 = BluePill LED
55         gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO13);
56         gpio_clear(GPIOC, GPIO13);
57
58         // PB7 = SDA for display controller
59         // PB6 = SCL for display controller
60         gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, GPIO6 | GPIO7);
61
62         // PA8 = SFH5110 output (5V tolerant) connected to TIM1_CH1
63         gpio_set_mode(GPIOC, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO8);
64 }
65
66 static void usart_init(void)
67 {
68         usart_set_baudrate(USART1, 115200);
69         usart_set_databits(USART1, 8);
70         usart_set_stopbits(USART1, USART_STOPBITS_1);
71         usart_set_mode(USART1, USART_MODE_TX);
72         usart_set_parity(USART1, USART_PARITY_NONE);
73         usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
74
75         usart_enable(USART1);
76 }
77
78 /*** System ticks ***/
79
80 static volatile u32 ms_ticks;
81
82 void sys_tick_handler(void)
83 {
84         ms_ticks++;
85 }
86
87 static void tick_init(void)
88 {
89         systick_set_frequency(1000, CPU_CLOCK_MHZ * 1000000);
90         systick_counter_enable();
91         systick_interrupt_enable();
92 }
93
94 static void delay_ms(uint ms)
95 {
96         u32 start_ticks = ms_ticks;
97         while (ms_ticks - start_ticks < ms)
98                 ;
99 }
100
101 /*** Display ***/
102
103 /*
104  *      Display digits:
105  *
106  *                 ---- 40 ----
107  *               |              |
108  *               |              |
109  *              20              80
110  *               |              |
111  *               |              |
112  *                 ---- 10 ----
113  *               |              |
114  *               |              |
115  *              08              02
116  *               |              |
117  *               |              |
118  *                 ---- 04 ----
119  *                                      (01)
120  */
121
122 static byte disp[4];
123 static byte ctrl = 0x56;
124
125 static void display_update(void)
126 {
127         // debug_puts("Display update\n");
128         byte cmds[4];
129         cmds[0] = 0;
130         cmds[1] = ctrl;
131         cmds[2] = ((disp[1] & 0x88) >> 3) | ((disp[1] & 0x44) >> 1) | ((disp[1] & 0x22) << 1) | ((disp[1] & 0x11) << 3);
132         cmds[3] = disp[0];
133         i2c_transfer7(I2C1, 0x76/2, (byte *) cmds, sizeof(cmds), NULL, 0);
134
135         cmds[2] = ((disp[3] & 0x88) >> 3) | ((disp[3] & 0x44) >> 1) | ((disp[3] & 0x22) << 1) | ((disp[3] & 0x11) << 3);
136         cmds[3] = disp[2];
137         i2c_transfer7(I2C1, 0x70/2, (byte *) cmds, sizeof(cmds), NULL, 0);
138
139         // debug_puts("Update done\n");
140 }
141
142 static void display_init(void)
143 {
144         debug_puts("I2C init\n");
145         i2c_peripheral_disable(I2C1);
146         i2c_set_speed(I2C1, i2c_speed_sm_100k, rcc_apb1_frequency / 1000000);
147         i2c_peripheral_enable(I2C1);
148
149         disp[0] = 0x82;
150         disp[1] = 0xdc;
151         disp[2] = 0xd6;
152         disp[3] = 0xb2;
153         display_update();
154 }
155
156 static void display_test(void)
157 {
158         static byte mode;
159
160         disp[0] ^= 0x01;
161         display_update();
162
163 #if 0
164         byte cmds[] = { 0x00, mode ? 0x77 : 0x77 };
165         i2c_transfer7(I2C1, 0x70/2, (byte *) cmds, sizeof(cmds), NULL, 0);
166 #endif
167
168 #if 0
169         byte disp[] = { 0xff, 0xff, mode ? 0xff : 0x00, mode ? 0xff : 0xff };
170         byte cmds[] = { 0x00, 0x77, 0, 0, 0, 0 };
171         cmds[2] = (disp[0] & 0xf0) | (disp[2] >> 4);
172         cmds[3] = (disp[1] & 0xf0) | (disp[3] >> 4);
173         cmds[4] = (disp[2] & 0x0f) | (disp[0] << 4);
174         cmds[5] = (disp[3] & 0x0f) | (disp[1] << 4);
175         i2c_transfer7(I2C1, 0x70/2, (byte *) cmds, sizeof(cmds), NULL, 0);
176 #endif
177
178         mode = !mode;
179 }
180
181 static const byte lcd_font[] = {
182         [0] = 0xee,
183         [1] = 0x82,
184         [2] = 0xdc,
185         [3] = 0xd6,
186         [4] = 0xb2,
187         [5] = 0x76,
188         [6] = 0x7e,
189         [7] = 0xc2,
190         [8] = 0xfe,
191         [9] = 0xf6,
192         [10] = 0xea,
193         [11] = 0x3e,
194         [12] = 0x6c,
195         [13] = 0x9e,
196         [14] = 0x7c,
197         [15] = 0x78,
198 };
199
200 /*** Infrared Remote Control ***/
201
202 static void ir_init(void)
203 {
204         debug_puts("IR init\n");
205
206         // TIM1 will measure pulses and spaces between them with 1μs resolution
207         timer_set_prescaler(TIM1, 71);          // 72 MHz / 72 = 1 MHz
208         timer_set_mode(TIM1, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP);
209         timer_set_period(TIM1, 65535);
210         timer_update_on_overflow(TIM1);
211
212         // IC1 will trigger on TI1 (TIM1_CH1) falling edge
213         timer_ic_set_input(TIM1, TIM_IC1, TIM_IC_IN_TI1);
214         // timer_ic_set_filter(TIM1, TIM_IC1, TIM_IC_OFF);
215         timer_set_oc_polarity_low(TIM1, TIM_OC1);       // OC functions affect IC, too
216
217         // IC2 will trigger on TI1 (TIM1_CH1) rising edge
218         timer_ic_set_input(TIM1, TIM_IC2, TIM_IC_IN_TI1);
219         timer_set_oc_polarity_high(TIM1, TIM_OC2);
220
221         // OC3 will trigger on a break longer than 50 ms
222         timer_set_oc_mode(TIM1, TIM_OC3, TIM_OCM_ACTIVE);
223         timer_set_oc_value(TIM1, TIM_OC3, 30000);
224
225         // Program slave controller to reset the timer on IC1
226         timer_slave_set_trigger(TIM1, TIM_SMCR_TS_TI1FP1);
227         timer_slave_set_mode(TIM1, TIM_SMCR_SMS_RM);
228
229         // Request interrupts
230         timer_enable_irq(TIM1, TIM_DIER_CC1IE | TIM_DIER_CC2IE | TIM_DIER_CC3IE);
231         nvic_enable_irq(NVIC_TIM1_CC_IRQ);
232
233         // Enable ICs and OCs
234         timer_enable_oc_output(TIM1, TIM_OC1);
235         timer_enable_oc_output(TIM1, TIM_OC2);
236         timer_enable_oc_output(TIM1, TIM_OC3);
237
238         timer_enable_counter(TIM1);
239 }
240
241 // Circular queue of pulse durations
242 #define IR_MAX_PULSES 32
243 static u32 ir_pulses[IR_MAX_PULSES];    // Top 16 bits = mark, bottom 16 bits = space
244 static u16 ir_last_pulse;
245 static uint ir_pulses_rx, ir_pulses_tx;
246
247 #define IR_INF 0xffff
248
249 #define IR_MARK(x) (uint)((x) >> 16)
250 #define IR_SPACE(x) (uint)((x) & 0xffff)
251
252 static inline bool between(uint x, uint min, uint max)
253 {
254         return x >= min && x <= max;
255 }
256
257 static void ir_record_pulse(uint mark, uint space)
258 {
259         uint i = ir_pulses_tx;
260         ir_pulses_tx = (i + 1) % IR_MAX_PULSES;
261         if (ir_pulses_tx != ir_pulses_rx) {
262                 ir_pulses[i] = (mark << 16) | space;
263         } else {
264                 // Overflow detected
265                 ir_pulses[i] = (IR_INF << 16) | IR_INF;
266         }
267 }
268
269 void tim1_cc_isr(void)
270 {
271         if (TIM_SR(TIM1) & TIM_SR_CC1IF) {
272                 TIM_SR(TIM1) &= ~TIM_SR_CC1IF;
273                 u16 now = TIM_CCR1(TIM1);
274                 if (ir_last_pulse) {
275                         ir_record_pulse(ir_last_pulse, now - ir_last_pulse);
276                         ir_last_pulse = 0;
277                 }
278         }
279         if (TIM_SR(TIM1) & TIM_SR_CC2IF) {
280                 TIM_SR(TIM1) &= ~TIM_SR_CC2IF;
281                 ir_last_pulse = TIM_CCR2(TIM1);
282         }
283         if (TIM_SR(TIM1) & TIM_SR_CC3IF) {
284                 TIM_SR(TIM1) &= ~TIM_SR_CC3IF;
285                 if (ir_last_pulse) {
286                         ir_record_pulse(ir_last_pulse, IR_INF);
287                         ir_last_pulse = 0;
288                 }
289         }
290 }
291
292 static u32 ir_get_pulse(void)
293 {
294         u32 out = 0;
295
296         cm_disable_interrupts();
297         if (ir_pulses_rx != ir_pulses_tx) {
298                 out = ir_pulses[ir_pulses_rx];
299                 ir_pulses_rx = (ir_pulses_rx + 1) % IR_MAX_PULSES;
300         }
301         cm_enable_interrupts();
302         return out;
303 }
304
305 // Decoder for Onkyo RC-748S
306
307 static void ir_decode(void)
308 {
309         u32 pulse = ir_get_pulse();
310         if (!pulse)
311                 return;
312
313         uint mark = IR_MARK(pulse);
314         uint space = IR_SPACE(pulse);
315
316 #ifdef IR_TEST
317         debug_printf("IR: %d %d\n", mark, space);
318         return;
319 #endif
320
321         static u16 ir_bits;
322         static u32 ir_code;
323 #define IR_ERR 0xff
324
325         debug_printf("IR(%d): %d %d\n", ir_bits, mark, space);
326
327         if (space == IR_INF) {
328                 ir_bits = 0;
329         } else if (ir_bits == IR_ERR) {
330                 // Error state
331         } else if (ir_bits == 0) {
332                 // Start?
333                 if (between(mark, 8900, 9200)) {
334                         if (between(space, 4200, 4600)) {
335                                 ir_bits = 1;
336                                 ir_code = 0;
337                         } else if (between(space, 2000, 2300)) {
338                                 debug_printf("==> REP\n");
339                                 ir_bits = IR_ERR;
340                         }
341                 }
342         } else {
343                 if (between(mark, 500, 700)) {
344                         ir_bits++;
345                         if (between(space, 400, 700)) {
346                                 // 0
347                         } else if (between(space, 1500, 1800)) {
348                                 // 1
349                                 ir_code |= 1U << (33 - ir_bits);
350                         } else {
351                                 ir_bits = IR_ERR;
352                         }
353                         if (ir_bits == 33) {
354                                 debug_printf("==> %08x\n", (uint)ir_code);
355                                 ir_bits = IR_ERR;
356                         }
357                 } else {
358                         ir_bits = IR_ERR;
359                 }
360         }
361 }
362
363 /*** USB ***/
364
365 static usbd_device *usbd_dev;
366
367 enum usb_string {
368         STR_MANUFACTURER = 1,
369         STR_PRODUCT,
370         STR_SERIAL,
371 };
372
373 static char usb_serial_number[13];
374
375 static const char *usb_strings[] = {
376         "United Computer Wizards",
377         "Workshop Clock",
378         usb_serial_number,
379 };
380
381 static const struct usb_device_descriptor device = {
382         .bLength = USB_DT_DEVICE_SIZE,
383         .bDescriptorType = USB_DT_DEVICE,
384         .bcdUSB = 0x0200,
385         .bDeviceClass = 0xFF,
386         .bDeviceSubClass = 0,
387         .bDeviceProtocol = 0,
388         .bMaxPacketSize0 = 64,
389         .idVendor = 0x4242,
390         .idProduct = 0x0007,
391         .bcdDevice = 0x0000,
392         .iManufacturer = STR_MANUFACTURER,
393         .iProduct = STR_PRODUCT,
394         .iSerialNumber = STR_SERIAL,
395         .bNumConfigurations = 1,
396 };
397
398 static const struct usb_endpoint_descriptor endpoints[] = {{
399         // Bulk end-point for sending values to the display
400         .bLength = USB_DT_ENDPOINT_SIZE,
401         .bDescriptorType = USB_DT_ENDPOINT,
402         .bEndpointAddress = 0x01,
403         .bmAttributes = USB_ENDPOINT_ATTR_BULK,
404         .wMaxPacketSize = 64,
405         .bInterval = 1,
406 }};
407
408 static const struct usb_interface_descriptor iface = {
409         .bLength = USB_DT_INTERFACE_SIZE,
410         .bDescriptorType = USB_DT_INTERFACE,
411         .bInterfaceNumber = 0,
412         .bAlternateSetting = 0,
413         .bNumEndpoints = 1,
414         .bInterfaceClass = 0xFF,
415         .bInterfaceSubClass = 0,
416         .bInterfaceProtocol = 0,
417         .iInterface = 0,
418         .endpoint = endpoints,
419 };
420
421 static const struct usb_dfu_descriptor dfu_function = {
422         .bLength = sizeof(struct usb_dfu_descriptor),
423         .bDescriptorType = DFU_FUNCTIONAL,
424         .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
425         .wDetachTimeout = 255,
426         .wTransferSize = 1024,
427         .bcdDFUVersion = 0x0100,
428 };
429
430 static const struct usb_interface_descriptor dfu_iface = {
431         .bLength = USB_DT_INTERFACE_SIZE,
432         .bDescriptorType = USB_DT_INTERFACE,
433         .bInterfaceNumber = 1,
434         .bAlternateSetting = 0,
435         .bNumEndpoints = 0,
436         .bInterfaceClass = 0xFE,
437         .bInterfaceSubClass = 1,
438         .bInterfaceProtocol = 1,
439         .iInterface = 0,
440
441         .extra = &dfu_function,
442         .extralen = sizeof(dfu_function),
443 };
444
445 static const struct usb_interface ifaces[] = {{
446         .num_altsetting = 1,
447         .altsetting = &iface,
448 }, {
449         .num_altsetting = 1,
450         .altsetting = &dfu_iface,
451 }};
452
453 static const struct usb_config_descriptor config = {
454         .bLength = USB_DT_CONFIGURATION_SIZE,
455         .bDescriptorType = USB_DT_CONFIGURATION,
456         .wTotalLength = 0,
457         .bNumInterfaces = 2,
458         .bConfigurationValue = 1,
459         .iConfiguration = 0,
460         .bmAttributes = 0x80,
461         .bMaxPower = 50,        // multiplied by 2 mA
462         .interface = ifaces,
463 };
464
465 static byte usb_configured;
466 static uint8_t usbd_control_buffer[64];
467
468 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
469 {
470         // Reset to bootloader, which implements the rest of DFU
471         debug_printf("Switching to DFU\n");
472         debug_flush();
473         scb_reset_core();
474 }
475
476 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
477         struct usb_setup_data *req,
478         uint8_t **buf UNUSED,
479         uint16_t *len UNUSED,
480         void (**complete)(usbd_device *dev, struct usb_setup_data *req))
481 {
482         if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
483                 return USBD_REQ_NOTSUPP;
484
485         *complete = dfu_detach_complete;
486         return USBD_REQ_HANDLED;
487 }
488
489 static void ep01_cb(usbd_device *dev, uint8_t ep UNUSED)
490 {
491         // We received a frame from the USB host
492         byte buf[8];
493         uint len = usbd_ep_read_packet(dev, 0x01, buf, 8);
494         debug_printf("USB: Host sent %u bytes\n", len);
495         if (len >= 5) {
496                 for (uint i=0; i<4; i++) {
497                         if (buf[i] < 16)
498                                 disp[i] = lcd_font[buf[i]];
499                         else
500                                 disp[i] = 0;
501                 }
502                 if (buf[4])
503                         disp[1] |= 1;
504                 display_update();
505         }
506 }
507
508 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
509 {
510         usbd_register_control_callback(
511                 dev,
512                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
513                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
514                 dfu_control_cb);
515         usbd_ep_setup(dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, ep01_cb);
516         usb_configured = 1;
517 }
518
519 static void reset_cb(void)
520 {
521         debug_printf("USB: Reset\n");
522         usb_configured = 0;
523 }
524
525 static volatile bool usb_event_pending;
526
527 void usb_lp_can_rx0_isr(void)
528 {
529         /*
530          *  We handle USB in the main loop to avoid race conditions between
531          *  USB interrupts and other code. However, we need an interrupt to
532          *  up the main loop from sleep.
533          *
534          *  We set up only the low-priority ISR, because high-priority ISR handles
535          *  only double-buffered bulk transfers and isochronous transfers.
536          */
537         nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
538         usb_event_pending = 1;
539 }
540
541 static void usb_init(void)
542 {
543         // Simulate USB disconnect
544         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
545         gpio_clear(GPIOA, GPIO11 | GPIO12);
546         delay_ms(100);
547
548         usbd_dev = usbd_init(
549                 &st_usbfs_v1_usb_driver,
550                 &device,
551                 &config,
552                 usb_strings,
553                 ARRAY_SIZE(usb_strings),
554                 usbd_control_buffer,
555                 sizeof(usbd_control_buffer)
556         );
557         usbd_register_reset_callback(usbd_dev, reset_cb);
558         usbd_register_set_config_callback(usbd_dev, set_config_cb);
559         usb_event_pending = 1;
560 }
561
562 /*** Main ***/
563
564 int main(void)
565 {
566         clock_init();
567         gpio_init();
568         usart_init();
569
570         tick_init();
571         desig_get_unique_id_as_dfu(usb_serial_number);
572
573         debug_printf("Hello, world!\n");
574
575         usb_init();
576         display_init();
577         ir_init();
578
579         u32 last_blink = 0;
580
581         for (;;) {
582                 if (ms_ticks - last_blink >= 500) {
583                         debug_led_toggle();
584                         last_blink = ms_ticks;
585                         display_test();
586                 }
587
588                 ir_decode();
589
590                 if (usb_event_pending) {
591                         usbd_poll(usbd_dev);
592                         usb_event_pending = 0;
593                         nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
594                         nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
595                 }
596
597                 wait_for_interrupt();
598         }
599
600         return 0;
601 }