]> mj.ucw.cz Git - home-hw.git/blob - dmx/firmware/main.c
DMX: New board
[home-hw.git] / dmx / firmware / main.c
1 /*
2  *      DMX512 Interface
3  *
4  *      (c) 2020 Martin Mareš <mj@ucw.cz>
5  */
6
7 #include "util.h"
8 #include "interface.h"
9
10 #include <libopencm3/cm3/cortex.h>
11 #include <libopencm3/cm3/nvic.h>
12 #include <libopencm3/cm3/systick.h>
13 #include <libopencm3/cm3/scb.h>
14 #include <libopencm3/stm32/rcc.h>
15 #include <libopencm3/stm32/desig.h>
16 #include <libopencm3/stm32/gpio.h>
17 #include <libopencm3/stm32/timer.h>
18 #include <libopencm3/stm32/usart.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_in_hse_8mhz_out_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_TIM3);
34         rcc_periph_clock_enable(RCC_USART1);
35         rcc_periph_clock_enable(RCC_USART3);
36         rcc_periph_clock_enable(RCC_USB);
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_TIM3);
42         rcc_periph_reset_pulse(RST_USART1);
43         rcc_periph_reset_pulse(RST_USART3);
44         rcc_periph_reset_pulse(RST_USB);
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         // PB10 = TXD3 for DMX
59         // PB11 = RXD3 for DMX
60         gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO10);
61         gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_FLOAT, GPIO11);
62
63         // PB1 = TX enable for DMX (always on)
64         gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, GPIO1);
65         gpio_set(GPIOB, GPIO1);
66 }
67
68 static void usart_init(void)
69 {
70         usart_set_baudrate(USART1, 115200);
71         usart_set_databits(USART1, 8);
72         usart_set_stopbits(USART1, USART_STOPBITS_1);
73         usart_set_mode(USART1, USART_MODE_TX);
74         usart_set_parity(USART1, USART_PARITY_NONE);
75         usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE);
76
77         usart_enable(USART1);
78 }
79
80 /*** System ticks ***/
81
82 static volatile u32 ms_ticks;
83
84 void sys_tick_handler(void)
85 {
86         ms_ticks++;
87 }
88
89 static void tick_init(void)
90 {
91         systick_set_frequency(1000, CPU_CLOCK_MHZ * 1000000);
92         systick_counter_enable();
93         systick_interrupt_enable();
94 }
95
96 static void delay_ms(uint ms)
97 {
98         u32 start_ticks = ms_ticks;
99         while (ms_ticks - start_ticks < ms)
100                 ;
101 }
102
103 /*** DMX ***/
104
105 #define DMX_MAX_PACKET_SIZE 64
106
107 static volatile byte dmx_state;
108 static byte dmx_packet[DMX_MAX_PACKET_SIZE];
109 static byte dmx_pos, dmx_len;
110
111 static byte dmx_next_packet[DMX_MAX_PACKET_SIZE];
112 static byte dmx_next_len;
113
114 #undef DEBUG_DMX
115 #ifdef DEBUG_DMX
116 #define DMX_DEBUG(ch) debug_putc(ch)
117 #else
118 #define DMX_DEBUG(ch) do { } while (0)
119 #endif
120
121 enum dmx_state {
122         DMX_STATE_IDLE = 0,
123         DMX_STATE_BREAK,
124         DMX_STATE_MARK,
125         DMX_STATE_DATA,
126         DMX_STATE_LAST_BYTE,
127         DMX_STATE_GAP,
128 };
129
130 static void dmx_init(void)
131 {
132         usart_set_baudrate(USART3, 250000);
133         usart_set_databits(USART3, 8);
134         usart_set_stopbits(USART3, USART_STOPBITS_2);
135         usart_set_mode(USART3, USART_MODE_TX);
136         usart_set_parity(USART3, USART_PARITY_NONE);
137         usart_set_flow_control(USART3, USART_FLOWCONTROL_NONE);
138         nvic_enable_irq(NVIC_USART3_IRQ);
139
140         usart_enable(USART3);
141
142         timer_set_prescaler(TIM3, CPU_CLOCK_MHZ - 1);   // 1 MHz
143         timer_set_mode(TIM3, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP);
144         timer_update_on_overflow(TIM3);
145         timer_disable_preload(TIM3);
146         timer_one_shot_mode(TIM3);
147         timer_enable_irq(TIM3, TIM_DIER_UIE);
148         nvic_enable_irq(NVIC_TIM3_IRQ);
149
150         // Until we get data from USB, send "turn everything off" packets
151         memset(dmx_next_packet, 0, DMX_MAX_PACKET_SIZE);
152         dmx_next_len = DMX_MAX_PACKET_SIZE;
153 }
154
155 void tim3_isr(void)
156 {
157         if (TIM_SR(TIM3) & TIM_SR_UIF) {
158                 TIM_SR(TIM3) &= ~TIM_SR_UIF;
159                 switch (dmx_state) {
160                         case DMX_STATE_BREAK:
161                                 // Send mark for 50 μs
162                                 DMX_DEBUG('m');
163                                 dmx_state = DMX_STATE_MARK;
164                                 gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, GPIO10);
165                                 timer_set_period(TIM3, 199);
166                                 timer_generate_event(TIM3, TIM_EGR_UG);
167                                 timer_enable_counter(TIM3);
168                                 break;
169                         case DMX_STATE_MARK:
170                                 // Start sending data bytes
171                                 DMX_DEBUG('d');
172                                 dmx_state = DMX_STATE_DATA;
173                                 usart_enable_tx_interrupt(USART3);
174                                 break;
175                         case DMX_STATE_GAP:
176                                 DMX_DEBUG('>');
177                                 dmx_state = DMX_STATE_IDLE;
178                                 break;
179                 }
180         }
181 }
182
183 void usart3_isr(void)
184 {
185         u32 status = USART_SR(USART3);
186
187         if (dmx_state == DMX_STATE_DATA) {
188                 if (status & USART_SR_TXE) {
189                         if (dmx_pos < dmx_len) {
190                                 DMX_DEBUG('.');
191                                 usart_send(USART3, dmx_packet[dmx_pos++]);
192                         } else {
193                                 // The transmitter is double-buffered, so at this moment, it is transmitting
194                                 // the last byte of the frame. Wait until transfer is completed.
195                                 DMX_DEBUG('l');
196                                 usart_disable_tx_interrupt(USART3);
197                                 USART_CR1(USART3) |= USART_CR1_TCIE;
198                                 dmx_state = DMX_STATE_LAST_BYTE;
199                         }
200                 }
201         } else if (dmx_state == DMX_STATE_LAST_BYTE) {
202                 // Transfer of the last byte is complete, but we have to wait
203                 // before the start of the next packet: minimum time between two
204                 // breaks must be at least 1204 μs. We already sent a 200μs break,
205                 // 200μs mark, and dmx_len 44μs data slots.
206                 USART_CR1(USART3) &= ~USART_CR1_TCIE;
207                 uint sent = 200 + 200 + 44*dmx_len;
208                 if (sent < 1300) {
209                         DMX_DEBUG('g');
210                         dmx_state = DMX_STATE_GAP;
211                         timer_set_period(TIM3, 1300 - sent - 1);
212                         timer_generate_event(TIM3, TIM_EGR_UG);
213                         timer_enable_counter(TIM3);
214                 } else {
215                         DMX_DEBUG('>');
216                         dmx_state = DMX_STATE_IDLE;
217                 }
218         }
219 }
220
221 static void dmx_send(void)
222 {
223         if (dmx_state != DMX_STATE_IDLE)
224                 return;
225
226         if (!dmx_len)
227                 return;
228
229         dmx_pos = 0;
230
231         // Send break for 200 μs
232         DMX_DEBUG('<');
233         dmx_state = DMX_STATE_BREAK;
234         gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO10);
235         gpio_clear(GPIOB, GPIO10);
236
237         timer_set_period(TIM3, 199);
238         timer_generate_event(TIM3, TIM_EGR_UG);
239         timer_enable_counter(TIM3);
240 }
241
242 /*** USB ***/
243
244 static usbd_device *usbd_dev;
245
246 enum usb_string {
247         STR_MANUFACTURER = 1,
248         STR_PRODUCT,
249         STR_SERIAL,
250 };
251
252 static char usb_serial_number[13];
253
254 static const char *usb_strings[] = {
255         "United Computer Wizards",
256         "DMX512 Interface",
257         usb_serial_number,
258 };
259
260 static const struct usb_device_descriptor device = {
261         .bLength = USB_DT_DEVICE_SIZE,
262         .bDescriptorType = USB_DT_DEVICE,
263         .bcdUSB = 0x0200,
264         .bDeviceClass = 0xFF,
265         .bDeviceSubClass = 0,
266         .bDeviceProtocol = 0,
267         .bMaxPacketSize0 = 64,
268         .idVendor = DMX_USB_VENDOR,
269         .idProduct = DMX_USB_PRODUCT,
270         .bcdDevice = DMX_USB_VERSION,
271         .iManufacturer = STR_MANUFACTURER,
272         .iProduct = STR_PRODUCT,
273         .iSerialNumber = STR_SERIAL,
274         .bNumConfigurations = 1,
275 };
276
277 static const struct usb_endpoint_descriptor endpoints[] = {{
278         // Bulk end-point for sending values to DMX
279         .bLength = USB_DT_ENDPOINT_SIZE,
280         .bDescriptorType = USB_DT_ENDPOINT,
281         .bEndpointAddress = 0x01,
282         .bmAttributes = USB_ENDPOINT_ATTR_BULK,
283         .wMaxPacketSize = 64,
284         .bInterval = 1,
285 }};
286
287 static const struct usb_interface_descriptor iface = {
288         .bLength = USB_DT_INTERFACE_SIZE,
289         .bDescriptorType = USB_DT_INTERFACE,
290         .bInterfaceNumber = 0,
291         .bAlternateSetting = 0,
292         .bNumEndpoints = 1,
293         .bInterfaceClass = 0xFF,
294         .bInterfaceSubClass = 0,
295         .bInterfaceProtocol = 0,
296         .iInterface = 0,
297         .endpoint = endpoints,
298 };
299
300 static const struct usb_dfu_descriptor dfu_function = {
301         .bLength = sizeof(struct usb_dfu_descriptor),
302         .bDescriptorType = DFU_FUNCTIONAL,
303         .bmAttributes = USB_DFU_CAN_DOWNLOAD | USB_DFU_WILL_DETACH,
304         .wDetachTimeout = 255,
305         .wTransferSize = 1024,
306         .bcdDFUVersion = 0x0100,
307 };
308
309 static const struct usb_interface_descriptor dfu_iface = {
310         .bLength = USB_DT_INTERFACE_SIZE,
311         .bDescriptorType = USB_DT_INTERFACE,
312         .bInterfaceNumber = 1,
313         .bAlternateSetting = 0,
314         .bNumEndpoints = 0,
315         .bInterfaceClass = 0xFE,
316         .bInterfaceSubClass = 1,
317         .bInterfaceProtocol = 1,
318         .iInterface = 0,
319
320         .extra = &dfu_function,
321         .extralen = sizeof(dfu_function),
322 };
323
324 static const struct usb_interface ifaces[] = {{
325         .num_altsetting = 1,
326         .altsetting = &iface,
327 }, {
328         .num_altsetting = 1,
329         .altsetting = &dfu_iface,
330 }};
331
332 static const struct usb_config_descriptor config = {
333         .bLength = USB_DT_CONFIGURATION_SIZE,
334         .bDescriptorType = USB_DT_CONFIGURATION,
335         .wTotalLength = 0,
336         .bNumInterfaces = 2,
337         .bConfigurationValue = 1,
338         .iConfiguration = 0,
339         .bmAttributes = 0x80,
340         .bMaxPower = 50,        // multiplied by 2 mA
341         .interface = ifaces,
342 };
343
344 static byte usb_configured;
345 static uint8_t usbd_control_buffer[64];
346
347 static void dfu_detach_complete(usbd_device *dev UNUSED, struct usb_setup_data *req UNUSED)
348 {
349         // Reset to bootloader, which implements the rest of DFU
350         debug_printf("Switching to DFU\n");
351         debug_flush();
352         scb_reset_core();
353 }
354
355 static enum usbd_request_return_codes dfu_control_cb(usbd_device *dev UNUSED,
356         struct usb_setup_data *req,
357         uint8_t **buf UNUSED,
358         uint16_t *len UNUSED,
359         void (**complete)(usbd_device *dev, struct usb_setup_data *req))
360 {
361         if (req->bmRequestType != 0x21 || req->bRequest != DFU_DETACH)
362                 return USBD_REQ_NOTSUPP;
363
364         *complete = dfu_detach_complete;
365         return USBD_REQ_HANDLED;
366 }
367
368 static void ep01_cb(usbd_device *dev, uint8_t ep UNUSED)
369 {
370         // We received a frame from the USB host
371         uint len = usbd_ep_read_packet(dev, 0x01, dmx_next_packet, DMX_MAX_PACKET_SIZE);
372         debug_printf("USB: Host sent %u bytes\n", len);
373         dmx_next_len = len;
374 }
375
376 static void set_config_cb(usbd_device *dev, uint16_t wValue UNUSED)
377 {
378         usbd_register_control_callback(
379                 dev,
380                 USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
381                 USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
382                 dfu_control_cb);
383         usbd_ep_setup(dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, ep01_cb);
384         usb_configured = 1;
385 }
386
387 static void reset_cb(void)
388 {
389         debug_printf("USB: Reset\n");
390         usb_configured = 0;
391 }
392
393 static volatile bool usb_event_pending;
394
395 void usb_lp_can_rx0_isr(void)
396 {
397         /*
398          *  We handle USB in the main loop to avoid race conditions between
399          *  USB interrupts and other code. However, we need an interrupt to
400          *  up the main loop from sleep.
401          *
402          *  We set up only the low-priority ISR, because high-priority ISR handles
403          *  only double-buffered bulk transfers and isochronous transfers.
404          */
405         nvic_disable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
406         usb_event_pending = 1;
407 }
408
409 static void usb_init(void)
410 {
411         // Simulate USB disconnect
412         gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_50_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, GPIO11 | GPIO12);
413         gpio_clear(GPIOA, GPIO11 | GPIO12);
414         delay_ms(100);
415
416         usbd_dev = usbd_init(
417                 &st_usbfs_v1_usb_driver,
418                 &device,
419                 &config,
420                 usb_strings,
421                 ARRAY_SIZE(usb_strings),
422                 usbd_control_buffer,
423                 sizeof(usbd_control_buffer)
424         );
425         usbd_register_reset_callback(usbd_dev, reset_cb);
426         usbd_register_set_config_callback(usbd_dev, set_config_cb);
427         usb_event_pending = 1;
428 }
429
430 /*** Main ***/
431
432 int main(void)
433 {
434         clock_init();
435         gpio_init();
436         tick_init();
437         usart_init();
438         desig_get_unique_id_as_dfu(usb_serial_number);
439
440         debug_printf("Hail, Lord Damian! Thy DMX interface is ready.\n");
441
442         usb_init();
443         dmx_init();
444
445         u32 last_blink = 0;
446         u32 last_send = 0;
447
448         for (;;) {
449                 if (ms_ticks - last_blink >= 100) {
450                         debug_led_toggle();
451                         last_blink = ms_ticks;
452                         dmx_send();
453                 }
454
455                 if (usb_event_pending) {
456                         usbd_poll(usbd_dev);
457                         usb_event_pending = 0;
458                         nvic_clear_pending_irq(NVIC_USB_LP_CAN_RX0_IRQ);
459                         nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ);
460                 }
461
462                 if (dmx_state == DMX_STATE_IDLE) {
463                         if (dmx_next_len) {
464                                 // We have a new packet to send
465                                 debug_printf("Sending new packet: %d bytes\n", dmx_next_len);
466                                 memcpy(dmx_packet, dmx_next_packet, dmx_next_len);
467                                 dmx_len = dmx_next_len;
468                                 dmx_next_len = 0;
469                                 dmx_send();
470                                 last_send = ms_ticks;
471                         } else if (ms_ticks - last_send >= 100) {
472                                 // Re-send every 100 ms
473                                 // debug_printf("Re-send: %d bytes\n", dmx_len);
474                                 dmx_send();
475                                 last_send = ms_ticks;
476                         }
477                 }
478
479                 wait_for_interrupt();
480         }
481
482         return 0;
483 }