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