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