diff --git a/.github/workflows/compile.yml b/.github/workflows/compile.yml new file mode 100644 index 0000000..1a638ea --- /dev/null +++ b/.github/workflows/compile.yml @@ -0,0 +1,32 @@ +name: Build binaries + +on: + - push + - workflow_dispatch + +jobs: + build: + runs-on: ubuntu-20.04 + + steps: + - uses: actions/checkout@v3 + with: + submodules: recursive + - name: Setup arm-none-eabi-gcc + uses: carlosperate/arm-none-eabi-gcc-action@v1 + with: + release: 11.2-2022.02 + - name: Build libopencm3 + run: make lib + - name: Make main binary + run: make -C src + - name: Consolidate binaries + run: | + mkdir dist + cp src/main.elf dist/ + cp src/main.bin dist/ + - name: Archive produced binaries + uses: actions/upload-artifact@v3 + with: + name: mcv4-binaries + path: dist/* diff --git a/.gitignore b/.gitignore index d24b6ab..2a65cc5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,20 @@ +*~ *.o -*.elf +*.d *.bin +*.elf +*.hex +*.srec +*.list *.map -depend +*.stylecheck +generated.*.ld +.gdb_history +.DS_Store + +# Project files from idea/netbeans/eclipse +nbproject/ +.idea/ +.project + mcv4.conf diff --git a/.gitmodules b/.gitmodules index 29e93ae..c4a0df1 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "libopencm3"] path = libopencm3 - url = git://github.com/libopencm3/libopencm3.git + url = https://github.com/libopencm3/libopencm3.git diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..153d416 --- /dev/null +++ b/LICENSE @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. \ No newline at end of file diff --git a/Makefile b/Makefile index 84cfe78..72eb9a8 100644 --- a/Makefile +++ b/Makefile @@ -1,67 +1,95 @@ -FW_VER=3 - -TOOLCHAIN_DIR = ./libopencm3 -PREFIX = arm-none-eabi -CC = $(PREFIX)-gcc -LD = $(PREFIX)-gcc -SIZE = $(PREFIX)-size -GDB = $(PREFIX)-gdb -OBJCOPY = $(PREFIX)-objcopy -OOCD = openocd - -LDSCRIPT = stm32-mcv4.ld -OOCD_BOARD = oocd/mcv4.cfg - -CFLAGS += -mcpu=cortex-m3 -mthumb -msoft-float -DSTM32F1 \ - -Wall -Wextra -O0 -std=gnu99 -g -fno-common \ - -I$(TOOLCHAIN_DIR)/include -DFW_VER=$(FW_VER) -LDFLAGS += -lc -lm -L$(TOOLCHAIN_DIR)/lib/thumb/cortex-m3 -L$(TOOLCHAIN_DIR)/lib \ - -L$(TOOLCHAIN_DIR)/lib/stm32/f1 -lnosys -T$(LDSCRIPT) \ - -nostartfiles -Wl,--gc-sections,-Map=mcv4.map -mcpu=cortex-m3 \ - -mthumb -march=armv7-m -mfix-cortex-m3-ldrd -msoft-float - -O_FILES = main.o led.o output.o usart.o analogue.o fw_ver.o -TEST_O_FILES = test.o led.o output.o - -all: mcv4.bin mcv4_test.bin - -test: mcv4_test.bin - -include depend - -mcv4.elf: $(O_FILES) $(LD_SCRIPT) $(TOOLCHAIN_DIR)/lib/libopencm3_stm32f1.a - $(LD) -o $@ $(O_FILES) $(LDFLAGS) -lopencm3_stm32f1 - $(SIZE) $@ - -mcv4_test.elf: $(TEST_O_FILES) $(LD_SCRIPT) $(TOOLCHAIN_DIR)/lib/libopencm3_stm32f1.a - $(LD) -o $@ $(TEST_O_FILES) $(LDFLAGS) -lopencm3_stm32f1 - $(SIZE) $@ - -%.bin: %.elf - $(OBJCOPY) -O binary $< $@ - -depend: *.c - rm -f depend - for file in $^; do \ - $(CC) $(CFLAGS) -MM $$file -o - >> $@ ; \ - done ; - -.PHONY: all test clean flash - -flash: mcv4.elf - $(OOCD) -f "$(OOCD_BOARD)" \ - -c "init" \ - -c "reset init" \ - -c "stm32f1x mass_erase 0" \ - -c "flash write_image $<" \ - -c "reset" \ - -c "shutdown" - -debug: mcv4.elf - $(OOCD) -f "$(OOCD_BOARD)" \ - -c "init" \ - # -c "reset halt" & - $(GDB) mcv4.elf - -clean: - -rm -f mcv4.elf depend *.o +## +## This file is part of the libopencm3 project. +## +## Copyright (C) 2009 Uwe Hermann +## +## This library is free software: you can redistribute it and/or modify +## it under the terms of the GNU Lesser General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## (at your option) any later version. +## +## This library is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU Lesser General Public License for more details. +## +## You should have received a copy of the GNU Lesser General Public License +## along with this library. If not, see . +## + +PREFIX ?= arm-none-eabi- + +TARGETS := src + +# Be silent per default, but 'make V=1' will show all compiler calls. +ifneq ($(V),1) +Q := @ +# Do not print "Entering directory ...". +MAKEFLAGS += --no-print-directory +endif + +OPENCM3_DIR ?= $(realpath libopencm3) +EXAMPLE_RULES = bin + +all: build + +bin: EXAMPLE_RULES += bin +hex: EXAMPLE_RULES += hex +srec: EXAMPLE_RULES += srec +list: EXAMPLE_RULES += list +images: EXAMPLE_RULES += images + +bin: build +hex: build +srec: build +list: build +images: build + +build: lib examples + +lib: + $(Q)if [ ! "`ls -A $(OPENCM3_DIR)`" ] ; then \ + printf "######## ERROR ########\n"; \ + printf "\tlibopencm3 is not initialized.\n"; \ + printf "\tPlease run:\n"; \ + printf "\t$$ git submodule init\n"; \ + printf "\t$$ git submodule update\n"; \ + printf "\tbefore running make.\n"; \ + printf "######## ERROR ########\n"; \ + exit 1; \ + fi + $(Q)$(MAKE) -C $(OPENCM3_DIR) + +EXAMPLE_DIRS:=$(sort $(dir $(wildcard $(addsuffix /Makefile,$(TARGETS))))) +$(EXAMPLE_DIRS): lib + @printf " BUILD $@\n"; + $(Q)$(MAKE) --directory=$@ OPENCM3_DIR=$(OPENCM3_DIR) $(EXAMPLE_RULES) + +examples: $(EXAMPLE_DIRS) + $(Q)true + +examplesclean: $(EXAMPLE_DIRS:=.clean) + +clean: examplesclean styleclean + $(Q)$(MAKE) -C libopencm3 clean + +stylecheck: $(EXAMPLE_DIRS:=.stylecheck) +styleclean: $(EXAMPLE_DIRS:=.styleclean) + + +%.clean: + $(Q)if [ -d $* ]; then \ + printf " CLEAN $*\n"; \ + $(MAKE) -C $* clean OPENCM3_DIR=$(OPENCM3_DIR) || exit $?; \ + fi; + +%.styleclean: + $(Q)$(MAKE) -C $* styleclean OPENCM3_DIR=$(OPENCM3_DIR) + +%.stylecheck: + $(Q)$(MAKE) -C $* stylecheck OPENCM3_DIR=$(OPENCM3_DIR) + + +.PHONY: build lib examples $(EXAMPLE_DIRS) install clean stylecheck styleclean \ + bin hex srec list images + diff --git a/README.md b/README.md index 10f32b3..6f192ed 100644 --- a/README.md +++ b/README.md @@ -1,101 +1,70 @@ Motor Board v4 Firmware ======================= -Prerequisites -------------- +## Instructions -These instructions assume that you are using a version of Linux, but should also work on BSD-derived OSes (including OS X). Windows users may wish to try [Cygwin][cygwin], create a Linux VM (although flashing the board from a VM may require some thought), or consider their life choices. +Using a posix system, you require `make`, the `arm-none-eabi` toolchain and `git`. +Before attempting to build anything initialise all the submodules. +```shell +$ git submodule update --init --recursive +``` -* `git` can be found in your distribution's repositories, or [online][git]. -* A working C compiler, such as `gcc` or `clang`, also from your distribution's repositories. -* `make`, also from your distribution's repositories. -* The `arm-none-eabi` toolchain. This may be in your distribution's repositories, otherwise download it [from Launchpad][toolchain] and follow the instructions in the README. -* `stm32flash`, which can be found [on Google Code][stm32flash]. After downloading, build and install it: +To build the main binary, run: +```shell +$ make +``` +The binary will then be at `src/main.bin`. +This will also build the library libopencm3 the first time you run it. - $ make - $ sudo make install +This can be flashed to an attached motor board that is in bootloader using: +```shell +$ make -C src prog +``` +To use the `prog` command you need to install stm32flash. This is a cross-platform utility that may be in your operating system's package manager, otherwise it can be downloaded from [their website](https://sourceforge.net/p/stm32flash/wiki/Home/). -Instructions ------------- +To enter the bootloader the pushbutton on the board can be pressed with the 12V input connected. Whilst 12V power is present the board will remain in bootloader. -1. From a shell, `cd` into the directory where you cloned the repository and download the `libopencm3` submodule: +### Finding the board - $ git submodule update --init +With the pyserial library, the serial port can be identified using the `pyserial-ports --verbose` command. -2. Determine your `arm-none-eabi` toolchain prefix, unless it is in your `$PATH`. If you downloaded it from the link above, it will be the path to the `bin` directory of the extracted folder, followed by `arm-none-eabi`. - -3. Build `libopencm3`: - - $ cd libopencm3 - $ make PREFIX= - -4. Change back to the project directory and build the firmware: - - $ cd .. - $ make PREFIX= - -5. Connect the motor board to your machine via USB. The USB Power Light (green, next to the connector) should turn on. - -6. Connect the motor board to a power source. The main power light (green, in the middle of the board) should turn on. If using the SR power board, you will have to run a program to turn on the motor rail. - -7. Press the firmware button on the side of the motor board with a long thin object. - -8. To test connectivity, run the following command, where X is found by running `ls /dev/ttyUSB*`: - - $ stm32flash /dev/ttyUSB - -9. Load the firmware onto the motor board: - - $ stm32flash -w mcv4.bin -v /dev/ttyUSB - ## Controls The motor board is largely controlled over the serial interface. There is one physical push button on the board that puts the microprocessor into a mode in which new firmware can be installed. +### LEDs + +There are 4 LEDs controlled by the MCU, 2 blue and 2 red located around the input choke. +The blue LED is lit when the respective channel is drawing over 5 amps. +The red LED is lit when the respective H-bridge has reported a fault. + ## USB interface Unlike other SR v4 boards, the STM32 on the motor board does not directly communicate over USB. Instead there is an FTDI USB serial interface chip. The FTDI Chip has vendor ID `0403` and product ID `6001`. It can be further filtered by the USB `product` field. -Given that the appropriate drivers are available on your computer, it should appear as a standard serial interface. You should open this interface at a baud rate of `1000000bps`. +Given that the appropriate drivers are available on your computer, it should appear as a standard serial interface. You should open this interface at a baud rate of `115200bps`. ### Serial Commands +Commands can be sent to the board via the serial or USB serial interface. Each command is its own line and is terminated with a new line. -8 bit commands should be sent over the serial interface to the board. - -The following commands are supported: - -| Decimal Value | Unicode| Purpose | -|---------------|--------|---------------------------------| -| 0 | `\x00` | Reset the STM32 | -| 1 | `\x01` | Get the firmware version string | -| 2 | `\x02` | Set Motor 0 value | -| 3 | `\x03` | Set Motor 1 value | -| 4 | `\x04` | Reset into USB bootloader | - - -### Setting Motor Speeds - -The value of a motor can be set by sending the appropriate command, and then a second byte as follows: - -The argument byte is a standard 8-bit signed number, where a few values are reserved for the special cases of no-op, coast and brake. - -| Decimal Value | Purpose | -|---------------|-----------------| -| 0 | No-op | -| 1 | Coast the motor | -| 2 | Brake the motor | - -### Firmware String - -When the firmware string is requested from the motor board, you will receive bytes of the following format over the serial interface: `MCV4B:3\n`. - -The number after the colon represents the firmware version of the board. +Action | Description | Command | Parameter Description | Return | Return Parameters +--- | --- | --- | --- | --- | --- +Identify | Get the board type and version | *IDN? | - | Student Robotics:MBv4B:\:\ | \
\ +Status | Get board status | *STATUS? | - | \:\ | \ - a comma separated list of 1/0s indicating if an output driver has reported a fault e.g. 1,0
\ - voltage at 12V input in mV +Reset | Reset board to safe startup state
- Turn off all outputs
- Reset the lights | *RESET | - | ACK | - +Set motor power | Sets the speed of one of the motors | MOT:\:SET:\ | \ motor number, int, 0-1
\ motor power, int, -1000 to 1000 | ACK | - +Read motor power | Gets the current speed setting of the motor | MOT:\:GET? | \ motor number, int, 0-1 | \:\ | \ motor enabled, int, 0-1
\ motor power, int, -1000 to 1000" +Disable motor output | Puts the motor into high impedance (equivalent to current coast) | MOT:\:DISABLE | \ motor number, int, 0-1 | ACK | - +Read motor current | Read the current power draw of the motor | MOT:\:I? | \ motor number, int, 0-1 | \ | \ - current, int, measured in mA +Enter bootloader | Enter the serial bootloader to load new firmware | *SYS:BOOTLOADER | - | ACK | - ## udev Rule +On most systems this should not be required as serial ports will already below to a non-root group, i.e. plugdev. + If you are connecting the Motor Board to a Linux computer with udev, the following rule can be added in order to access the Motor Board interface without root privileges: @@ -103,7 +72,9 @@ the Motor Board interface without root privileges: It should be noted that `plugdev` can be changed to any Unix group of your preference. -[cygwin]: http://cygwin.com/ -[toolchain]: https://launchpad.net/gcc-arm-embedded -[stm32flash]: http://stm32flash.googlecode.com -[git]: http://git-scm.com +## Designs + +You can access the schematics and source code of the hardware in the following places. +- [Full Schematics](https://studentrobotics.org/docs/resources/kit/motor-schematic.pdf) +- [Competitor Facing Docs](https://studentrobotics.org/docs/kit/motor_board) +- [Hardware designs](https://github.com/srobo/motor-v4-hw) diff --git a/analogue.c b/analogue.c deleted file mode 100644 index 848c9e8..0000000 --- a/analogue.c +++ /dev/null @@ -1,71 +0,0 @@ -#include "analogue.h" -#include "led.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -void analogue_init(void) { - gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_ANALOG, GPIO1); /* 12V */ - gpio_set_mode(GPIOC, GPIO_MODE_INPUT, GPIO_CNF_INPUT_ANALOG, GPIO0); /* M0 CS */ - gpio_set_mode(GPIOC, GPIO_MODE_INPUT, GPIO_CNF_INPUT_ANALOG, GPIO1); /* M0a */ - gpio_set_mode(GPIOC, GPIO_MODE_INPUT, GPIO_CNF_INPUT_ANALOG, GPIO2); /* M0b */ - - /* NVIC set up */ - nvic_enable_irq(NVIC_ADC1_2_IRQ); - nvic_set_priority(NVIC_ADC1_2_IRQ, 1); - - /* Timer set up */ - rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_TIM1EN); - - timer_set_mode(TIM1, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); - /* 24MHz/12kHz = 2kHz timer clock. /2 gives 1000Hz sampling frequency */ - timer_set_period(TIM1, 2); - timer_set_prescaler(TIM1, 12000); - - timer_set_oc_mode(TIM1, TIM_OC1, TIM_OCM_PWM1); - timer_enable_oc_preload(TIM1, TIM_OC1); - timer_set_oc_value(TIM1, TIM_OC1, 1); - - timer_set_master_mode(TIM1, TIM_CR2_MMS_COMPARE_OC1REF); - - timer_enable_preload(TIM1); - timer_enable_counter(TIM1); - - /* Halt the ADC timer while debugging */ - DBGMCU_CR |= DBGMCU_CR_TIM1_STOP; - - /* ADC set up */ - rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_ADC1EN); - rcc_set_adcpre(RCC_CFGR_ADCPRE_PCLK2_DIV2); - - adc_off(ADC1); - - adc_enable_external_trigger_injected(ADC1, ADC_CR2_JEXTSEL_TIM1_TRGO); - adc_enable_scan_mode(ADC1); - adc_enable_eoc_interrupt(ADC1); - - adc_power_on(ADC1); - - uint8_t channel[] = {9, 10, 11, 12}; - adc_set_injected_sequence(ADC1, 4, channel); - - /* Wait for things to warm up */ - for (int i=0; i<100000; i++) - __asm__("nop"); - adc_reset_calibration(ADC1); - adc_calibration(ADC1); -} - -void adc1_2_isr(void) { - led_toggle(LED_M0_R); - ADC1_SR = 0; -} diff --git a/analogue.h b/analogue.h deleted file mode 100644 index 3eaefa5..0000000 --- a/analogue.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef __ANALOGUE_H -#define __ANALOGUE_H - -#include - - -void analogue_init(void); - -#endif /* __ANALOGUE_H */ diff --git a/error.h b/error.h deleted file mode 100644 index 01485ff..0000000 --- a/error.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef __ERROR_H -#define __ERROR_H - -#define ENOCH -1 -#define ENODIR -2 -#define ENOSPEED -3 - -#endif /* __ERROR_H */ diff --git a/fw_ver.c b/fw_ver.c deleted file mode 100644 index 8bce5bf..0000000 --- a/fw_ver.c +++ /dev/null @@ -1,6 +0,0 @@ -#include - -/* Current firmware version */ -/* Put this in .fwver section so that the linker script can link it - * into the right place. */ -const uint16_t firmware_version __attribute__ ((section (".fwver"))) = FW_VER; diff --git a/fw_ver.h b/fw_ver.h deleted file mode 100644 index 10bc067..0000000 --- a/fw_ver.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef __FW_VER_H -#define __FW_VER_H -#include - -extern const uint16_t firmware_version; - -#endif /* __FW_VER_HW */ diff --git a/led.c b/led.c deleted file mode 100644 index a1ac830..0000000 --- a/led.c +++ /dev/null @@ -1,12 +0,0 @@ -#include "led.h" - -void led_init(void) { - gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_2_MHZ, - GPIO_CNF_OUTPUT_PUSHPULL, LED_M0_R); - gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_2_MHZ, - GPIO_CNF_OUTPUT_PUSHPULL, LED_M0_B); - gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_2_MHZ, - GPIO_CNF_OUTPUT_PUSHPULL, LED_M1_R); - gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_2_MHZ, - GPIO_CNF_OUTPUT_PUSHPULL, LED_M1_B); -} diff --git a/led.h b/led.h deleted file mode 100644 index 9738223..0000000 --- a/led.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef __LED_H -#define __LED_H - -#include - -#define LED_M0_R GPIO6 -#define LED_M0_B GPIO7 -#define LED_M1_R GPIO8 -#define LED_M1_B GPIO9 - -void led_init(void); - -#define led_set(led) gpio_set(GPIOC, led) -#define led_clear(led) gpio_clear(GPIOC, led) -#define led_toggle(led) gpio_toggle(GPIOC, led) - -#endif /* __LED_H */ diff --git a/libopencm3 b/libopencm3 index 0f29fc8..203202e 160000 --- a/libopencm3 +++ b/libopencm3 @@ -1 +1 @@ -Subproject commit 0f29fc8b1be14db4908ee1d377c5e571d0ca6235 +Subproject commit 203202e9390d269ac0d57a6fd3c891f56998a4c8 diff --git a/main.c b/main.c deleted file mode 100644 index 5582aa2..0000000 --- a/main.c +++ /dev/null @@ -1,129 +0,0 @@ -#include -#include - -#include -#include -#include - -#include "led.h" -#include "output.h" -#include "usart.h" -#include "analogue.h" -#include "fw_ver.h" - -uint32_t *top_of_ram = ((uint32_t *)0x20001FF0); -#define BOOTLOADER_MAGIC 0xFACEBEE5 - -void init(void) { - rcc_clock_setup_in_hse_8mhz_out_24mhz(); - - rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_IOPAEN); - rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_IOPBEN); - rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_IOPCEN); - led_init(); - output_init(); - usart_init(); - //analogue_init(); - - led_set(LED_M0_R); -} - -void print_version(void) { - printf("MCV4B:%i\n", firmware_version); -} - -void enter_bootloader(void) { - printf("Entering bootloader\n"); - *top_of_ram = BOOTLOADER_MAGIC; - scb_reset_system(); -} - -void set_output(int channel, int8_t i) { - if (i == -127) { - output_disable(channel); - } else if (i == -126) { - output_enable(channel); - output_direction(channel, DIR_HALT); - } else { - output_enable(channel); - if (i < 0) { - output_direction(channel, DIR_REV); - } else { - output_direction(channel, DIR_FWD); - } - output_speed(channel, abs(i)); - } -} - -typedef enum { - STATE_INIT, - STATE_SPEED0, - STATE_SPEED1 -} state_t; - -void fsm(int c) { - int8_t i = c - 128; - - static state_t state = STATE_INIT; - switch (state) { - case STATE_INIT: - switch (i) { - case -128: - state = STATE_INIT; - break; - case -127: - state = STATE_INIT; - print_version(); - break; - case -126: - state = STATE_SPEED0; - break; - case -125: - state = STATE_SPEED1; - break; - case -124: - enter_bootloader(); - break; - default: - state = STATE_INIT; - break; - } - break; - case STATE_SPEED0: - state = STATE_INIT; - if (i != -128) { - set_output(0, i); - } - break; - case STATE_SPEED1: - state = STATE_INIT; - if (i != -128) { - set_output(1, i); - } - break; - default: - state = STATE_INIT; - break; - } -} - - -int main(void) { - /* Check to see if we should jump into the bootloader */ - if (*top_of_ram == BOOTLOADER_MAGIC) { - *top_of_ram = 0; - asm("ldr r0, =0x1FFFF000\n\t" \ - "ldr sp,[r0, #0]\n\t" \ - "ldr r0,[r0, #4]\n\t" \ - "bx r0"); - } - - init(); - - while (1) { - int c = usart_get_char(); - fsm(c); - } - - return 0; -} diff --git a/output.c b/output.c deleted file mode 100644 index fe49a3c..0000000 --- a/output.c +++ /dev/null @@ -1,141 +0,0 @@ -#include "output.h" -#include "error.h" - -#include -#include -#include - -#define PWM_PORT GPIOA -#define CTRL_PORT GPIOB - -#define M0INa GPIO12 -#define M0INb GPIO13 -#define M0ENa GPIO14 -#define M0ENb GPIO15 -#define M1INa GPIO8 -#define M1INb GPIO9 -#define M1ENa GPIO10 -#define M1ENb GPIO11 -#define M0PWM GPIO_TIM2_CH2 -#define M1PWM GPIO_TIM2_CH1_ETR - -#define setup_ctrl_gpio(pin) \ - gpio_set_mode(CTRL_PORT, GPIO_MODE_OUTPUT_2_MHZ, \ - GPIO_CNF_OUTPUT_PUSHPULL, pin) - -#define setup_pwm_pin(pin) \ - gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_2_MHZ, \ - GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, pin); - -#define check_channel(ch) do { \ - if (!(ch == 0 || ch == 1)) return ENOCH; \ - } while(0) -#define check_direction(dir) do { \ - if (!(dir < DIR_COUNT)) return ENODIR; \ - } while(0) - -#define check_speed(speed) do { \ - if (!(speed >= 0 && speed <= 4096)) return ENOSPEED; \ - } while(0) - -int output_init(void) { - setup_ctrl_gpio(M0INa); - setup_ctrl_gpio(M0INb); - setup_ctrl_gpio(M0ENa); - setup_ctrl_gpio(M0ENb); - setup_ctrl_gpio(M1INa); - setup_ctrl_gpio(M1INb); - setup_ctrl_gpio(M1ENa); - setup_ctrl_gpio(M1ENb); - - rcc_peripheral_enable_clock(&RCC_APB1ENR, RCC_APB1ENR_TIM2EN); - setup_pwm_pin(M0PWM); - setup_pwm_pin(M1PWM); - - timer_set_mode(TIM2, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); - timer_set_period(TIM2, 2000); - timer_set_prescaler(TIM2, 1); - - timer_set_oc_mode(TIM2, TIM_OC1, TIM_OCM_PWM1); - timer_set_oc_mode(TIM2, TIM_OC2, TIM_OCM_PWM1); - timer_enable_oc_preload(TIM2, TIM_OC1); - timer_enable_oc_preload(TIM2, TIM_OC2); - - timer_set_oc_polarity_high(TIM2, TIM_OC1); - timer_set_oc_polarity_high(TIM2, TIM_OC2); - timer_enable_oc_output(TIM2, TIM_OC1); - timer_enable_oc_output(TIM2, TIM_OC2); - - output_speed(0, 0); - output_speed(1, 0); - - timer_enable_preload(TIM2); - timer_enable_counter(TIM2); - return 0; -} - -int output_enable(int channel) { - check_channel(channel); - if (channel == 0) { - gpio_set(CTRL_PORT, M0ENa); - gpio_set(CTRL_PORT, M0ENb); - } else { - gpio_set(CTRL_PORT, M1ENa); - gpio_set(CTRL_PORT, M1ENb); - } - return 0; -} - -int output_disable(int channel) { - check_channel(channel); - if (channel == 0) { - gpio_clear(CTRL_PORT, M0ENa); - gpio_clear(CTRL_PORT, M0ENb); - } else { - gpio_clear(CTRL_PORT, M1ENa); - gpio_clear(CTRL_PORT, M1ENb); - } - return 0; -} - -int output_direction(int channel, direction_t direction) { - check_channel(channel); - check_direction(direction); - if (direction == DIR_HALT) { - if (channel == 0) { - gpio_clear(CTRL_PORT, M0INa); - gpio_clear(CTRL_PORT, M0INb); - } else { - gpio_clear(CTRL_PORT, M1INa); - gpio_clear(CTRL_PORT, M1INb); - } - } else if (direction == DIR_FWD) { - if (channel == 0) { - gpio_set(CTRL_PORT, M0INa); - gpio_clear(CTRL_PORT, M0INb); - } else { - gpio_set(CTRL_PORT, M1INa); - gpio_clear(CTRL_PORT, M1INb); - } - } else if (direction == DIR_REV) { - if (channel == 0) { - gpio_clear(CTRL_PORT, M0INa); - gpio_set(CTRL_PORT, M0INb); - } else { - gpio_clear(CTRL_PORT, M1INa); - gpio_set(CTRL_PORT, M1INb); - } - } - return 0; -} - -int output_speed(int channel, int speed) { - check_channel(channel); - check_speed(speed); - if (channel == 0) { - timer_set_oc_value(TIM2, TIM_OC2, speed*20); - } else { - timer_set_oc_value(TIM2, TIM_OC1, speed*20); - } - return 0; -} diff --git a/output.h b/output.h deleted file mode 100644 index d1c47c2..0000000 --- a/output.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef __OUTPUT_H -#define __OUTPUT_H - -#include - -typedef enum { - DIR_HALT, - DIR_FWD, - DIR_REV, - - DIR_COUNT -} direction_t; - -int output_init(void); - -int output_enable(int channel); -int output_disable(int channel); - -int output_direction(int channel, direction_t direction); - -int output_speed(int channel, int speed); - -#endif /* __OUTPUT_H */ diff --git a/scripts/.gitkeep b/scripts/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/scripts/commission.py b/scripts/commission.py new file mode 100755 index 0000000..ac4fe09 --- /dev/null +++ b/scripts/commission.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +import argparse +import os +import subprocess +import tempfile +from time import sleep +from pathlib import Path + +import serial +from serial.serialutil import SerialException +from serial.tools import list_ports + +from insert_serial import pad_serial, insert_bin_serial + +BOARD_TYPE = 'MCv4B' +BOARD_VID = '0403' +BOARD_PID = '6001' +EEPROM_CONFIG = (Path(__file__).parent / '../utils/mcv4.conf.in').resolve() + + +def program_eeprom(asset): + with tempfile.TemporaryDirectory() as tmpdirname: + tmpdir = Path(tmpdirname) + orig_dir = os.getcwd() + try: + config_data = EEPROM_CONFIG.read_text() + + # Apply asset code to eeprom config + config_data = config_data.replace('SERIAL', asset) + eeprom_conf = tmpdir / 'mcv4.conf' + eeprom_conf.write_text(config_data) + os.chdir(tmpdir) + + # Flash eeprom w/ ftdi_eeprom + subprocess.check_call(['ftdi_eeprom', '--flash-eeprom', 'mcv4.conf']) + + Path('mcv4.eeprom').rename('mcv4-in.eeprom') + # Read back eeprom to verify + subprocess.check_call(['ftdi_eeprom', '--read-eeprom', 'mcv4.conf']) + + input_binary = Path('mcv4-in.eeprom').read_bytes() + output_binary = Path('mcv4.eeprom').read_bytes() + if input_binary == output_binary: + print("EEPROM verified") + else: + print("Verification failed") + raise RuntimeError + + finally: + os.chdir(orig_dir) + + +def serial_flash_firmware(port, firmware, detect_asset=False): + print( + "To flash the board using the factory bootloader you need to connect " + "12 volts to the board and connect the USB port. " + "Once connected press the board's pushbutton") + input('Press enter once this is done') + + if port is None: + port = find_port() + if port is None: + print('Failed to find serial port') + raise RuntimeError + + if detect_asset: + asset_code = find_asset(port) + else: + asset_code = input("Enter asset code to bake into the firmware and USB descriptor (will have sr prepended): ") + asset_code = 'sr' + asset_code.upper() + print(f"Programming asset code: {asset_code}") + + with tempfile.TemporaryDirectory() as tmpdirname: + tmpdir = Path(tmpdirname) + # Apply asset code to fw + stock_data = Path(firmware).read_bytes() + serial_num_addr = stock_data.find(b'XXXXXXXXXXXXXXX') + + if serial_num_addr == -1: + print("Couldn't find asset code placeholder") + raise subprocess.CalledProcessError + + data = insert_bin_serial(stock_data, pad_serial(asset_code, 15), serial_num_addr) + + # write fw w/ serial num to temp file + fw_file = tmpdir / 'main.bin' + fw_file.write_bytes(data) + + # Flash fw w/ stm32flash + subprocess.check_call(['stm32flash', '-b', '115200', '-w', str(fw_file), '-v', '-R', port]) + sleep(2) + return asset_code + + +def verify_firmware(version, expected_serial=None): + try: + s = serial.serial_for_url(f'hwgrep://{BOARD_VID}:{BOARD_PID}', timeout=3, baudrate=115200) + s.flush() + s.write(b'*IDN?\n') + identity_raw = s.readline() + if not identity_raw.endswith(b'\n'): + print(f"Board did not correctly respond to identify, returned: {identity_raw!r}") + return False + + identity = identity_raw.decode('utf-8').strip().split(':') + if identity[0] != 'Student Robotics': + print("Incorrect manufacturer returned") + return False + if identity[1] != BOARD_TYPE: + print("Incorrect board type returned") + return False + if identity[3] != version: + print('Incorrect version returned') + return False + if expected_serial is not None and identity[2] != expected_serial: + print(f"Serial number differs from expected, received {identity[2]!r}") + return False + + print(f"Successfully flashed {identity[2]}") + return identity[2] + + except SerialException: + print("Failed to open serial port") + return False + + +def log_success(log_file, asset_code): + with open(log_file, 'a') as f: + f.write(f"{asset_code}\n") + + +def find_port(): + try: + s = serial.serial_for_url(f'hwgrep://{BOARD_VID}:{BOARD_PID}', do_not_open=True) + return s.name + except SerialException: + return None + + +def find_asset(port): + return next(list_ports.grep(port)).serial_number + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('file', help="Firmware file to flash") + parser.add_argument('version', help="The version number the new firmware reports") + parser.add_argument('-log', '--serial_log', default=None, help="File to store serials successfully flashed") + parser.add_argument('--port', default=None, help="The serial port to access the board on, defaults to autodetection") + parser.add_argument('--eeprom', action='store_true', help="Also program the FTDI EEPROM with the asset code") + parser.add_argument('-auto', '--detect_asset', action='store_true', help="Autodetect asset code from eeprom") + + args = parser.parse_args() + + if args.eeprom and args.detect_asset: + raise RuntimeError("Can't write eeprom and use it to detect asset code.") + + try: + while True: + input('Press enter to flash motor board') + try: + expected_asset = serial_flash_firmware(args.port, args.file, args.detect_asset) + except subprocess.CalledProcessError: + print("Failed to flash firmware, try again") + continue + + verified_code = verify_firmware(args.version, expected_asset) + if args.eeprom: + try: + program_eeprom(expected_asset) + except RuntimeError: + print("EEPROM write failed") + continue + if verified_code is not False and args.serial_log is not None: + log_success(args.serial_log, verified_code) + except (KeyboardInterrupt, EOFError): + return + + +if __name__ == '__main__': + main() diff --git a/scripts/insert_serial.py b/scripts/insert_serial.py new file mode 100755 index 0000000..03a7bbd --- /dev/null +++ b/scripts/insert_serial.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +import argparse +from pathlib import Path + + +def pad_serial(serial_num, length=16): + "" + # Trim and pad to one below length to allow for a null terminator + serial_num_truncated = serial_num[:length - 1] + serial_num_padded = serial_num_truncated.ljust(length - 1, '\0') + + return serial_num_padded + '\0' + + +def insert_bin_serial(data, serial_num, addr): + "" + data_array = bytearray(data) # make the data mutable + + serial_bytes = serial_num.encode('ascii') + length = len(serial_bytes) + + # insert serial using slicing + data_array[addr:(addr + length)] = serial_bytes + + return bytes(data_array) + + +def ExistingFile(val): + """ To be used as an argparse argument type + Tests the file exists without opening it to avoid issues with files + not being closed: https://bugs.python.org/issue13824 + """ + f = Path(val) + try: + if not f.is_file(): + raise argparse.ArgumentTypeError(f'File not found {val}') + except PermissionError as e: + raise argparse.ArgumentTypeError(e) + + return f + + +def ValidPath(val): + """ To be used as an argparse argument type + Tests the filepath exists without creating it to avoid issues with + files not being closed: https://bugs.python.org/issue13824 + """ + f = Path(val) + try: + if not f.parent.is_dir(): + raise argparse.ArgumentTypeError(f'Path does not exist {val}') + except PermissionError as e: + raise argparse.ArgumentTypeError(e) + + return f + + +def main(): + parser = argparse.ArgumentParser( + description="Insert a serial number into a pre-compiled binary" + ) + parser.add_argument( + '-a', '--address', type=int, default=0x1FE0, + help=( + "The address offset from the start of the file to place the " + "serial number (defaults to 0x1FE0)" + ) + ) + parser.add_argument( + '-l', '--length', type=int, default=16, + help="The length of the serial number placeholder, including the null terminator (defaults to 16)" + ) + parser.add_argument('serial_num', help="The value to set the serial number to.") + parser.add_argument( + 'infile', type=ExistingFile, + help="The template file to insert the serial number into.", + ) + parser.add_argument( + 'outfile', type=ValidPath, + help="The file to write the output to.", + ) + + args = parser.parse_args() + + data = args.infile.read_bytes() + serial_num = pad_serial(args.serial_num, args.length) + new_data = insert_bin_serial(data, serial_num, args.address) + + args.outfile.write_bytes(new_data) + + +if __name__ == "__main__": + main() diff --git a/src/Makefile b/src/Makefile new file mode 100644 index 0000000..c3d8455 --- /dev/null +++ b/src/Makefile @@ -0,0 +1,66 @@ +## +## This file is part of the libopencm3 project. +## +## Copyright (C) 2009 Uwe Hermann +## Copyright (C) 2010 Piotr Esden-Tempski +## +## This library is free software: you can redistribute it and/or modify +## it under the terms of the GNU Lesser General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## (at your option) any later version. +## +## This library is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU Lesser General Public License for more details. +## +## You should have received a copy of the GNU Lesser General Public License +## along with this library. If not, see . +## +FW_VER ?= 4.4 + +# Name of C file with main function +BINARY = main +# Name of all other C files to be compiled (with .o extension) +OBJS = analogue.o led.o output.o usart.o msg_handler.o + +LDSCRIPT = $(OPENCM3_DIR)/../utils/stm32-mcv4.ld + +DEFS = -DFW_VER=\"$(FW_VER)\" +OOCD_FILE = ../utils/mcv4.cfg + +all: bin + +include ../utils/rules.mk + +elf: $(BINARY).elf +bin: $(BINARY).bin +hex: $(BINARY).hex +srec: $(BINARY).srec +list: $(BINARY).list +GENERATED_BINARIES=$(BINARY).elf $(BINARY).bin $(BINARY).hex $(BINARY).srec $(BINARY).list $(BINARY).map + +images: $(BINARY).images +flash: $(BINARY).flash +prog: $(BINARY).stm32flash + +# Define a helper macro for debugging make errors online +# you can type "make print-OPENCM3_DIR" and it will show you +# how that ended up being resolved by all of the included +# makefiles. +print-%: + @echo $*=$($*) + +clean: + @#printf " CLEAN\n" + $(Q)$(RM) $(GENERATED_BINARIES) generated.* $(OBJS) $(OBJS:%.o=%.d) + +stylecheck: $(STYLECHECKFILES:=.stylecheck) +styleclean: $(STYLECHECKFILES:=.styleclean) + +size: $(BINARY).elf + $(Q)arm-none-eabi-size -G -d $(BINARY).elf + +.PHONY: images clean stylecheck styleclean elf bin hex srec list + +-include $(OBJS:.o=.d) diff --git a/src/analogue.c b/src/analogue.c new file mode 100644 index 0000000..3f6f3eb --- /dev/null +++ b/src/analogue.c @@ -0,0 +1,137 @@ +#include "analogue.h" +#include "led.h" +#include "output.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +uint16_t input_voltage = 0; + +static void init_adc_timer(void) { + rcc_periph_clock_enable(RCC_TIM1); + + timer_set_mode(TIM1, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); + // 24MHz/1k = 24kHz timer clock. /1 gives 24kHz sampling frequency + timer_set_period(TIM1, 1000); + timer_set_prescaler(TIM1, 1); + + // Configure OC1 to generate an event on match + timer_set_oc_mode(TIM1, TIM_OC1, TIM_OCM_PWM1); + timer_enable_oc_preload(TIM1, TIM_OC1); + timer_set_oc_value(TIM1, TIM_OC1, 1); + + // Enable trigger output for triggering ADC scan run + timer_set_master_mode(TIM1, TIM_CR2_MMS_COMPARE_OC1REF); + + timer_enable_preload(TIM1); + + /* Halt the ADC timer while debugging */ + DBGMCU_CR |= DBGMCU_CR_TIM1_STOP; +} + +static void init_adc(void) { + gpio_set_mode(GPIOB, GPIO_MODE_INPUT, GPIO_CNF_INPUT_ANALOG, GPIO1); // 12V + gpio_set_mode(GPIOC, GPIO_MODE_INPUT, GPIO_CNF_INPUT_ANALOG, GPIO3); // M0 CS + gpio_set_mode(GPIOC, GPIO_MODE_INPUT, GPIO_CNF_INPUT_ANALOG, GPIO0); // M1 CS + + rcc_periph_clock_enable(RCC_ADC1); + rcc_set_adcpre(RCC_CFGR_ADCPRE_PCLK2_DIV2); + + // Disable ADC during configuration + adc_power_off(ADC1); + + // Extend the conversion times to reduce noise impact + adc_set_sample_time_on_all_channels(ADC1, ADC_SMPR_SMP_239DOT5CYC); + adc_set_right_aligned(ADC1); + + // Enable an interrupt after each scan run + nvic_enable_irq(NVIC_ADC1_2_IRQ); + nvic_set_priority(NVIC_ADC1_2_IRQ, 1); + adc_enable_eoc_interrupt(ADC1); + + // Enable scan runs on timer 1 trigger output + adc_enable_external_trigger_injected(ADC1, ADC_CR2_JEXTSEL_TIM1_TRGO); + adc_enable_scan_mode(ADC1); + + // Configure the channels to be sampled in each scan run + // the outputs will be in the ADC_JDRx registers + uint8_t channel[] = {9, 13, 10}; + adc_set_injected_sequence(ADC1, 3, channel); + + adc_power_on(ADC1); + + // Wait >1.3us for ADC to be ready to perform conversions + __asm__( // wait 40 clock cycles @ 24MHz = ~1.6us + "nop;nop;nop;nop;nop;" + "nop;nop;nop;nop;nop;" // 10 + "nop;nop;nop;nop;nop;" + "nop;nop;nop;nop;nop;" // 20 + "nop;nop;nop;nop;nop;" + "nop;nop;nop;nop;nop;" // 30 + "nop;nop;nop;nop;nop;" + "nop;nop;nop;nop;nop;" // 40 + ); + adc_reset_calibration(ADC1); + adc_calibrate(ADC1); +} + +void analogue_init(void) { + init_adc_timer(); + init_adc(); + + timer_enable_counter(TIM1); +} + +static uint16_t convert_to_ma(uint16_t current_raw) { + // voltage_mv = code * vref/4096 + // current_ma = (voltage_mv/rshunt) * Igain + + // current_ma = code * 3300/(4096 * 1100) * 7000 + return (uint16_t)((((uint32_t)current_raw * 2625) >> 9) & 0xffff); +} + +static uint16_t convert_to_mv(uint16_t voltage_raw) { + // meas_voltage_mv = code * vref/4096 + // voltage_mv = meas_voltage_mv * (R1 + R2)/(R2) + + // voltage_mv = (code * 3300/4096) * 5400/1100 + return (uint16_t)((((uint32_t)voltage_raw * 2025) >> 9) & 0xffff); +} + +static uint16_t decay_filter(uint16_t in_sample, uint16_t prev_out_sample) { + // Low-pass single-pole IIR filter, decay=0.972 + // y(n) = b1*x[n] + a0*y[n-1], a0 = decay, b1 = (1 - a0) + int32_t decay = 256 - 249; // 1 - 0.972 shifted 8 left + int32_t intermediary = ((int32_t)in_sample - (int32_t)prev_out_sample); + return (uint16_t)(prev_out_sample + ((decay * intermediary) >> 8)); +} + +void adc1_2_isr(void) { + ADC1_SR = 0; + check_output_faults(); + + input_voltage = convert_to_mv(adc_read_injected(ADC1, 1)); // 12V + uint16_t m0_current = convert_to_ma((uint16_t)(adc_read_injected(ADC1, 2) & 0xffff)); // M0 CS + uint16_t m1_current = convert_to_ma((uint16_t)(adc_read_injected(ADC1, 3) & 0xffff)); // M1 CS + + output_data[0].current = decay_filter(m0_current, output_data[0].current); + output_data[1].current = decay_filter(m1_current, output_data[1].current); + + // Light blue LEDs when the outputs are drawing more than 5 amps + for (uint8_t i = 0; i < NUM_OUTPUTS; i++) { + if (output_data[i].current > 5000) { + led_set((i == 0)?(LED_M0_B):(LED_M1_B)); + } else { + led_clear((i == 0)?(LED_M0_B):(LED_M1_B)); + } + } +} diff --git a/src/analogue.h b/src/analogue.h new file mode 100644 index 0000000..6c411d9 --- /dev/null +++ b/src/analogue.h @@ -0,0 +1,7 @@ +#pragma once + +#include + +extern uint16_t input_voltage; + +void analogue_init(void); diff --git a/src/led.c b/src/led.c new file mode 100644 index 0000000..14a4a0c --- /dev/null +++ b/src/led.c @@ -0,0 +1,12 @@ +#include "led.h" + +void led_init(void) { + gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_2_MHZ, + GPIO_CNF_OUTPUT_PUSHPULL, LED_M0_R); + gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_2_MHZ, + GPIO_CNF_OUTPUT_PUSHPULL, LED_M0_B); + gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_2_MHZ, + GPIO_CNF_OUTPUT_PUSHPULL, LED_M1_R); + gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_2_MHZ, + GPIO_CNF_OUTPUT_PUSHPULL, LED_M1_B); +} diff --git a/src/led.h b/src/led.h new file mode 100644 index 0000000..7161dcf --- /dev/null +++ b/src/led.h @@ -0,0 +1,15 @@ +#pragma once + +#include +#include + +#define LED_M0_R GPIO6 +#define LED_M0_B GPIO7 +#define LED_M1_R GPIO8 +#define LED_M1_B GPIO9 + +void led_init(void); + +static inline void led_set(const uint16_t led) {gpio_set(GPIOC, led);} +static inline void led_clear(const uint16_t led) {gpio_clear(GPIOC, led);} +static inline void led_toggle(const uint16_t led) {gpio_toggle(GPIOC, led);} diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..ba449c9 --- /dev/null +++ b/src/main.c @@ -0,0 +1,69 @@ +#include +#include + +#include +#include +#include +#include +#include + +#include "led.h" +#include "output.h" +#include "usart.h" +#include "analogue.h" +#include "msg_handler.h" + + +static void init(void) { + rcc_clock_setup_pll(&rcc_hse_configs[RCC_CLOCK_HSE8_24MHZ]); + + rcc_periph_clock_enable(RCC_GPIOA); + rcc_periph_clock_enable(RCC_GPIOB); + rcc_periph_clock_enable(RCC_GPIOC); + rcc_periph_clock_enable(RCC_PWR); + rcc_periph_clock_enable(RCC_BKP); + led_init(); + output_init(); + usart_init(); + analogue_init(); + + // Configure watchdog. Period: 50ms + iwdg_set_period_ms(50); + iwdg_start(); +} + +static void enter_bootloader(void) { + // Configure required clocks to write to backup registers + rcc_periph_clock_enable(RCC_PWR); + rcc_periph_clock_enable(RCC_BKP); + set_bootloader_signature(0); // reset bootloader signature so we don't repeatedly enter bootloader + __asm__ __volatile__( + "ldr r0, =0x1FFFF000;" // load bootloader address into r0 + "ldr sp,[r0, #0];" // Load bootloader address into stack pointer + "ldr r0,[r0, #4];" // Load bootloader start address into r0 (addr+4) + "bx r0;" // Jump to address in r0 + ); +} + +int main(void) { + /* Check to see if we should jump into the bootloader */ + if (bootloader_flag == BOOTLOADER_SIGNATURE) { + enter_bootloader(); + } + + init(); + + while (1) { + iwdg_reset(); + uint16_t c = usart_get_char(); + if (c & 0x100) { // skip parity errors + continue; + } + process_received_data((char)(c & 0xff)); + + if (bootloader_flag == BOOTLOADER_SIGNATURE) { + scb_reset_system(); // reset MCU to enter bootloader + } + } + return 0; +} diff --git a/src/msg_handler.c b/src/msg_handler.c new file mode 100644 index 0000000..49d6859 --- /dev/null +++ b/src/msg_handler.c @@ -0,0 +1,224 @@ +#include +#include +#include +#include +#include + +#include "msg_handler.h" +#include "output.h" +#include "analogue.h" +#include "usart.h" + +#define BOARD_NAME_SHORT "MCv4B" +#define MSG_MAXLEN 64 +#define USB_BUFFER_SIZE 64 + +const char serialnum[] = "XXXXXXXXXXXXXXX"; +char msg_buffer[MSG_MAXLEN]; +int current_msg_len = 0; + +static char* itoa(int value, char* string); + +static void append_str(char* dest, const char* src, int dest_max_len) { + strncat(dest, src, dest_max_len - strlen(dest)); +} +static char* get_next_arg(char* response, const char* err_msg, int max_len) { + char* next_arg = strtok(NULL, ":"); + if (next_arg == NULL) { + strncat(response, err_msg, max_len); + return NULL; + } + return next_arg; +} + +void process_received_data(char new_data) { + if (new_data == '\n') { + msg_buffer[current_msg_len] = '\0'; // add null terminator to make it a string + + char response_buffer[USB_BUFFER_SIZE]; + + handle_msg(msg_buffer, response_buffer, (USB_BUFFER_SIZE - 2)); + current_msg_len = 0; + + uint16_t resp_len = strlen(response_buffer); + response_buffer[resp_len++] = '\n'; + response_buffer[resp_len] = '\0'; + usart_send_string(response_buffer); + } else if (new_data == '\r') { + // Drop carriage returns + } else { + msg_buffer[current_msg_len] = new_data; + current_msg_len++; + + // drop a full buffer without newlines + if (current_msg_len == (MSG_MAXLEN - 1)) { + current_msg_len = 0; + } + } +} + +void handle_msg(char* buf, char* response, int max_len) { + // max_len is the maximum length of the string that can be fitted in buf + // so the buffer must be at least max_len+1 long + char temp_str[12] = {0}; // for doing itoa conversions + response[0] = '\0'; // make a blank string + + char* next_arg = strtok(buf, ":"); + if (strcmp(next_arg, "MOT") == 0) { + next_arg = get_next_arg(response, "NACK:Missing motor number", max_len); + if(next_arg == NULL) {return;} + + unsigned long int output_num; + + if (isdigit((int)next_arg[0])) { + output_num = strtoul(next_arg, NULL, 10); + // bounds check + if (output_num >= 2) { + append_str(response, "NACK:Invalid motor number", max_len); + return; + } + } else { + append_str(response, "NACK:Missing motor number", max_len); + return; + } + + next_arg = get_next_arg(response, "NACK:Missing motor command", max_len); + if(next_arg == NULL) {return;} + + if (strcmp(next_arg, "SET") == 0) { + next_arg = get_next_arg(response, "NACK:Missing motor power", max_len); + if(next_arg == NULL) {return;} + if (!(isdigit((int)next_arg[0]) || (next_arg[0] == '-'))) { + append_str(response, "NACK:Invalid motor power", max_len); + return; + } + + long int output_val = strtol(next_arg, NULL, 10); + + // bounds check + if (output_val < MIN_MOTOR_VAL || output_val > MAX_MOTOR_VAL) { + append_str(response, "NACK:Invalid motor power", max_len); + return; + } + // Set motor power + output_set_power((uint8_t) output_num, (int16_t) output_val); + + append_str(response, "ACK", max_len); + return; + } else if (strcmp(next_arg, "GET?") == 0) { + // Get motor value + append_str(response, output_enabled((uint8_t)output_num)?"1":"0", max_len); + append_str(response, ":", max_len); + append_str(response, itoa(output_get_output((uint8_t)output_num), temp_str), max_len); + return; + } else if (strcmp(next_arg, "DISABLE") == 0) { + // Disable motor + output_disable((uint8_t)output_num); + + append_str(response, "ACK", max_len); + return; + } else if (strcmp(next_arg, "I?") == 0) { + append_str(response, itoa(output_get_current((uint8_t)output_num), temp_str), max_len); + return; + } else { + append_str(response, "NACK:Unknown motor command", max_len); + return; + } + } else if (strcmp(next_arg, "*IDN?") == 0) { + // Identifier string: manufacturer, board name, asset tag, version + append_str(response, "Student Robotics:" BOARD_NAME_SHORT ":", max_len); + append_str(response, serialnum, max_len); + append_str(response, ":" FW_VER, max_len); + return; + } else if (strcmp(next_arg, "*STATUS?") == 0) { + append_str(response, (output_data[0].in_fault)?"1":"0", max_len); + append_str(response, ",", max_len); + append_str(response, (output_data[1].in_fault)?"1":"0", max_len); + append_str(response, ":", max_len); + append_str(response, itoa(input_voltage, temp_str), max_len); + return; + } else if (strcmp(next_arg, "*RESET") == 0) { + outputs_reset(); + + append_str(response, "ACK", max_len); + return; + } else if (strcmp(next_arg, "*SYS") == 0) { + next_arg = get_next_arg(response, "NACK:Missing system command", max_len); + if(next_arg == NULL) {return;} + + if (strcmp(next_arg, "BOOTLOADER") == 0) { + // enter bootloader after sending ack + enter_bootloader_next_cycle(); + + append_str(response, "ACK\n\n", max_len); + return; + } + + append_str(response, "NACK:Invalid system command", max_len); + return; + } else if (strcmp(next_arg, "ECHO") == 0) { + next_arg = strtok(NULL, ":"); + + append_str(response, next_arg, max_len); + return; + } else { + append_str(response, "NACK:Unknown command: '", max_len); + append_str(response, next_arg, max_len); + append_str(response, "'", max_len); + return; + } + + // This should be unreachable + append_str(response, "NACK:Unknown error", max_len); + return; +} + +static char* itoa(int value, char* string) { + // string must be a buffer of at least 12 chars + // including stdio.h to get sprintf overflows the rom + char tmp[11]; + char* tmp_ptr = tmp; + char* sp = string; + unsigned int digit; + unsigned int remaining; + bool sign; + + if ( string == NULL ) { + return 0; + } + + sign = (value < 0); + if (sign) { + remaining = -value; + } else { + remaining = (unsigned int)value; + } + + while (remaining || tmp_ptr == tmp) { + digit = remaining % 10; + remaining /= 10; + *tmp_ptr = digit + '0'; + tmp_ptr++; + } + + if (sign) { + *sp = '-'; + sp++; + } + + // string is in reverse at this point + while (tmp_ptr > tmp) { + tmp_ptr--; + *sp = *tmp_ptr; + sp++; + } + *sp = '\0'; + + return string; +} + +void enter_bootloader_next_cycle(void) { + // Set the signature to enter bootloader at next reset + // the main loop will trigger a reset at the end of this transaction + set_bootloader_signature(BOOTLOADER_SIGNATURE); +} diff --git a/src/msg_handler.h b/src/msg_handler.h new file mode 100644 index 0000000..1ef8f1a --- /dev/null +++ b/src/msg_handler.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include + +#define bootloader_flag (BKP_DR1 & 0xFFFF) +#define BOOTLOADER_SIGNATURE 0xBEE5 + +void process_received_data(char new_data); +void handle_msg(char* buf, char* response, int max_len); +void enter_bootloader_next_cycle(void); + +static inline void set_bootloader_signature(uint32_t signature) { + pwr_disable_backup_domain_write_protect(); + // The backup registers are not cleared on reset + // They are 16 bit registers and register 1 is used to signal when + // the bootloader should be entered + BKP_DR1 = signature; + pwr_enable_backup_domain_write_protect(); +} diff --git a/src/output.c b/src/output.c new file mode 100644 index 0000000..53c210e --- /dev/null +++ b/src/output.c @@ -0,0 +1,199 @@ +#include "output.h" +#include "led.h" + +#include + +#include +#include +#include + +#define MOTOR_SPEED_COEFF 2 + +static const struct { + uint32_t INa; + uint32_t INb; + uint32_t ENa; + uint32_t ENb; + uint32_t PWM; + enum tim_oc_id timer_chan; +} output_pins[] = {{ + .INa = GPIO12, + .INb = GPIO13, + .ENa = GPIO14, + .ENb = GPIO15, + .PWM = GPIO_TIM2_CH2, + .timer_chan = TIM_OC2 +}, { + .INa = GPIO8, + .INb = GPIO9, + .ENa = GPIO10, + .ENb = GPIO11, + .PWM = GPIO_TIM2_CH1_ETR, + .timer_chan = TIM_OC1 +}}; + +output_t output_data[NUM_OUTPUTS] = { 0 }; + +static void setup_gpio(void) { + for (uint8_t i = 0; i < NUM_OUTPUTS; i++) { + // setup ctrl gpio + gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, output_pins[i].INa); + gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_PUSHPULL, output_pins[i].INb); + // Enable pins are pulled low by the H-bridge when in fault + gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, output_pins[i].ENa); + gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_OPENDRAIN, output_pins[i].ENb); + output_disable(i); + + // setup pwm pins + gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_2_MHZ, GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, output_pins[i].PWM); + } +} + +void output_init(void) { + for (uint8_t i = 0; i < NUM_OUTPUTS; i++) { + output_data[i].enabled = false; + output_data[i].value = 0; + output_data[i].in_fault = false; + output_data[i].current = 0; + } + setup_gpio(); + + rcc_periph_clock_enable(RCC_TIM2); + // Run the timer at 24MHz + timer_set_mode(TIM2, TIM_CR1_CKD_CK_INT, TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); + // Don't prescaler the timer clock, results in a ~12kHz PWM + timer_set_prescaler(TIM2, 1); + // Configure period to match available motor value range + timer_set_period(TIM2, (MOTOR_SPEED_COEFF * MAX_MOTOR_VAL)); + + for (uint8_t i = 0; i < NUM_OUTPUTS; i++) { + // Configure positive polarity output compare + timer_set_oc_mode(TIM2, output_pins[i].timer_chan, TIM_OCM_PWM1); + timer_set_oc_polarity_high(TIM2, output_pins[i].timer_chan); + + // Enable output compare outputs to physical pins + timer_enable_oc_preload(TIM2, output_pins[i].timer_chan); + timer_enable_oc_output(TIM2, output_pins[i].timer_chan); + } + + timer_enable_preload(TIM2); + timer_enable_counter(TIM2); +} + +void output_set_power(uint8_t output_num, int16_t output_val) { + if (!(output_num < NUM_OUTPUTS)) { + // skip invalid output numbers + return; + } + if (output_val < MIN_MOTOR_VAL || output_val > MAX_MOTOR_VAL) { + // skip invalid output values + return; + } + + if (!output_data[output_num].enabled) { + // enable output if it wasn't previously + gpio_set(GPIOB, output_pins[output_num].ENa); + gpio_set(GPIOB, output_pins[output_num].ENb); + + output_data[output_num].enabled = true; + } + + // set direction + if (output_val > 0) { // forward + gpio_set(GPIOB, output_pins[output_num].INa); + gpio_clear(GPIOB, output_pins[output_num].INb); + + // set speed + timer_set_oc_value(TIM2, output_pins[output_num].timer_chan, output_val * MOTOR_SPEED_COEFF); + } else if (output_val < 0) { // reverse + gpio_clear(GPIOB, output_pins[output_num].INa); + gpio_set(GPIOB, output_pins[output_num].INb); + + // set speed + timer_set_oc_value(TIM2, output_pins[output_num].timer_chan, -output_val * MOTOR_SPEED_COEFF); + } else if (output_val == 0) { // brake + gpio_clear(GPIOB, output_pins[output_num].INa); + gpio_clear(GPIOB, output_pins[output_num].INb); + } + + // store set speed + output_data[output_num].value = output_val; +} + +bool output_enabled(uint8_t output_num) { + if (!(output_num < NUM_OUTPUTS)) { + // skip invalid output numbers + return false; + } + + return output_data[output_num].enabled; +} + +int8_t output_get_output(uint8_t output_num) { + if (!(output_num < NUM_OUTPUTS)) { + // skip invalid output numbers + return 0; + } + + if (output_data[output_num].enabled) { + return output_data[output_num].value; + } else { + return 0; + } +} + +void output_disable(uint8_t output_num) { + if (!(output_num < NUM_OUTPUTS)) { + // skip invalid output numbers + return; + } + + output_data[output_num].enabled = false; + + gpio_clear(GPIOB, output_pins[output_num].ENa); + gpio_clear(GPIOB, output_pins[output_num].ENb); +} + +uint16_t output_get_current(uint8_t output_num) { + if (!(output_num < NUM_OUTPUTS)) { + // skip invalid output numbers + return 0; + } + + return output_data[output_num].current; +} + +void check_output_faults(void) { + for (uint8_t i = 0; i < NUM_OUTPUTS; i++) { + if (output_data[i].enabled) { + // The h-bridge drives the enable pin low when a fault occurs + if ( + (!gpio_get(GPIOB, output_pins[i].ENa)) + || (!gpio_get(GPIOB, output_pins[i].ENb)) + ) { + // A fault has occured on the output + output_data[i].in_fault = true; + led_set((i == 0)?(LED_M0_R):(LED_M1_R)); + } else { + output_data[i].in_fault = false; + led_clear((i == 0)?(LED_M0_R):(LED_M1_R)); + } + } else { + output_data[i].in_fault = false; + led_clear((i == 0)?(LED_M0_R):(LED_M1_R)); + } + } +} + +void outputs_reset(void) { + for (uint8_t i = 0; i < NUM_OUTPUTS; i++) { + output_disable(i); + output_data[i].in_fault = false; + output_data[i].current = 0; + } + + led_clear(LED_M0_R); + led_clear(LED_M0_B); + led_clear(LED_M1_R); + led_clear(LED_M1_B); +} diff --git a/src/output.h b/src/output.h new file mode 100644 index 0000000..afb2e37 --- /dev/null +++ b/src/output.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include "led.h" + +#define MAX_MOTOR_VAL 1000 +#define MIN_MOTOR_VAL (-MAX_MOTOR_VAL) +#define NUM_OUTPUTS 2 + +typedef struct { + bool enabled; + int8_t value; + bool in_fault; + uint16_t current; +} output_t; +// defined in output.c +extern output_t output_data[]; + +void output_init(void); + +void output_set_power(uint8_t output_num, int16_t output_val); +bool output_enabled(uint8_t output_num); +int8_t output_get_output(uint8_t output_num); +void output_disable(uint8_t output_num); +uint16_t output_get_current(uint8_t output_num); +void check_output_faults(void); +void outputs_reset(void); diff --git a/src/usart.c b/src/usart.c new file mode 100644 index 0000000..7a154f2 --- /dev/null +++ b/src/usart.c @@ -0,0 +1,45 @@ +#include "usart.h" + +#include +#include +#include +#include "libopencm3/stm32/rcc.h" +#include "libopencm3/stm32/gpio.h" +#include "libopencm3/stm32/usart.h" + +void usart_init(void) { + rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_USART1EN); + + gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_10_MHZ, + GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO_USART1_TX); + + usart_set_baudrate(USART1, 115200); + usart_set_databits(USART1, 8); + usart_set_stopbits(USART1, USART_STOPBITS_1); + usart_set_parity(USART1, USART_PARITY_NONE); + usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE); + usart_set_mode(USART1, USART_MODE_TX_RX); + + usart_enable(USART1); +} + +uint16_t usart_get_char(void) { + // Wait until the data is ready to be received. + while ((USART_SR(USART1) & USART_SR_RXNE) == 0)iwdg_reset(); + return usart_recv(USART1); +} + +int usart_send_string(char* str) { + uint16_t len = strlen(str); + + for (uint16_t i=0; i + +void usart_init(void); + +uint16_t usart_get_char(void); +int usart_send_string(char* str); diff --git a/test.c b/test.c deleted file mode 100644 index 685ea15..0000000 --- a/test.c +++ /dev/null @@ -1,64 +0,0 @@ -#include -#include - -#include -#include - -#include "led.h" -#include "output.h" - -#define DELAY 3 - -#define delay(x) do { for (int i = 0; i < x * 100000; i++) \ - __asm__("nop"); \ - } while(0) - -void init(void) { - rcc_clock_setup_in_hse_8mhz_out_24mhz(); - - rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_IOPAEN); - rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_IOPBEN); - rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_IOPCEN); - led_init(); - output_init(); -} - -void flash(int led) { - led_set(led); - delay(DELAY); - led_clear(led); - delay(DELAY); -} - -int main(void) { - int i; - - init(); - output_speed(0, 50); - output_speed(1, 50); - - while (1) { - flash(LED_M0_R); - flash(LED_M0_B); - flash(LED_M1_R); - flash(LED_M1_B); - - output_enable(0); - output_direction(0, DIR_FWD); - delay(DELAY*2); - output_direction(0, DIR_REV); - delay(DELAY*2); - output_disable(0); - delay(DELAY); - - output_enable(1); - output_direction(1, DIR_FWD); - delay(DELAY*2); - output_direction(1, DIR_REV); - delay(DELAY*2); - output_disable(1); - delay(DELAY); - } - - return 0; -} diff --git a/usart.c b/usart.c deleted file mode 100644 index 066c16a..0000000 --- a/usart.c +++ /dev/null @@ -1,41 +0,0 @@ -#include "usart.h" -#include "output.h" - -#include "libopencm3/stm32/f1/rcc.h" -#include "libopencm3/stm32/f1/gpio.h" -#include "libopencm3/stm32/usart.h" -#include "libopencm3/cm3/nvic.h" -#include "errno.h" - -void usart_init() { - rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_USART1EN); - - gpio_set_mode(GPIOA, GPIO_MODE_OUTPUT_10_MHZ, \ - GPIO_CNF_OUTPUT_ALTFN_PUSHPULL, GPIO_USART1_TX); - - usart_set_baudrate(USART1, 1000000); - usart_set_databits(USART1, 8); - usart_set_stopbits(USART1, USART_STOPBITS_1); - usart_set_parity(USART1, USART_PARITY_NONE); - usart_set_flow_control(USART1, USART_FLOWCONTROL_NONE); - usart_set_mode(USART1, USART_MODE_TX_RX); - - usart_enable(USART1); -} - -int usart_get_char(void) { - return usart_recv_blocking(USART1); -} - -int _write(int file, char *ptr, int len) { - int i; - - if (file == 1) { - for (i=0; i +## Copyright (C) 2010 Piotr Esden-Tempski +## +## This library is free software: you can redistribute it and/or modify +## it under the terms of the GNU Lesser General Public License as published by +## the Free Software Foundation, either version 3 of the License, or +## (at your option) any later version. +## +## This library is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU Lesser General Public License for more details. +## +## You should have received a copy of the GNU Lesser General Public License +## along with this library. If not, see . +## + +SERIAL_DEV ?= /dev/ttyUSB0 + +LIBNAME = opencm3_stm32f1 +DEFS += -DSTM32F1 + +FP_FLAGS ?= -msoft-float +ARCH_FLAGS = -mthumb -mcpu=cortex-m3 $(FP_FLAGS) -mfix-cortex-m3-ldrd + +################################################################################ +# OpenOCD specific variables + +OOCD ?= openocd +OOCD_INTERFACE ?= flossjtag +OOCD_TARGET ?= stm32f1x + +# Be silent per default, but 'make V=1' will show all compiler calls. +ifneq ($(V),1) +Q := @ +NULL := 2>/dev/null +endif + +############################################################################### +# Executables + +PREFIX ?= arm-none-eabi- + +CC := $(PREFIX)gcc +CXX := $(PREFIX)g++ +LD := $(PREFIX)gcc +AR := $(PREFIX)ar +AS := $(PREFIX)as +OBJCOPY := $(PREFIX)objcopy +OBJDUMP := $(PREFIX)objdump +GDB := $(PREFIX)gdb +STFLASH = $(shell which st-flash) +STM32FLASH = $(shell which stm32flash) +STYLECHECK := /checkpatch.pl +STYLECHECKFLAGS := --no-tree -f --terse --mailback +STYLECHECKFILES := $(shell find . -name '*.[ch]') +OPT := -Os +DEBUG := -ggdb3 +CSTD ?= -std=c99 + +############################################################################### +# Source files + +OBJS += $(BINARY).o + +ifeq ($(strip $(OPENCM3_DIR)),) +# user has not specified the library path, so we try to detect it + +# where we search for the library +LIBPATHS := ./libopencm3 ../libopencm3 + +OPENCM3_DIR := $(wildcard $(LIBPATHS:=/locm3.sublime-project)) +OPENCM3_DIR := $(firstword $(dir $(OPENCM3_DIR))) + +ifeq ($(strip $(OPENCM3_DIR)),) +$(warning Cannot find libopencm3 library in the standard search paths.) +$(error Please specify it through OPENCM3_DIR variable!) +endif +endif + +ifeq ($(V),1) +$(info Using $(OPENCM3_DIR) path to library) +endif + +define ERR_DEVICE_LDSCRIPT_CONFLICT +You can either specify DEVICE=blah, and have the LDSCRIPT generated, +or you can provide LDSCRIPT, and ensure CPPFLAGS, LDFLAGS and LDLIBS +all contain the correct values for the target you wish to use. +You cannot provide both! +endef + +ifeq ($(strip $(DEVICE)),) +# Old style, assume LDSCRIPT exists +DEFS += -I$(OPENCM3_DIR)/include +LDFLAGS += -L$(OPENCM3_DIR)/lib +LDLIBS += -l$(LIBNAME) +LDSCRIPT ?= $(OPENCM3_DIR)/../utils/$(BINARY).ld +else +# New style, assume device is provided, and we're generating the rest. +ifneq ($(strip $(LDSCRIPT)),) +$(error $(ERR_DEVICE_LDSCRIPT_CONFLICT)) +endif +include $(OPENCM3_DIR)/mk/genlink-config.mk +endif + +OPENCM3_SCRIPT_DIR = $(OPENCM3_DIR)/scripts +SCRIPT_DIR = $(OPENCM3_DIR)/../scripts + +############################################################################### +# C flags + +TGT_CFLAGS += $(OPT) $(CSTD) $(DEBUG) +TGT_CFLAGS += $(ARCH_FLAGS) +TGT_CFLAGS += -Wextra -Wshadow -Wimplicit-function-declaration +TGT_CFLAGS += -Wredundant-decls -Wmissing-prototypes -Wstrict-prototypes +TGT_CFLAGS += -fno-common -ffunction-sections -fdata-sections + +############################################################################### +# C++ flags + +TGT_CXXFLAGS += $(OPT) $(CXXSTD) $(DEBUG) +TGT_CXXFLAGS += $(ARCH_FLAGS) +TGT_CXXFLAGS += -Wextra -Wshadow -Wredundant-decls -Weffc++ +TGT_CXXFLAGS += -fno-common -ffunction-sections -fdata-sections + +############################################################################### +# C & C++ preprocessor common flags + +TGT_CPPFLAGS += -MD +TGT_CPPFLAGS += -Wall -Wundef +TGT_CPPFLAGS += $(DEFS) + +############################################################################### +# Linker flags + +TGT_LDFLAGS += --static -nostartfiles +TGT_LDFLAGS += -T$(LDSCRIPT) +TGT_LDFLAGS += $(ARCH_FLAGS) $(DEBUG) +TGT_LDFLAGS += -Wl,-Map=$(*).map -Wl,--cref +TGT_LDFLAGS += -Wl,--gc-sections -Wl,--print-memory-usage +ifeq ($(V),99) +TGT_LDFLAGS += -Wl,--print-gc-sections +endif + +############################################################################### +# Used libraries + +LDLIBS += -Wl,--start-group -lc -lgcc -lnosys -Wl,--end-group + +############################################################################### +############################################################################### +############################################################################### + +.SUFFIXES: .elf .bin .hex .srec .list .map .images +.SECONDEXPANSION: +.SECONDARY: + +# Either verify the user provided LDSCRIPT exists, or generate it. +ifeq ($(strip $(DEVICE)),) +$(LDSCRIPT): + ifeq (,$(wildcard $(LDSCRIPT))) + $(error Unable to find specified linker script: $(LDSCRIPT)) + endif +else +include $(OPENCM3_DIR)/mk/genlink-rules.mk +endif + +$(OPENCM3_DIR)/lib/lib$(LIBNAME).a: +ifeq (,$(wildcard $@)) + $(warning $(LIBNAME).a not found, attempting to rebuild in $(OPENCM3_DIR)) + $(MAKE) -C $(OPENCM3_DIR) +endif + +%.images: %.bin %.hex %.srec %.list %.map + @printf "*** $* images generated ***\n" + +%.bin: %.elf + @printf " OBJCOPY $(*).bin\n" +# pad binary out to full size of flash + $(Q)$(OBJCOPY) -Obinary $(*).elf $(*).bin + +%.hex: %.elf + @printf " OBJCOPY $(*).hex\n" + $(Q)$(OBJCOPY) -Oihex $(*).elf $(*).hex + +%.srec: %.elf + @printf " OBJCOPY $(*).srec\n" + $(Q)$(OBJCOPY) -Osrec $(*).elf $(*).srec + +%.list: %.elf + @printf " OBJDUMP $(*).list\n" + $(Q)$(OBJDUMP) -S $(*).elf > $(*).list + +%.elf %.map: $(OBJS) $(LDSCRIPT) $(OPENCM3_DIR)/lib/lib$(LIBNAME).a + @printf " LD $(*).elf\n" + $(Q)$(LD) $(TGT_LDFLAGS) $(LDFLAGS) $(OBJS) $(LDLIBS) -o $(*).elf + +%.o: %.c + @printf " CC $(*).c\n" + $(Q)$(CC) $(TGT_CFLAGS) $(CFLAGS) $(TGT_CPPFLAGS) $(CPPFLAGS) -o $(*).o -c $(*).c + +%.o: %.cxx + @printf " CXX $(*).cxx\n" + $(Q)$(CXX) $(TGT_CXXFLAGS) $(CXXFLAGS) $(TGT_CPPFLAGS) $(CPPFLAGS) -o $(*).o -c $(*).cxx + +%.o: %.cpp + @printf " CXX $(*).cpp\n" + $(Q)$(CXX) $(TGT_CXXFLAGS) $(CXXFLAGS) $(TGT_CPPFLAGS) $(CPPFLAGS) -o $(*).o -c $(*).cpp + + +# the cat is due to multithreaded nature - we like to have consistent chunks of text on the output +%.stylecheck: % + $(Q)$(OPENCM3_SCRIPT_DIR)$(STYLECHECK) $(STYLECHECKFLAGS) $* > $*.stylecheck; \ + if [ -s $*.stylecheck ]; then \ + cat $*.stylecheck; \ + else \ + rm -f $*.stylecheck; \ + fi; + +%.styleclean: + $(Q)rm -f $*.stylecheck; + + +%.stlink-flash: %.bin + @printf " FLASH $<\n" + $(STFLASH) write $(*).bin 0x8000000 + +ifeq ($(BMP_PORT),) +ifeq ($(OOCD_FILE),) +%.flash: %.elf + @printf " FLASH $<\n" + (echo "halt; program $(realpath $(*).elf) verify reset" | nc -4 localhost 4444 2>/dev/null) || \ + $(OOCD) -f interface/$(OOCD_INTERFACE).cfg \ + -f target/$(OOCD_TARGET).cfg \ + -c "program $(*).elf verify reset exit" \ + $(NULL) +else +%.flash: %.elf + @printf " FLASH $<\n" + (echo "halt; program $(realpath $(*).elf) verify reset" | nc -4 localhost 4444 2>/dev/null) || \ + $(OOCD) -f $(OOCD_FILE) \ + -c "program $(*).elf verify reset exit" \ + $(NULL) +endif +else +%.flash: %.elf + @printf " GDB $(*).elf (flash)\n" + $(GDB) --batch \ + -ex 'target extended-remote $(BMP_PORT)' \ + -x $(SCRIPT_DIR)/black_magic_probe_flash.scr \ + $(*).elf +endif + +%.stm32flash: %.bin + $(STM32FLASH) -b 115200 -w $(*).bin -v -R $(SERIAL_DEV) diff --git a/stm32-mcv4.ld b/utils/stm32-mcv4.ld similarity index 99% rename from stm32-mcv4.ld rename to utils/stm32-mcv4.ld index ec1afb7..70b2a03 100644 --- a/stm32-mcv4.ld +++ b/utils/stm32-mcv4.ld @@ -42,8 +42,6 @@ SECTIONS *(.vectors) /* Vector table */ *(.text*) /* Program code */ . = ALIGN(4); - *(.fwver) - . = ALIGN(4); *(.rodata*) /* Read-only data */ . = ALIGN(4); } >rom