├── .gitignore ├── gdbinit ├── .gitmodules ├── StrPrintf.h ├── led.h ├── systick.h ├── uart.h ├── button_boot.h ├── stm32f4-1bitsy.ld ├── stm32f4-discovery.ld ├── usb.h ├── README.md ├── button_boot.c ├── systick.c ├── led.c ├── uart.c ├── usb-serial.c ├── Makefile ├── CBUF.h ├── usb.c ├── StrPrintf.c └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | build-*/ 2 | usb-ser-mon.log 3 | -------------------------------------------------------------------------------- /gdbinit: -------------------------------------------------------------------------------- 1 | monitor jtag_scan 2 | attach 1 3 | load 4 | break main 5 | run 6 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "libopencm3"] 2 | path = libopencm3 3 | url = https://github.com/libopencm3/libopencm3 4 | -------------------------------------------------------------------------------- /StrPrintf.h: -------------------------------------------------------------------------------- 1 | /* Any copyright is dedicated to the Public Domain. 2 | * http://creativecommons.org/publicdomain/zero/1.0/ */ 3 | 4 | #pragma once 5 | 6 | #include 7 | 8 | typedef int (*StrXPrintfFunc)(void *outParm, int c); 9 | 10 | int 11 | StrPrintf(char* outStr, int maxLen, const char* fmt, ...); 12 | 13 | int 14 | StrXPrintf(StrXPrintfFunc outFunc, void* outParm, const char* fmt, ...); 15 | 16 | int 17 | vStrPrintf(char* outStr, int maxLen, const char* fmt, va_list args); 18 | 19 | int 20 | vStrXPrintf(StrXPrintfFunc outFunc,void* outParm, const char* fmt, 21 | va_list args); 22 | -------------------------------------------------------------------------------- /led.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Dave Hylands 3 | * 4 | * This library is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU Lesser General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This library is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public License 15 | * along with this library. If not, see . 16 | */ 17 | 18 | #ifndef LED_H 19 | #define LED_H 20 | 21 | void led_init(void); 22 | void led_on(unsigned led_num); 23 | void led_off(unsigned led_num); 24 | void led_toggle(unsigned led_num); 25 | 26 | #endif // LED_H 27 | -------------------------------------------------------------------------------- /systick.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the libopencm3 project. 3 | * 4 | * Copyright (C) 2010 Gareth McMullin 5 | * 6 | * This library is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This library is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with this library. If not, see . 18 | */ 19 | 20 | #ifndef SYSTICK_H 21 | #define SYSTICK_H 22 | 23 | #include 24 | 25 | extern volatile uint32_t system_millis; 26 | 27 | void systick_init(void); 28 | 29 | void msleep(uint32_t msecs); 30 | 31 | #endif // SYSTICK_H 32 | -------------------------------------------------------------------------------- /uart.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Dave Hylands 3 | * 4 | * This library is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU Lesser General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This library is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public License 15 | * along with this library. If not, see . 16 | */ 17 | 18 | #ifndef UART_H 19 | #define UART_H 20 | 21 | #include 22 | #include 23 | 24 | void uart_init(void); 25 | void uart_printf(const char *fmt, ...); 26 | 27 | void uart_send_byte(uint8_t ch); 28 | void uart_send_strn(const char *str, size_t len); 29 | void uart_send_strn_cooked(const char *str, size_t len); 30 | 31 | 32 | #endif // UART_H 33 | -------------------------------------------------------------------------------- /button_boot.h: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the libopencm3 project. 3 | * 4 | * Copyright (C) 2016 Piotr Esden-Tempski 5 | * 6 | * This library is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This library is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with this library. If not, see . 18 | */ 19 | 20 | #ifndef COMMON_BUTTON_BOOT_H 21 | #define COMMON_BUTTON_BOOT_H 22 | 23 | /* This function sets up and checks the state of the user button. 24 | * If the user button is depressed the built in factory bootloader is launched. 25 | */ 26 | void button_boot(void); 27 | 28 | #endif /* COMMON_BUTTON_BOOT_H */ 29 | -------------------------------------------------------------------------------- /stm32f4-1bitsy.ld: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the libopencm3 project. 3 | * 4 | * Copyright (C) 2009 Uwe Hermann 5 | * Copyright (C) 2011 Stephen Caudle 6 | * 7 | * This library is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Lesser General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This library is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Lesser General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Lesser General Public License 18 | * along with this library. If not, see . 19 | */ 20 | 21 | /* Linker script for ST STM32F4DISCOVERY (STM32F415RGT6, 1024K flash, 128K RAM). */ 22 | 23 | /* Define memory regions. */ 24 | MEMORY 25 | { 26 | rom (rx) : ORIGIN = 0x08000000, LENGTH = 1024K 27 | ram (rwx) : ORIGIN = 0x20000000, LENGTH = 128K 28 | } 29 | 30 | /* Include the common ld script. */ 31 | INCLUDE libopencm3_stm32f4.ld 32 | 33 | -------------------------------------------------------------------------------- /stm32f4-discovery.ld: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the libopencm3 project. 3 | * 4 | * Copyright (C) 2009 Uwe Hermann 5 | * Copyright (C) 2011 Stephen Caudle 6 | * 7 | * This library is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU Lesser General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This library is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU Lesser General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU Lesser General Public License 18 | * along with this library. If not, see . 19 | */ 20 | 21 | /* Linker script for ST STM32F4DISCOVERY (STM32F407VG, 1024K flash, 128K RAM). */ 22 | 23 | /* Define memory regions. */ 24 | MEMORY 25 | { 26 | rom (rx) : ORIGIN = 0x08000000, LENGTH = 1024K 27 | ram (rwx) : ORIGIN = 0x20000000, LENGTH = 128K 28 | } 29 | 30 | /* Include the common ld script. */ 31 | INCLUDE libopencm3_stm32f4.ld 32 | 33 | -------------------------------------------------------------------------------- /usb.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Dave Hylands 3 | * 4 | * This library is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU Lesser General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This library is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public License 15 | * along with this library. If not, see . 16 | */ 17 | 18 | #ifndef USB_H 19 | #define USB_H 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | void usb_vcp_init(void); 26 | 27 | bool usb_vcp_is_connected(void); 28 | 29 | uint16_t usb_vcp_avail(void); 30 | int usb_vcp_recv_byte(void); 31 | void usb_vcp_send_byte(uint8_t ch); 32 | void usb_vcp_send_strn(const char *str, size_t len); 33 | void usb_vcp_send_strn_cooked(const char *str, size_t len); 34 | 35 | void usb_vcp_printf(const char *fmt, ...); 36 | 37 | #endif // USB_H 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | USB Serial example for libopencm3 2 | 3 | This started life as [usb_cdcacm](https://github.com/libopencm3/libopencm3-examples/tree/master/examples/stm32/f4/stm32f4-discovery/usb_cdcacm) 4 | but has been modularized a bit. 5 | 6 | Reading and writing via the usb serial now uses a circular buffer and has been 7 | made interrupt driven. 8 | 9 | ### Prerequisites 10 | 11 | - arm-none-eabi toolchain. Tested with the 4.9.3 version from [launchpad](https://launchpad.net/gcc-arm-embedded) 12 | - [stlink](https://github.com/texane/stlink) 13 | - python 2.7 (libopencm3's build uses this) 14 | 15 | ### Build 16 | 17 | ``` 18 | git clone https://github.com/dhylands/libopencm3-usb-serial usb-serial 19 | cd usb-serial 20 | make 21 | ``` 22 | 23 | By default, this builds for the 1BitSy. You can specify a board to build 24 | for the STM32F4 Discovery: 25 | ``` 26 | make BOARD=STM32F4DISC 27 | ``` 28 | 29 | ### Flash (for 1BitSy) 30 | 31 | To flash using the BlackMagic Probe: 32 | ``` 33 | make run 34 | ``` 35 | This will stop at main. Type 'c' to continue and it will run. You can remove 36 | the `break main` statement from gdbinit if you'd just like it to run all the time. 37 | 38 | ### Flash (for STM32F4 Discovery board) 39 | 40 | To flash using the STM32F4 builtin discovery STLINK flasher: 41 | ``` 42 | make BOARD=STM32F4DISC stlink 43 | ``` 44 | -------------------------------------------------------------------------------- /button_boot.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the libopencm3 project. 3 | * 4 | * Copyright (C) 2016 Piotr Esden-Tempski 5 | * 6 | * This library is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This library is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with this library. If not, see . 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | #include "button_boot.h" 25 | 26 | #define BLDR_ADDRESS 0x1FFF0000 27 | 28 | void button_boot(void) { 29 | // Enable GPIOC clock. 30 | rcc_periph_clock_enable(RCC_GPIOC); 31 | 32 | // Set GPIO1 (in GPIO port C) to 'input open-drain'. 33 | gpio_mode_setup(GPIOC, GPIO_MODE_INPUT, GPIO_PUPD_NONE, GPIO1); 34 | 35 | // Check if the user button is depressed, if so launch the factory bootloader 36 | if ((GPIOC_IDR & (1 << 1)) == 0) { 37 | // Set vector table base address. 38 | SCB_VTOR = BLDR_ADDRESS & 0xFFFF; 39 | // Initialise master stack pointer. 40 | asm volatile("msr msp, %0"::"g" 41 | (*(volatile uint32_t *)BLDR_ADDRESS)); 42 | // Jump to bootloader. 43 | (*(void (**)())(BLDR_ADDRESS + 4))(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /systick.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the libopencm3 project. 3 | * 4 | * Copyright (C) 2010 Gareth McMullin 5 | * 6 | * This library is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This library is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with this library. If not, see . 18 | */ 19 | 20 | #include "systick.h" 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | /* monotonically increasing number of milliseconds from reset 28 | * overflows every 49 days if you're wondering 29 | */ 30 | volatile uint32_t system_millis; 31 | 32 | /* Called when systick fires */ 33 | void sys_tick_handler(void) 34 | { 35 | system_millis++; 36 | } 37 | 38 | /* sleep for delay milliseconds */ 39 | void msleep(uint32_t delay) { 40 | 41 | uint32_t start = system_millis; 42 | 43 | // Wraparound of tick is taken care of by 2's complement arithmetic. 44 | while (system_millis - start < delay) { 45 | __WFI(); 46 | } 47 | } 48 | 49 | /* Set up a timer to create 1mS ticks. */ 50 | void systick_init(void) { 51 | /* clock rate / 1000 to get 1mS interrupt rate */ 52 | systick_set_reload(rcc_ahb_frequency / 1000); 53 | systick_set_clocksource(STK_CSR_CLKSOURCE_AHB); 54 | systick_counter_enable(); 55 | /* this done last */ 56 | systick_interrupt_enable(); 57 | } 58 | 59 | 60 | -------------------------------------------------------------------------------- /led.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Dave Hylands 3 | * 4 | * This library is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU Lesser General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This library is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public License 15 | * along with this library. If not, see . 16 | */ 17 | 18 | #include "led.h" 19 | 20 | #include 21 | #include 22 | 23 | static const struct { 24 | uint32_t gpioport; 25 | uint16_t gpios; 26 | uint8_t on_value; 27 | } led[] = { 28 | #if defined(BOARD_1BITSY) 29 | { GPIOA, GPIO8, 0 }, 30 | #elif defined(BOARD_STM32F4DISC) 31 | { GPIOD, GPIO12, 1 }, 32 | { GPIOD, GPIO13, 1 }, 33 | { GPIOD, GPIO14, 1 }, 34 | { GPIOD, GPIO15, 1 }, 35 | #else 36 | #error Unrecognized BOARD 37 | #endif 38 | }; 39 | #define NUM_LEDS (sizeof(led) / sizeof(led[0])) 40 | 41 | void led_init(void) 42 | { 43 | for (unsigned i = 0; i < NUM_LEDS; i++) { 44 | uint32_t port = led[i].gpioport; 45 | rcc_periph_clock_enable(RCC_GPIOA + ((port - GPIOA) / (GPIOB - GPIOA))); 46 | gpio_mode_setup(port, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, led[i].gpios); 47 | led_off(i); 48 | } 49 | } 50 | 51 | void led_on(unsigned led_num) { 52 | if (led_num < NUM_LEDS) { 53 | if (led[led_num].on_value) { 54 | gpio_set(led[led_num].gpioport, led[led_num].gpios); 55 | } else { 56 | gpio_clear(led[led_num].gpioport, led[led_num].gpios); 57 | } 58 | } 59 | } 60 | 61 | void led_off(unsigned led_num) { 62 | if (led_num < NUM_LEDS) { 63 | if (led[led_num].on_value) { 64 | gpio_clear(led[led_num].gpioport, led[led_num].gpios); 65 | } else { 66 | gpio_set(led[led_num].gpioport, led[led_num].gpios); 67 | } 68 | } 69 | } 70 | 71 | void led_toggle(unsigned led_num) { 72 | if (led_num < NUM_LEDS) { 73 | gpio_toggle(led[led_num].gpioport, led[led_num].gpios); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /uart.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Dave Hylands 3 | * 4 | * This library is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU Lesser General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This library is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public License 15 | * along with this library. If not, see . 16 | */ 17 | 18 | #include "uart.h" 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include "StrPrintf.h" 27 | 28 | void uart_init(void) 29 | { 30 | rcc_periph_clock_enable(RCC_GPIOA); 31 | rcc_periph_clock_enable(RCC_USART2); 32 | 33 | /* Setup USART2 parameters. */ 34 | usart_set_baudrate(USART2, 115200); 35 | usart_set_databits(USART2, 8); 36 | usart_set_stopbits(USART2, USART_STOPBITS_1); 37 | usart_set_mode(USART2, USART_MODE_TX); 38 | usart_set_parity(USART2, USART_PARITY_NONE); 39 | usart_set_flow_control(USART2, USART_FLOWCONTROL_NONE); 40 | 41 | /* Finally enable the USART. */ 42 | usart_enable(USART2); 43 | 44 | // Setup USART2 Tx on A2 45 | gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO2); 46 | gpio_set_af(GPIOA, GPIO_AF7, GPIO2); 47 | } 48 | 49 | static int uart_putc(void *out_param, int ch) { 50 | (void)out_param; 51 | if (ch == '\n') { 52 | usart_send_blocking(USART2, '\r'); 53 | } 54 | usart_send_blocking(USART2, ch); 55 | return 1; 56 | } 57 | 58 | void uart_printf(const char *fmt, ...) { 59 | va_list args; 60 | va_start(args, fmt); 61 | vStrXPrintf(uart_putc, NULL, fmt, args); 62 | va_end(args); 63 | } 64 | 65 | void uart_send_byte(uint8_t ch) { 66 | usart_send_blocking(USART2, ch); 67 | } 68 | 69 | void uart_send_strn(const char *str, size_t len) { 70 | for (const char *end = str + len; str < end; str++) { 71 | uart_send_byte(*str); 72 | } 73 | } 74 | 75 | void uart_send_strn_cooked(const char *str, size_t len) { 76 | for (const char *end = str + len; str < end; str++) { 77 | if (*str == '\n') { 78 | uart_send_byte('\r'); 79 | } 80 | uart_send_byte(*str); 81 | } 82 | } 83 | 84 | -------------------------------------------------------------------------------- /usb-serial.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Dave Hylands 3 | * 4 | * This library is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU Lesser General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This library is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public License 15 | * along with this library. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | 21 | #include "button_boot.h" 22 | #include "led.h" 23 | #include "systick.h" 24 | #include "uart.h" 25 | #include "usb.h" 26 | 27 | int main(void) 28 | { 29 | #if defined(BOARD_1BITSY) 30 | // button_boot checks to see if the USER button is pushed during powerup 31 | // and if so, reboots into DFU mode. 32 | button_boot(); 33 | rcc_clock_setup_hse_3v3(&rcc_hse_25mhz_3v3[RCC_CLOCK_3V3_168MHZ]); 34 | #elif defined(BOARD_STM32F4DISC) 35 | rcc_clock_setup_hse_3v3(&rcc_hse_8mhz_3v3[RCC_CLOCK_3V3_168MHZ]); 36 | #else 37 | #error Unrecognized BOARD 38 | #endif 39 | 40 | led_init(); 41 | systick_init(); 42 | uart_init(); 43 | usb_vcp_init(); 44 | 45 | uart_printf("\n*****\n"); 46 | uart_printf("***** Starting (UART) ...\n"); 47 | uart_printf("*****\n"); 48 | 49 | usb_vcp_printf("\n*****\n"); 50 | usb_vcp_printf("***** Starting (USB) ...\n"); 51 | usb_vcp_printf("*****\n"); 52 | 53 | 54 | uint32_t last_millis = system_millis; 55 | uint32_t blink = 0; 56 | 57 | while (1) { 58 | 59 | char buf[128]; 60 | size_t len = 0; 61 | while (1) { 62 | if (len >= sizeof(buf)) { 63 | break; 64 | } 65 | if (usb_vcp_avail()) { 66 | char ch = usb_vcp_recv_byte(); 67 | usb_vcp_send_byte(ch); 68 | if (ch == '\r') { 69 | usb_vcp_send_byte('\n'); 70 | } 71 | if (ch == '\r' || ch == '\n') { 72 | break; 73 | } 74 | buf[len++] = ch; 75 | } 76 | 77 | if (system_millis - last_millis > 100) { 78 | if (blink <= 3) { 79 | led_toggle(0); 80 | } 81 | blink = (blink + 1) % 10; 82 | last_millis = system_millis; 83 | } 84 | __WFI(); 85 | } 86 | uart_send_strn("Line: ", 6); 87 | uart_send_strn(buf, len); 88 | uart_send_strn("\r\n", 2); 89 | 90 | usb_vcp_send_strn("Line: ", 6); 91 | usb_vcp_send_strn(buf, len); 92 | usb_vcp_send_strn("\r\n", 2); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | BOARD ?= 1bitsy 2 | #BOARD ?= discovery 3 | $(info BOARD = $(BOARD)) 4 | 5 | TARGET ?= usb-serial 6 | FLASH_ADDR ?= 0x8000000 7 | 8 | # Turn on increased build verbosity by defining BUILD_VERBOSE in your main 9 | # Makefile or in your environment. You can also use V=1 on the make command 10 | # line. 11 | 12 | ifeq ("$(origin V)", "command line") 13 | BUILD_VERBOSE=$(V) 14 | endif 15 | ifndef BUILD_VERBOSE 16 | BUILD_VERBOSE = 0 17 | endif 18 | ifeq ($(BUILD_VERBOSE),0) 19 | Q = @ 20 | else 21 | Q = 22 | endif 23 | # Since this is a new feature, advertise it 24 | ifeq ($(BUILD_VERBOSE),0) 25 | $(info Use make V=1 or set BUILD_VERBOSE in your environment to increase build verbosity.) 26 | endif 27 | 28 | BUILD ?= build-$(BOARD) 29 | 30 | RM = rm 31 | ECHO = @echo 32 | 33 | CROSS_COMPILE = arm-none-eabi- 34 | 35 | AS = $(CROSS_COMPILE)as 36 | CC = $(CROSS_COMPILE)gcc 37 | LD = $(CROSS_COMPILE)ld 38 | GDB = $(CROSS_COMPILE)gdb 39 | OBJCOPY = $(CROSS_COMPILE)objcopy 40 | SIZE = $(CROSS_COMPILE)size 41 | 42 | LIBOPENCM3_DIR = libopencm3 43 | LIBOPENCM3_LIBDIR = $(LIBOPENCM3_DIR)/lib 44 | LIBOPENCM3_LIBNAME = opencm3_stm32f4 45 | LIBOPENCM3_LIBNAME_FULL = $(LIBOPENCM3_LIBDIR)/lib$(LIBOPENCM3_LIBNAME).a 46 | 47 | INC = -I. 48 | INC += -I$(LIBOPENCM3_DIR)/include 49 | 50 | CFLAGS_CORTEX_M4 = -mthumb -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -fsingle-precision-constant -Wdouble-promotion -Werror 51 | 52 | CFLAGS = -DSTM32F4 $(INC) 53 | CFLAGS += -Wextra -Wshadow -Wredundant-decls -Wall -Wmissing-prototypes -Wstrict-prototypes 54 | CFLAGS += -ansi -std=gnu99 -nostdlib $(CFLAGS_CORTEX_M4) $(COPT) 55 | 56 | CFLAGS_1bitsy = -DBOARD_1BITSY 57 | CFLAGS_discovery = -DBOARD_STM32F4DISC 58 | 59 | LDSCRIPT_1bitsy = stm32f4-1bitsy.ld 60 | LDSCRIPT_discovery = stm32f4-discovery.ld 61 | 62 | OBJ_1bitsy = $(BUILD)/button_boot.o 63 | OBJ_discovery = 64 | 65 | CFLAGS += $(CFLAGS_$(BOARD)) 66 | 67 | #Debugging/Optimization 68 | ifeq ($(DEBUG), 1) 69 | CFLAGS += -g 70 | COPT = -O0 71 | else 72 | COPT += -Os -DNDEBUG 73 | endif 74 | 75 | LDFLAGS = --static -nostartfiles -T $(LDSCRIPT_$(BOARD)) -Wl,-Map=$(@:.elf=.map),--cref 76 | 77 | LIBS = -L$(LIBOPENCM3_LIBDIR) -l$(LIBOPENCM3_LIBNAME) 78 | 79 | OBJ = $(BUILD)/$(TARGET).o \ 80 | $(BUILD)/led.o \ 81 | $(BUILD)/systick.o \ 82 | $(BUILD)/uart.o \ 83 | $(BUILD)/usb.o \ 84 | $(BUILD)/StrPrintf.o \ 85 | $(OBJ_$(BOARD)) 86 | 87 | all: $(BUILD)/$(TARGET).elf 88 | 89 | define compile_c 90 | $(ECHO) "CC $<" 91 | $(Q)$(CC) $(CFLAGS) -c -MD -o $@ $< 92 | @# The following fixes the dependency file. 93 | @# See http://make.paulandlesley.org/autodep.html for details. 94 | @cp $(@:.o=.d) $(@:.o=.P); \ 95 | sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \ 96 | -e '/^$$/ d' -e 's/$$/ :/' < $(@:.o=.d) >> $(@:.o=.P); \ 97 | rm -f $(@:.o=.d) 98 | endef 99 | 100 | $(OBJ): | $(BUILD) 101 | $(BUILD): 102 | mkdir -p $@ 103 | 104 | $(BUILD)/%.o: %.c 105 | $(call compile_c) 106 | 107 | pgm: $(BUILD)/$(TARGET).dfu 108 | ifeq ($(USE_PYDFU),1) 109 | $(Q)./pydfu.py -u $^ 110 | else 111 | $(Q)dfu-util -a 0 -D $^ -s:leave 112 | endif 113 | 114 | $(BUILD)/$(TARGET).bin: $(BUILD)/$(TARGET).elf 115 | $(OBJCOPY) -O binary $^ $@ 116 | 117 | $(BUILD)/$(TARGET).dfu: $(BUILD)/$(TARGET).bin 118 | $(Q)./dfu.py -b $(FLASH_ADDR):$^ $@ 119 | 120 | $(LIBOPENCM3_LIBNAME_FULL): 121 | git submodule update --init 122 | make -C $(LIBOPENCM3_DIR) TARGETS=stm32/f4 123 | 124 | # Building the library generates a bunch of header files, so make each object 125 | # depend on the library to ensure that the headers gets built. 126 | $(OBJ): $(LIBOPENCM3_LIBNAME_FULL) 127 | 128 | $(BUILD)/$(TARGET).elf: $(OBJ) 129 | $(ECHO) "LINK $@" 130 | $(Q)$(CC) $(CFLAGS_CORTEX_M4) $(LDFLAGS) -o $@ $(OBJ) $(LIBS) 131 | $(Q)$(SIZE) $@ 132 | 133 | stlink: $(BUILD)/$(TARGET).bin 134 | $(Q)st-flash --reset write $^ $(FLASH_ADDR) 135 | 136 | uart: $(BUILD)/$(TARGET).bin 137 | $(Q)./stm32loader.py -p /dev/ttyUSB0 -evw $^ 138 | 139 | run: $(BUILD)/$(TARGET).elf 140 | $(GDB) -ex 'target extended-remote /dev/ttyACM0' -x gdbinit $< 141 | 142 | # Unprotect does a MASS erase, so it shouldn't try to flash as well. 143 | # And on the STM32F103, the ACK never gets received 144 | uart-unprotect: 145 | $(Q)./stm32loader.py -p /dev/ttyUSB0 -uV 146 | 147 | clean: 148 | $(RM) -rf $(BUILD) 149 | .PHONY: clean 150 | 151 | -include $(OBJ:.o=.P) 152 | -------------------------------------------------------------------------------- /CBUF.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * 3 | * Since this code originated from code which is public domain, I 4 | * hereby declare this code to be public domain as well. 5 | * 6 | * Dave Hylands - dhylands@gmail.com 7 | * 8 | ****************************************************************************/ 9 | /** 10 | * 11 | * @file CBUF.h 12 | * 13 | * @defgroup CBUF Circular Buffer 14 | * @{ 15 | * 16 | * @brief A simple and efficient set of circular buffer manipulations. 17 | * 18 | * These macros implement a circular buffer which employs get and put 19 | * pointers, in such a way that mutual exclusion is not required 20 | * (assumes one reader & one writer). 21 | * 22 | * It requires that the circular buffer size be a power of two, and the 23 | * size of the buffer needs to smaller than the index. So an 8 bit index 24 | * supports a circular buffer upto (1 << 7) = 128 entries, and a 16 bit index 25 | * supports a circular buffer upto (1 << 15) = 32768 entries. 26 | * 27 | * The basis for these routines came from an article in Jack Ganssle's 28 | * Embedded Muse: http://www.ganssle.com/tem/tem110.pdf 29 | * 30 | * The structure which defines the circular buffer needs to have 3 members 31 | * m_get_idx, m_put_idx, and @c m_entry, and m_entry needs to be 32 | * an array of elements rather than a pointer to an array of elements. 33 | * 34 | * @c m_get_idx and @c m_put_idx need to be unsigned integers of the same size. 35 | * 36 | * @c m_entry needs to be an array of entries. The type of each entry is 37 | * entirely up to the caller. 38 | * 39 | * @code 40 | * struct 41 | * { 42 | * volatile uint8_t m_get_idx; 43 | * volatile uint8_t m_put_idx; 44 | * uint8_t m_entry[ 64 ]; 45 | * 46 | * } myQ; 47 | * @endcode 48 | * 49 | * You could then use CBUF_Push to add a character to the circular buffer: 50 | * 51 | * @code 52 | * CBUF_Push(myQ, 'x'); 53 | * @endcode 54 | * 55 | * And CBUF_Pop to retrieve an element from the buffer: 56 | * 57 | * @code 58 | * ch = CBUF_Pop(myQ); 59 | * @endcode 60 | * 61 | ****************************************************************************/ 62 | 63 | #if !defined(CBUF_H) 64 | #define CBUF_H 65 | 66 | /* ---- Include Files ---------------------------------------------------- */ 67 | 68 | /* ---- Constants and Types ---------------------------------------------- */ 69 | 70 | /** 71 | * Initializes the circular buffer for use. 72 | */ 73 | 74 | #define CBUF_Init(cbuf) cbuf.m_get_idx = cbuf.m_put_idx = 0 75 | 76 | /** 77 | * Returns the number of elements which are currently 78 | * contained in the circular buffer. 79 | */ 80 | 81 | #define CBUF_Len(cbuf) ((typeof(cbuf.m_put_idx))((cbuf.m_put_idx) - (cbuf.m_get_idx))) 82 | 83 | /** 84 | * Returns the size of the buffer (in entries) 85 | */ 86 | #define CBUF_Size(cbuf) (sizeof(cbuf.m_entry) / sizeof(cbuf.m_entry[0])) 87 | 88 | /** 89 | * Returns the number of unused entries which are currently in 90 | * the buffer. 91 | */ 92 | #define CBUF_Space(cbuf) (CBUF_Size(cbuf) - CBUF_Len(cbuf)) 93 | 94 | /** 95 | * Determines the mask used to extract the real get & put 96 | * pointers. 97 | */ 98 | #define CBUF_Mask(cbuf) (CBUF_Size(cbuf) - 1) 99 | 100 | /** 101 | * Determines if the get and put pointers are "wrapped". 102 | */ 103 | #define CBUF_Wrapped(cbuf) (((cbuf.m_put_idx ^ cbuf.m_get_idx) & ~CBUF_Mask(cbuf)) != 0) 104 | 105 | /** 106 | * Returns the number of contiguous entries which can be 107 | * retrieved from the buffer. 108 | */ 109 | #define CBUF_ContigLen(cbuf) (CBUF_Wrapped(cbuf) ? (CBUF_Size(cbuf) - (cbuf.m_get_idx & CBUF_Mask(cbuf))) : CBUF_Len(cbuf)) 110 | 111 | /** 112 | * Returns the number of contiguous entries which can be placed 113 | * into the buffer. 114 | */ 115 | #define CBUF_ContigSpace(cbuf) (CBUF_Wrapped(cbuf) ? CBUF_Space(cbuf) : (CBUF_Size(cbuf) - (cbuf.m_put_idx & CBUF_Mask(cbuf)))) 116 | 117 | /** 118 | * Appends an element to the end of the circular buffer. The 119 | * element is expected to be of the same type as the @c m_entry 120 | * member. 121 | */ 122 | 123 | #define CBUF_Push(cbuf, elem) do { \ 124 | (cbuf.m_entry)[cbuf.m_put_idx & CBUF_Mask(cbuf)] = (elem); \ 125 | cbuf.m_put_idx++; \ 126 | } while (0) 127 | 128 | /** 129 | * Retrieves an element from the beginning of the circular buffer 130 | */ 131 | 132 | #define CBUF_Pop(cbuf) ({ \ 133 | __typeof__(cbuf.m_entry[0]) _elem = (cbuf.m_entry)[cbuf.m_get_idx & CBUF_Mask(cbuf)]; \ 134 | cbuf.m_get_idx++; \ 135 | _elem; }) 136 | 137 | /** 138 | * Returns a pointer to the last spot that was pushed. 139 | */ 140 | 141 | #define CBUF_GetLastEntryPtr(cbuf) &(cbuf.m_entry)[ (cbuf.m_put_idx - 1) & CBUF_Mask(cbuf)] 142 | 143 | /** 144 | * Returns a pointer to the next spot to push. This can be used 145 | * in conjunction with CBUF_AdvancePushIdx to fill out an entry 146 | * before indicating that it's available. It is the caller's 147 | * responsibility to enure that space is available, and that no 148 | * other items are pushed to overwrite the entry returned. 149 | */ 150 | 151 | #define CBUF_GetPushEntryPtr(cbuf) &(cbuf.m_entry)[ cbuf.m_put_idx & CBUF_Mask(cbuf)] 152 | 153 | /** 154 | * Advances the put index. This is useful if you need to 155 | * reserve space for an item but can't fill in the contents 156 | * yet. CBUG_GetLastEntryPtr can be used to get a pointer to 157 | * the item. It is the caller's responsibility to ensure that 158 | * the item isn't popped before the contents are filled in. 159 | */ 160 | 161 | #define CBUF_AdvancePushIdx(cbuf) cbuf.m_put_idx++ 162 | #define CBUF_AdvancePushIdxBy(cbuf, len) cbuf.m_put_idx += (len) 163 | 164 | /** 165 | * Advances the get index. This is slightly more efficient than 166 | * popping and tossing the result. 167 | */ 168 | 169 | #define CBUF_AdvancePopIdx(cbuf) cbuf.m_get_idx++ 170 | #define CBUF_AdvancePopIdxBy(cbuf, len) cbuf.m_get_idx += (len) 171 | 172 | /** 173 | * Retrieves the idx'th element from the beginning of 174 | * the circular buffer 175 | */ 176 | 177 | #define CBUF_Get(cbuf, idx) (cbuf.m_entry)[(cbuf.m_get_idx + idx) & CBUF_Mask(cbuf)] 178 | 179 | /** 180 | * Retrieves the idx'th element from the end of the 181 | * circular buffer. 182 | */ 183 | 184 | #define CBUF_GetEnd(cbuf, idx) (cbuf.m_entry)[(cbuf.m_put_idx - idx - 1) & CBUF_Mask(cbuf)] 185 | 186 | /** 187 | * Returns a pointer to the next spot to push. 188 | */ 189 | 190 | #define CBUF_GetPopEntryPtr(cbuf) &(cbuf.m_entry)[cbuf.m_get_idx & CBUF_Mask(cbuf)] 191 | 192 | /** 193 | * Determines if the circular buffer is empty. 194 | */ 195 | 196 | #define CBUF_IsEmpty(cbuf) (CBUF_Len(cbuf) == 0) 197 | 198 | /** 199 | * Determines if the circular buffer is full. 200 | */ 201 | 202 | #define CBUF_IsFull(cbuf) (CBUF_Space(cbuf) == 0) 203 | 204 | /** 205 | * Determines if the circular buffer is currenly overflowed or underflowed. 206 | */ 207 | 208 | #define CBUF_Error(cbuf) (CBUF_Len(cbuf) > CBUF_Size(cbuf)) 209 | 210 | /* ---- Variable Externs ------------------------------------------------- */ 211 | /* ---- Function Prototypes ---------------------------------------------- */ 212 | 213 | /** @} */ 214 | 215 | #endif // CBUF_H 216 | -------------------------------------------------------------------------------- /usb.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the libopencm3 project. 3 | * 4 | * Copyright (C) 2010 Gareth McMullin 5 | * 6 | * This library is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This library is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with this library. If not, see . 18 | */ 19 | /* 20 | * Significant parts of this originated from 21 | * libopencm3-examples/examples/stm32/f4/stm32f429i-discovery/usb_cdcacm 22 | * which is why I left the copyright notice above. 23 | */ 24 | 25 | #include "usb.h" 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include "CBUF.h" 35 | #include "StrPrintf.h" 36 | 37 | typedef struct { 38 | volatile uint16_t m_get_idx; 39 | volatile uint16_t m_put_idx; 40 | uint8_t m_entry[1024]; // Size must be a power of 2 41 | } buf_t; 42 | 43 | static buf_t usb_serial_rx_buf; 44 | static buf_t usb_serial_tx_buf; 45 | static bool usb_serial_need_empty_tx = false; 46 | 47 | static usbd_device *g_usbd_dev = NULL; 48 | static bool g_usbd_is_connected = false; 49 | 50 | static char usb_serial[13]; // 12 digits plus a null terminator 51 | 52 | // Use a scheme similar to MicroPython, but offset the PIDs by 0x100 53 | // VID: 0xf055 54 | // PID: 0x9900 CDC + MSC (which I have no plans on supporting) 55 | // 0x9901 CDC + HID 56 | // 0x9902 CDC only 57 | 58 | static const struct usb_device_descriptor dev = { 59 | .bLength = USB_DT_DEVICE_SIZE, 60 | .bDescriptorType = USB_DT_DEVICE, 61 | .bcdUSB = 0x0200, 62 | .bDeviceClass = USB_CLASS_CDC, 63 | .bDeviceSubClass = 0, 64 | .bDeviceProtocol = 0, 65 | .bMaxPacketSize0 = 64, 66 | .idVendor = 0xf055, // VID 67 | .idProduct = 0x9902, // PID 68 | .bcdDevice = 0x0200, // Version (2.00) 69 | .iManufacturer = 1, 70 | .iProduct = 2, 71 | .iSerialNumber = 3, 72 | .bNumConfigurations = 1, 73 | }; 74 | 75 | /* 76 | * This notification endpoint isn't implemented. According to CDC spec it's 77 | * optional, but its absence causes a NULL pointer dereference in the 78 | * Linux cdc_acm driver. 79 | */ 80 | static const struct usb_endpoint_descriptor comm_endp[] = {{ 81 | .bLength = USB_DT_ENDPOINT_SIZE, 82 | .bDescriptorType = USB_DT_ENDPOINT, 83 | .bEndpointAddress = 0x83, 84 | .bmAttributes = USB_ENDPOINT_ATTR_INTERRUPT, 85 | .wMaxPacketSize = 8, 86 | .bInterval = 32, 87 | } }; 88 | 89 | static const struct usb_endpoint_descriptor data_endp[] = {{ 90 | .bLength = USB_DT_ENDPOINT_SIZE, 91 | .bDescriptorType = USB_DT_ENDPOINT, 92 | .bEndpointAddress = 0x01, 93 | .bmAttributes = USB_ENDPOINT_ATTR_BULK, 94 | .wMaxPacketSize = 64, 95 | .bInterval = 0, 96 | }, { 97 | .bLength = USB_DT_ENDPOINT_SIZE, 98 | .bDescriptorType = USB_DT_ENDPOINT, 99 | .bEndpointAddress = 0x82, 100 | .bmAttributes = USB_ENDPOINT_ATTR_BULK, 101 | .wMaxPacketSize = 64, 102 | .bInterval = 0, 103 | } }; 104 | 105 | static const struct { 106 | struct usb_cdc_header_descriptor header; 107 | struct usb_cdc_call_management_descriptor call_mgmt; 108 | struct usb_cdc_acm_descriptor acm; 109 | struct usb_cdc_union_descriptor cdc_union; 110 | } __attribute__((packed)) cdcacm_functional_descriptors = { 111 | .header = { 112 | .bFunctionLength = sizeof(struct usb_cdc_header_descriptor), 113 | .bDescriptorType = CS_INTERFACE, 114 | .bDescriptorSubtype = USB_CDC_TYPE_HEADER, 115 | .bcdCDC = 0x0110, 116 | }, 117 | .call_mgmt = { 118 | .bFunctionLength = 119 | sizeof(struct usb_cdc_call_management_descriptor), 120 | .bDescriptorType = CS_INTERFACE, 121 | .bDescriptorSubtype = USB_CDC_TYPE_CALL_MANAGEMENT, 122 | .bmCapabilities = 0, 123 | .bDataInterface = 1, 124 | }, 125 | .acm = { 126 | .bFunctionLength = sizeof(struct usb_cdc_acm_descriptor), 127 | .bDescriptorType = CS_INTERFACE, 128 | .bDescriptorSubtype = USB_CDC_TYPE_ACM, 129 | .bmCapabilities = 0x2, 130 | }, 131 | .cdc_union = { 132 | .bFunctionLength = sizeof(struct usb_cdc_union_descriptor), 133 | .bDescriptorType = CS_INTERFACE, 134 | .bDescriptorSubtype = USB_CDC_TYPE_UNION, 135 | .bControlInterface = 0, 136 | .bSubordinateInterface0 = 1, 137 | } 138 | }; 139 | 140 | static const struct usb_interface_descriptor comm_iface[] = {{ 141 | .bLength = USB_DT_INTERFACE_SIZE, 142 | .bDescriptorType = USB_DT_INTERFACE, 143 | .bInterfaceNumber = 0, 144 | .bAlternateSetting = 0, 145 | .bNumEndpoints = 1, 146 | .bInterfaceClass = USB_CLASS_CDC, 147 | .bInterfaceSubClass = USB_CDC_SUBCLASS_ACM, 148 | .bInterfaceProtocol = USB_CDC_PROTOCOL_AT, 149 | .iInterface = 0, 150 | 151 | .endpoint = comm_endp, 152 | 153 | .extra = &cdcacm_functional_descriptors, 154 | .extralen = sizeof(cdcacm_functional_descriptors) 155 | } }; 156 | 157 | static const struct usb_interface_descriptor data_iface[] = {{ 158 | .bLength = USB_DT_INTERFACE_SIZE, 159 | .bDescriptorType = USB_DT_INTERFACE, 160 | .bInterfaceNumber = 1, 161 | .bAlternateSetting = 0, 162 | .bNumEndpoints = 2, 163 | .bInterfaceClass = USB_CLASS_DATA, 164 | .bInterfaceSubClass = 0, 165 | .bInterfaceProtocol = 0, 166 | .iInterface = 0, 167 | 168 | .endpoint = data_endp, 169 | } }; 170 | 171 | static const struct usb_interface ifaces[] = {{ 172 | .num_altsetting = 1, 173 | .altsetting = comm_iface, 174 | }, { 175 | .num_altsetting = 1, 176 | .altsetting = data_iface, 177 | } }; 178 | 179 | static const struct usb_config_descriptor config = { 180 | .bLength = USB_DT_CONFIGURATION_SIZE, 181 | .bDescriptorType = USB_DT_CONFIGURATION, 182 | .wTotalLength = 0, 183 | .bNumInterfaces = 2, 184 | .bConfigurationValue = 1, 185 | .iConfiguration = 0, 186 | .bmAttributes = 0x80, 187 | //.bMaxPower = 0x32, 188 | .bMaxPower = 250, // units of 2mA 189 | 190 | .interface = ifaces, 191 | }; 192 | 193 | static const char *usb_strings[] = { 194 | "Manufacturer", 195 | "STM32F4 CDC Demo", 196 | usb_serial, 197 | }; 198 | #define NUM_USB_STRINGS (sizeof(usb_strings) / sizeof(usb_strings[0])) 199 | 200 | static const struct usb_cdc_line_coding line_coding = { 201 | .dwDTERate = 115200, 202 | .bCharFormat = USB_CDC_1_STOP_BITS, 203 | .bParityType = USB_CDC_NO_PARITY, 204 | .bDataBits = 0x08 205 | }; 206 | 207 | /* Buffer to be used for control requests. */ 208 | uint8_t usbd_control_buffer[128]; 209 | 210 | #define USB_CDC_REQ_GET_LINE_CODING 0x21 // Not defined in libopencm3 211 | 212 | static int cdcacm_control_request(usbd_device *usbd_dev, 213 | struct usb_setup_data *req, uint8_t **buf, uint16_t *len, 214 | void (**complete)(usbd_device *usbd_dev, struct usb_setup_data *req)) 215 | { 216 | (void)complete; 217 | (void)buf; 218 | (void)usbd_dev; 219 | 220 | switch (req->bRequest) { 221 | 222 | case USB_CDC_REQ_SET_CONTROL_LINE_STATE: { // 0x22 223 | uint16_t rtsdtr = req->wValue; // DTR is bit 0, RTS is bit 1 224 | g_usbd_is_connected = rtsdtr & 1; 225 | return USBD_REQ_HANDLED; 226 | } 227 | 228 | case USB_CDC_REQ_SET_LINE_CODING: // 0x20 229 | if (*len < sizeof(struct usb_cdc_line_coding)) { 230 | return 0; 231 | } 232 | return USBD_REQ_HANDLED; 233 | 234 | case USB_CDC_REQ_GET_LINE_CODING: 235 | *buf = (uint8_t *)&line_coding; 236 | return USBD_REQ_HANDLED; 237 | } 238 | return USBD_REQ_HANDLED; 239 | } 240 | 241 | static void cdcacm_data_rx_cb(usbd_device *usbd_dev, uint8_t ep) 242 | { 243 | uint16_t space = CBUF_ContigSpace(usb_serial_rx_buf); 244 | uint16_t len; 245 | if (space >= 64) { 246 | // We can read directly into our buffer 247 | len = usbd_ep_read_packet(usbd_dev, ep, 248 | CBUF_GetPushEntryPtr(usb_serial_rx_buf), 64); 249 | CBUF_AdvancePushIdxBy(usb_serial_rx_buf, len); 250 | } else { 251 | // Do it character by character. This covers 2 situations: 252 | // 1 - We're near the end of the buffer (so free space isn't contiguous) 253 | // 2 - We don't have much free space left. 254 | char buf[64]; 255 | len = usbd_ep_read_packet(usbd_dev, ep, buf, 64); 256 | for (int i = 0; i < len; i++) { 257 | // If the Rx buffer fills, then we drop the new data. 258 | if (CBUF_IsFull(usb_serial_rx_buf)) { 259 | return; 260 | } 261 | CBUF_Push(usb_serial_rx_buf, buf[i]); 262 | } 263 | } 264 | } 265 | 266 | static void cdcacm_sof_callback(void) { 267 | if (!g_usbd_is_connected) { 268 | // Host isn't connected - nothing to do. 269 | return; 270 | } 271 | 272 | uint16_t len = CBUF_ContigLen(usb_serial_tx_buf); 273 | if (len == 0 && !usb_serial_need_empty_tx) { 274 | // Nothing to do. 275 | return; 276 | } 277 | if (len > 64) { 278 | len = 64; 279 | } 280 | uint8_t *pop_ptr = CBUF_GetPopEntryPtr(usb_serial_tx_buf); 281 | uint16_t sent = usbd_ep_write_packet(g_usbd_dev, 0x82, pop_ptr, len); 282 | 283 | // If we just sent a packet of 64 bytes. If we get called again and 284 | // there is no more data to send, then we need to send a zero byte 285 | // packet to indicate to the host to release the data it has buffered. 286 | usb_serial_need_empty_tx = (sent == 64); 287 | CBUF_AdvancePopIdxBy(usb_serial_tx_buf, sent); 288 | } 289 | 290 | void otg_fs_isr(void) 291 | { 292 | if (g_usbd_dev) { 293 | usbd_poll(g_usbd_dev); 294 | } 295 | } 296 | 297 | static void cdcacm_set_config(usbd_device *usbd_dev, uint16_t wValue) 298 | { 299 | (void)wValue; 300 | 301 | usbd_ep_setup(usbd_dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, 302 | cdcacm_data_rx_cb); 303 | usbd_ep_setup(usbd_dev, 0x82, USB_ENDPOINT_ATTR_BULK, 64, NULL); 304 | usbd_ep_setup(usbd_dev, 0x83, USB_ENDPOINT_ATTR_INTERRUPT, 16, NULL); 305 | 306 | usbd_register_control_callback( 307 | usbd_dev, 308 | USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE, 309 | USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT, 310 | cdcacm_control_request); 311 | } 312 | 313 | bool usb_vcp_is_connected(void) { 314 | return g_usbd_is_connected; 315 | } 316 | 317 | uint16_t usb_vcp_avail(void) { 318 | return CBUF_Len(usb_serial_rx_buf); 319 | } 320 | 321 | int usb_vcp_recv_byte(void) { 322 | if (CBUF_IsEmpty(usb_serial_rx_buf)) { 323 | return -1; 324 | } 325 | return CBUF_Pop(usb_serial_rx_buf); 326 | } 327 | 328 | void usb_vcp_send_byte(uint8_t ch) { 329 | if (!CBUF_IsFull(usb_serial_tx_buf)) { 330 | CBUF_Push(usb_serial_tx_buf, ch); 331 | } 332 | } 333 | 334 | void usb_vcp_send_strn(const char *str, size_t len) { 335 | for (const char *end = str + len; str < end; str++) { 336 | usb_vcp_send_byte(*str); 337 | } 338 | } 339 | 340 | void usb_vcp_send_strn_cooked(const char *str, size_t len) { 341 | for (const char *end = str + len; str < end; str++) { 342 | if (*str == '\n') { 343 | usb_vcp_send_byte('\r'); 344 | } 345 | usb_vcp_send_byte(*str); 346 | } 347 | } 348 | 349 | static int usb_putc(void *out_param, int ch) { 350 | (void)out_param; 351 | if (ch == '\n') { 352 | usb_vcp_send_byte('\r'); 353 | } 354 | usb_vcp_send_byte(ch); 355 | return 1; 356 | } 357 | 358 | void usb_vcp_printf(const char *fmt, ...) { 359 | va_list args; 360 | va_start(args, fmt); 361 | vStrXPrintf(usb_putc, NULL, fmt, args); 362 | va_end(args); 363 | } 364 | 365 | static void fill_usb_serial(void) { 366 | // This document: http://www.usb.org/developers/docs/devclass_docs/usbmassbulk_10.pdf 367 | // says that the serial number has to be at least 12 digits long and that 368 | // the last 12 digits need to be unique. It also stipulates that the valid 369 | // character set is that of upper-case hexadecimal digits. 370 | // 371 | // The onboard DFU bootloader produces a 12-digit serial number based on 372 | // the 96-bit unique ID, so for consistency we go with this algorithm. 373 | // You can see the serial number if you do: 374 | // 375 | // dfu-util -l 376 | // 377 | // See: https://my.st.com/52d187b7 for the algorithim used. 378 | 379 | uint8_t *id = (uint8_t *)DESIG_UNIQUE_ID_BASE; 380 | 381 | uint8_t serial[6]; 382 | serial[0] = id[11]; 383 | serial[1] = id[10] + id[2]; 384 | serial[2] = id[9]; 385 | serial[3] = id[8] + id[0]; 386 | serial[4] = id[7]; 387 | serial[5] = id[6]; 388 | 389 | uint8_t *ser = &serial[0]; 390 | uint8_t *end = &serial[6]; 391 | char *ser_str = usb_serial; 392 | const char hex_digit[] = "0123456789ABCDEF"; 393 | 394 | for (; ser < end; ser++) { 395 | *ser_str++ = hex_digit[(*ser >> 4) & 0x0f]; 396 | *ser_str++ = hex_digit[(*ser >> 0) & 0x0f]; 397 | } 398 | *ser_str = '\0'; 399 | } 400 | 401 | void usb_vcp_init(void) { 402 | rcc_periph_clock_enable(RCC_GPIOA); 403 | rcc_periph_clock_enable(RCC_OTGFS); 404 | 405 | // A9 - USB VBUS (used to detect cable plugged in) 406 | // A10 - USB_ID (not currently used) 407 | // A11 - USB D- 408 | // A12 - USB D+ 409 | 410 | gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, 411 | GPIO9 | GPIO11 | GPIO12); 412 | gpio_set_af(GPIOA, GPIO_AF10, GPIO9 | GPIO11 | GPIO12); 413 | 414 | fill_usb_serial(); 415 | 416 | g_usbd_dev = usbd_init(&otgfs_usb_driver, &dev, &config, 417 | usb_strings, NUM_USB_STRINGS, 418 | usbd_control_buffer, sizeof(usbd_control_buffer)); 419 | 420 | usbd_register_set_config_callback(g_usbd_dev, cdcacm_set_config); 421 | usbd_register_sof_callback(g_usbd_dev, cdcacm_sof_callback); 422 | 423 | nvic_enable_irq(NVIC_OTG_FS_IRQ); 424 | } 425 | -------------------------------------------------------------------------------- /StrPrintf.c: -------------------------------------------------------------------------------- 1 | /**************************************************************************** 2 | * 3 | * Since this code originated from code which is public domain, I 4 | * hereby declare this code to be public domain as well. 5 | * 6 | * Dave Hylands - dhylands@gmail.com 7 | * 8 | ****************************************************************************/ 9 | /** 10 | * 11 | * @file StrPrintf.cpp 12 | * 13 | * @brief Implementation of a re-entrant printf function. 14 | * 15 | * Implements a reentrant version of the printf function. Also allows a 16 | * function pointer to be provided to perform the actual output. 17 | * 18 | * This version of printf was taken from 19 | * 20 | * http://www.efgh.com/software/gprintf.htm 21 | * 22 | * This software was posted by the author as being in the "public" domain. 23 | * I've taken the original gprintf.txt and made some minor revisions. 24 | * 25 | ****************************************************************************/ 26 | 27 | /** 28 | * @defgroup StrPrintf String Formatting 29 | * @ingroup Str 30 | */ 31 | /** 32 | * @defgroup StrPrintfInternal String Formatting Internals 33 | * @ingroup StrPrintf 34 | */ 35 | 36 | /* ---- Include Files ---------------------------------------------------- */ 37 | 38 | #include "StrPrintf.h" 39 | #include 40 | #include 41 | 42 | #if defined( AVR ) 43 | 44 | #undef StrPrintf 45 | #undef vStrPrintf 46 | 47 | #undef StrXPrintf 48 | #undef vStrXPrintf 49 | 50 | #define StrPrintf StrPrintf_P 51 | #define vStrPrintf vStrPrintf_P 52 | 53 | #define StrXPrintf StrXPrintf_P 54 | #define vStrXPrintf vStrXPrintf_P 55 | 56 | #else 57 | 58 | #define pgm_read_byte( addr ) *addr 59 | 60 | #endif 61 | 62 | /* ---- Public Variables ------------------------------------------------- */ 63 | /* ---- Private Constants and Types -------------------------------------- */ 64 | 65 | /** 66 | * @addtogroup StrPrintfInternal 67 | * @{ 68 | */ 69 | 70 | /** 71 | * Controls a variety of output options. 72 | */ 73 | 74 | typedef enum 75 | { 76 | NO_OPTION = 0x00, /**< No options specified. */ 77 | MINUS_SIGN = 0x01, /**< Should we print a minus sign? */ 78 | RIGHT_JUSTIFY = 0x02, /**< Should field be right justified? */ 79 | ZERO_PAD = 0x04, /**< Should field be zero padded? */ 80 | CAPITAL_HEX = 0x08 /**< Did we encounter %X? */ 81 | } FmtOption; 82 | 83 | /** @def IsOptionSet( p, x ) Determines if an option has been set. */ 84 | /** @def IsOptionClear( p, x ) Determines if an option is not set. */ 85 | /** @def SetOption( p, x ) Sets an option. */ 86 | /** @def ClearOption( p, x ) Unsets an option. */ 87 | 88 | #define IsOptionSet( p, x ) (( (p)->options & (x)) != 0 ) 89 | #define IsOptionClear( p, x ) (( (p)->options & (x)) == 0 ) 90 | #define SetOption( p, x ) (p)->options = (FmtOption)((p)->options | (x)) 91 | #define ClearOption( p, x ) (p)->options = (FmtOption)((p)->options & ~(x)) 92 | 93 | /** 94 | * Internal structure which is used to allow vStrXPrintf() to be reentrant. 95 | */ 96 | 97 | typedef struct 98 | { 99 | /** Number of characters output so far. */ 100 | int numOutputChars; 101 | 102 | /** Options determined from parsing format specification. */ 103 | FmtOption options; 104 | 105 | /** Minimum number of characters to output. */ 106 | short minFieldWidth; 107 | 108 | /** The exact number of characters to output. */ 109 | short editedStringLen; 110 | 111 | /** The number of leading zeros to output. */ 112 | short leadingZeros; 113 | 114 | /** The function to call to perform the actual output. */ 115 | StrXPrintfFunc outFunc; 116 | 117 | /** Parameter to pass to the output function. */ 118 | void *outParm; 119 | 120 | } Parameters; 121 | 122 | /** 123 | * Internal structure used by vStrPrintf() . 124 | */ 125 | typedef struct 126 | { 127 | char *str; /**< Buffer to store results into. */ 128 | int maxLen; /**< Maximum number of characters which can be stored. */ 129 | 130 | } StrPrintfParms; 131 | 132 | /* ---- Private Variables ------------------------------------------------ */ 133 | /* ---- Private Function Prototypes -------------------------------------- */ 134 | 135 | static void OutputChar(Parameters * p, int c); 136 | static void OutputField(Parameters * p, char *s); 137 | static int StrPrintfFunc(void *outParm, int ch); 138 | 139 | /** @} */ 140 | 141 | /* ---- Functions -------------------------------------------------------- */ 142 | 143 | /** 144 | * @addtogroup StrPrintf 145 | * @{ 146 | */ 147 | 148 | /***************************************************************************/ 149 | /** 150 | * Writes formatted data into a user supplied buffer. 151 | * 152 | * @param outStr (out) Place to store the formatted string. 153 | * @param maxLen (in) Max number of characters to write into @a outStr. 154 | * @param fmt (in) Format string (see vStrXPrintf() for sull details). 155 | */ 156 | 157 | int 158 | StrPrintf(char *outStr, int maxLen, const char *fmt, ...) 159 | { 160 | int rc; 161 | va_list args; 162 | 163 | va_start(args, fmt); 164 | rc = vStrPrintf(outStr, maxLen, fmt, args); 165 | va_end(args); 166 | 167 | return rc; 168 | 169 | } // StrPrintf 170 | 171 | /***************************************************************************/ 172 | /** 173 | * Generic printf function which writes formatted data by calling a user 174 | * supplied function. 175 | * 176 | * @a outFunc will be called to output each character. If @a outFunc returns 177 | * a number >= 0, then StrXPrintf will continue to call @a outFunc with 178 | * additional characters. 179 | * 180 | * If @a outFunc returns a negative number, then StrXPrintf will stop 181 | * calling @a outFunc and will return the non-negative return value. 182 | * 183 | * @param outFunc (in) Pointer to function to call to do the actual output. 184 | * @param outParm (in) Passed to @a outFunc. 185 | * @param fmt (in) Format string (see vStrXPrintf() for sull details). 186 | * 187 | */ 188 | 189 | int 190 | StrXPrintf(StrXPrintfFunc outFunc, void *outParm, const char *fmt, ...) 191 | { 192 | int rc; 193 | va_list args; 194 | 195 | va_start(args, fmt); 196 | rc = vStrXPrintf(outFunc, outParm, fmt, args); 197 | va_end(args); 198 | 199 | return rc; 200 | 201 | } // StrxPrintf 202 | 203 | /***************************************************************************/ 204 | /** 205 | * Writes formatted data into a user supplied buffer. 206 | * 207 | * @param outStr (out) Place to store the formatted string. 208 | * @param maxLen (in) Max number of characters to write into @a outStr. 209 | * @param fmt (in) Format string (see vStrXPrintf() for sull details). 210 | * @param args (in) Arguments in a format compatible with va_arg(). 211 | */ 212 | 213 | int 214 | vStrPrintf(char *outStr, int maxLen, const char *fmt, va_list args) 215 | { 216 | StrPrintfParms strParm; 217 | 218 | strParm.str = outStr; 219 | strParm.maxLen = maxLen - 1; /* Leave space for temrinating null char */ 220 | 221 | return vStrXPrintf(StrPrintfFunc, &strParm, fmt, args); 222 | 223 | } // vStrPrintf 224 | 225 | /***************************************************************************/ 226 | /** 227 | * Generic, reentrant printf function. This is the workhorse of the StrPrintf 228 | * functions. 229 | * 230 | * @a outFunc will be called to output each character. If @a outFunc returns 231 | * a number >= 0, then vStrXPrintf will continue to call @a outFunc with 232 | * additional characters. 233 | * 234 | * If @a outFunc returns a negative number, then vStrXPrintf will stop calling 235 | * @a outFunc and will return the non-negative return value. 236 | * 237 | * The format string @a fmt consists of ordinary characters, escape 238 | * sequences, and format specifications. The ordinary characters and escape 239 | * sequences are output in their order of appearance. Format specifications 240 | * start with a percent sign (%) and are read from left to right. When 241 | * the first format specification (if any) is encountered, it converts the 242 | * value of the first argument after @a fmt and outputs it accordingly. 243 | * The second format specification causes the second argument to be 244 | * converted and output, and so on. If there are more arguments than there 245 | * are format specifications, the extra arguments are ignored. The 246 | * results are undefined if there are not enough arguments for all the 247 | * format specifications. 248 | * 249 | * A format specification has optional, and required fields, in the following 250 | * form: 251 | * 252 | * %[flags][width][.precision][l]type 253 | * 254 | * Each field of the format specification is a single character or a number 255 | * specifying a particular format option. The simplest format specification 256 | * contains only the percent sign and a @b type character (for example %s). 257 | * If a percent sign is followed by a character that has no meaning as a 258 | * format field, the character is sent to the output function. For example, 259 | * to print a percent-sign character, use %%. 260 | * 261 | * The optional fields, which appear before the type character, control 262 | * other aspects of the formatting, as follows: 263 | * 264 | * @b flags may be one of the following: 265 | * 266 | * - - (minus sign) left align the result within the given field width. 267 | * - 0 (zero) Zeros are added until the minimum width is reached. 268 | * 269 | * @b width may be one of the following: 270 | * - a number specifying the minimum width of the field 271 | * - * (asterick) means that an integer taken from the argument list will 272 | * be used to provide the width. The @a width argument must precede the 273 | * value being formatted in the argument list. 274 | * 275 | * @b precision may be one of the following: 276 | * - a number 277 | * - * (asterick) means that an integer taken from the argument list will 278 | * be used to provide the precision. The @a precision argument must 279 | * precede the value being formatted in the argument list. 280 | * 281 | * The interpretation of @a precision depends on the type of field being 282 | * formatted: 283 | * - For b, d, o, u, x, X, the precision specifies the minimum number of 284 | * digits that will be printed. If the number of digits in the argument 285 | * is less than @a precision, the output value is padded on the left with 286 | * zeros. The value is not truncated when the number of digits exceeds 287 | * @a prcision. 288 | * - For s, the precision specifies the maximum number of characters to be 289 | * printed. 290 | * 291 | * The optional type modifier l (lowercase ell), may be used to specify 292 | * that the argument is a long argument. This makes a difference on 293 | * architectures where the sizeof an int is different from the sizeof a long. 294 | * 295 | * @b type causes the output to be formatted as follows: 296 | * - b Unsigned binary integer. 297 | * - c Character. 298 | * - d Signed decimal integer. 299 | * - o Unsigned octal integer. 300 | * - s Null terminated character string. 301 | * - u Unsigned Decimal integer. 302 | * - x Unsigned hexadecimal integer, using "abcdef". 303 | * - X Unsigned hexadecimal integer, using "ABCDEF". 304 | * 305 | * @param outFunc (in) Pointer to function to call to output a character. 306 | * @param outParm (in) Passed to @a outFunc. 307 | * @param fmt (in) Format string (ala printf, descrtibed above). 308 | * @param args (in) Variable length list of arguments. 309 | * 310 | * @return The number of characters successfully output, or a negative number 311 | * if an error occurred. 312 | */ 313 | 314 | int vStrXPrintf(StrXPrintfFunc outFunc, void *outParm, const char *fmt, va_list args) 315 | { 316 | Parameters p; 317 | char controlChar; 318 | 319 | p.numOutputChars = 0; 320 | p.outFunc = outFunc; 321 | p.outParm = outParm; 322 | 323 | controlChar = pgm_read_byte(fmt++); 324 | 325 | while (controlChar != '\0') { 326 | if (controlChar == '%') { 327 | short precision = -1; 328 | short longArg = 0; 329 | short base = 0; 330 | 331 | controlChar = pgm_read_byte(fmt++); 332 | p.minFieldWidth = 0; 333 | p.leadingZeros = 0; 334 | p.options = NO_OPTION; 335 | 336 | SetOption(&p, RIGHT_JUSTIFY); 337 | 338 | /* 339 | * Process [flags] 340 | */ 341 | 342 | if (controlChar == '-') { 343 | ClearOption(&p, RIGHT_JUSTIFY); 344 | controlChar = pgm_read_byte(fmt++); 345 | } 346 | 347 | if (controlChar == '0') { 348 | SetOption(&p, ZERO_PAD); 349 | controlChar = pgm_read_byte(fmt++); 350 | } 351 | 352 | /* 353 | * Process [width] 354 | */ 355 | 356 | if (controlChar == '*') { 357 | p.minFieldWidth = (short) va_arg(args, int); 358 | controlChar = pgm_read_byte(fmt++); 359 | } else { 360 | while (('0' <= controlChar) && (controlChar <= '9')) { 361 | p.minFieldWidth = p.minFieldWidth * 10 + controlChar - '0'; 362 | controlChar = pgm_read_byte(fmt++); 363 | } 364 | } 365 | 366 | /* 367 | * Process [.precision] 368 | */ 369 | 370 | if (controlChar == '.') { 371 | controlChar = pgm_read_byte(fmt++); 372 | if (controlChar == '*') { 373 | precision = (short) va_arg(args, int); 374 | controlChar = pgm_read_byte(fmt++); 375 | } else { 376 | precision = 0; 377 | while (('0' <= controlChar) && (controlChar <= '9')) { 378 | precision = precision * 10 + controlChar - '0'; 379 | controlChar = pgm_read_byte(fmt++); 380 | } 381 | } 382 | } 383 | 384 | /* 385 | * Process [l] 386 | */ 387 | 388 | if (controlChar == 'l') { 389 | longArg = 1; 390 | controlChar = pgm_read_byte(fmt++); 391 | } 392 | 393 | /* 394 | * Process type. 395 | */ 396 | 397 | if (controlChar == 'd') { 398 | base = 10; 399 | } else if (controlChar == 'x') { 400 | base = 16; 401 | } else if (controlChar == 'X') { 402 | base = 16; 403 | SetOption(&p, CAPITAL_HEX); 404 | } else if (controlChar == 'u') { 405 | base = 10; 406 | } else if (controlChar == 'o') { 407 | base = 8; 408 | } else if (controlChar == 'b') { 409 | base = 2; 410 | } else if (controlChar == 'c') { 411 | base = -1; 412 | ClearOption(&p, ZERO_PAD); 413 | } else if (controlChar == 's') { 414 | base = -2; 415 | ClearOption(&p, ZERO_PAD); 416 | } 417 | 418 | if (base == 0) { /* invalid conversion type */ 419 | if (controlChar != '\0') { 420 | OutputChar(&p, controlChar); 421 | controlChar = pgm_read_byte(fmt++); 422 | } 423 | } else { 424 | if (base == -1) { /* conversion type c */ 425 | char c = (char) va_arg(args, int); 426 | p.editedStringLen = 1; 427 | OutputField(&p, &c); 428 | } else if (base == -2) { /* conversion type s */ 429 | char *string = va_arg(args, char *); 430 | 431 | p.editedStringLen = 0; 432 | while (string[p.editedStringLen] != '\0') { 433 | if ((precision >= 0) 434 | && (p.editedStringLen >= precision)) { 435 | /* 436 | * We don't require the string to be null terminated 437 | * if a precision is specified. 438 | */ 439 | 440 | break; 441 | } 442 | p.editedStringLen++; 443 | } 444 | OutputField(&p, string); 445 | } else { /* conversion type d, b, o or x */ 446 | unsigned long x; 447 | 448 | /* 449 | * Worst case buffer allocation is required for binary output, 450 | * which requires one character per bit of a long. 451 | */ 452 | 453 | char buffer[CHAR_BIT * sizeof(unsigned long) + 1]; 454 | 455 | p.editedStringLen = 0; 456 | if (longArg) { 457 | x = va_arg(args, unsigned long); 458 | } else if (controlChar == 'd') { 459 | x = va_arg(args, int); 460 | } else { 461 | x = va_arg(args, unsigned); 462 | } 463 | 464 | if ((controlChar == 'd') && ((long) x < 0)) { 465 | SetOption(&p, MINUS_SIGN); 466 | x = -(long) x; 467 | } 468 | 469 | do { 470 | int c; 471 | c = x % base + '0'; 472 | if (c > '9') { 473 | if (IsOptionSet(&p, CAPITAL_HEX)) { 474 | c += 'A' - '9' - 1; 475 | } else { 476 | c += 'a' - '9' - 1; 477 | } 478 | } 479 | buffer[sizeof(buffer) - 1 - p.editedStringLen++] = (char) c; 480 | } 481 | while ((x /= base) != 0); 482 | 483 | if ((precision >= 0) && (precision > p.editedStringLen)) { 484 | p.leadingZeros = precision - p.editedStringLen; 485 | } 486 | OutputField(&p, buffer + sizeof(buffer) - p.editedStringLen); 487 | } 488 | controlChar = pgm_read_byte(fmt++); 489 | } 490 | } else { 491 | /* 492 | * We're not processing a % output. Just output the character that 493 | * was encountered. 494 | */ 495 | 496 | OutputChar(&p, controlChar); 497 | controlChar = pgm_read_byte(fmt++); 498 | } 499 | } 500 | return p.numOutputChars; 501 | 502 | } // vStrXPrintf 503 | 504 | /** @} */ 505 | 506 | /** 507 | * @addtogroup StrPrintfInternal 508 | * @{ 509 | */ 510 | 511 | /***************************************************************************/ 512 | /** 513 | * Outputs a single character, keeping track of how many characters have 514 | * been output. 515 | * 516 | * @param p (mod) State information. 517 | * @param c (in) Character to output. 518 | */ 519 | 520 | static void 521 | OutputChar(Parameters * p, int c) 522 | { 523 | if (p->numOutputChars >= 0) { 524 | int n = (*p->outFunc) (p->outParm, c); 525 | 526 | if (n >= 0) { 527 | p->numOutputChars++; 528 | } else { 529 | p->numOutputChars = n; 530 | } 531 | } 532 | 533 | } // OutputChar 534 | 535 | /***************************************************************************/ 536 | /** 537 | * Outputs a formatted field. This routine assumes that the field has been 538 | * converted to a string, and this routine takes care of the width 539 | * options, leading zeros, and any leading minus sign. 540 | * 541 | * @param p (mod) State information. 542 | * @param s (in) String to output. 543 | */ 544 | 545 | static void 546 | OutputField(Parameters * p, char *s) 547 | { 548 | short padLen = p->minFieldWidth - p->leadingZeros - p->editedStringLen; 549 | 550 | if (IsOptionSet(p, MINUS_SIGN)) { 551 | if (IsOptionSet(p, ZERO_PAD)) { 552 | /* 553 | * Since we're zero padding, output the minus sign now. If we're space 554 | * padding, we wait until we've output the spaces. 555 | */ 556 | 557 | OutputChar(p, '-'); 558 | } 559 | 560 | /* 561 | * Account for the minus sign now, even if we are going to output it 562 | * later. Otherwise we'll output too much space padding. 563 | */ 564 | 565 | padLen--; 566 | } 567 | 568 | if (IsOptionSet(p, RIGHT_JUSTIFY)) { 569 | /* 570 | * Right justified: Output the spaces then the field. 571 | */ 572 | 573 | while (--padLen >= 0) { 574 | OutputChar(p, p->options & ZERO_PAD ? '0' : ' '); 575 | } 576 | } 577 | if (IsOptionSet(p, MINUS_SIGN) && IsOptionClear(p, ZERO_PAD)) { 578 | /* 579 | * We're not zero padding, which means we haven't output the minus 580 | * sign yet. Do it now. 581 | */ 582 | 583 | OutputChar(p, '-'); 584 | } 585 | 586 | /* 587 | * Output any leading zeros. 588 | */ 589 | 590 | while (--p->leadingZeros >= 0) { 591 | OutputChar(p, '0'); 592 | } 593 | 594 | /* 595 | * Output the field itself. 596 | */ 597 | 598 | while (--p->editedStringLen >= 0) { 599 | OutputChar(p, *s++); 600 | } 601 | 602 | /* 603 | * Output any trailing space padding. Note that if we output leading 604 | * padding, then padLen will already have been decremented to zero. 605 | */ 606 | 607 | while (--padLen >= 0) { 608 | OutputChar(p, ' '); 609 | } 610 | 611 | } // OutputField 612 | 613 | /***************************************************************************/ 614 | /** 615 | * Helper function, used by vStrPrintf() (and indirectly by StrPrintf()) 616 | * for outputting characters into a user supplied buffer. 617 | * 618 | * @param outParm (mod) Pointer to StrPrintfParms structure. 619 | * @param ch (in) Character to output. 620 | * 621 | * @return 1 if the character was stored successfully, -1 if the buffer 622 | * was overflowed. 623 | */ 624 | 625 | static int 626 | StrPrintfFunc(void *outParm, int ch) 627 | { 628 | StrPrintfParms *strParm = (StrPrintfParms *) outParm; 629 | 630 | if (strParm->maxLen > 0) { 631 | *strParm->str++ = (char) ch; 632 | *strParm->str = '\0'; 633 | strParm->maxLen--; 634 | 635 | return 1; 636 | } 637 | 638 | /* 639 | * Whoops. We ran out of space. 640 | */ 641 | 642 | return -1; 643 | 644 | } // StrPrintfFunc 645 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------