Initial commit
This commit is contained in:
commit
b0d059fb24
34 changed files with 18172 additions and 0 deletions
192
Makefile
Normal file
192
Makefile
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
|
||||
########################################################################################################################
|
||||
# Dependency directories
|
||||
########################################################################################################################
|
||||
|
||||
MUSL_DIR ?= upstream/musl
|
||||
|
||||
########################################################################################################################
|
||||
# Algorithm parameters
|
||||
########################################################################################################################
|
||||
|
||||
# - none -
|
||||
|
||||
########################################################################################################################
|
||||
# High-level build parameters
|
||||
########################################################################################################################
|
||||
|
||||
DEBUG ?= 1
|
||||
OPT ?= 0
|
||||
|
||||
BUILDDIR ?= build
|
||||
BINARY := main.elf
|
||||
LDSCRIPT := generic_stm32.ld
|
||||
DEVICE := STM32F103xB
|
||||
|
||||
|
||||
########################################################################################################################
|
||||
# Sources
|
||||
########################################################################################################################
|
||||
|
||||
ASM_SOURCES := startup.s
|
||||
|
||||
C_SOURCES := src/main.c
|
||||
|
||||
CPP_SOURCES := # - none -
|
||||
|
||||
MUSL_SOURCES := # - none -
|
||||
MUSL_SOURCES := $(addprefix $(MUSL_DIR)/src/,$(MUSL_SOURCES))
|
||||
|
||||
C_SOURCES += $(MUSL_SOURCES)
|
||||
|
||||
|
||||
########################################################################################################################
|
||||
# Low-level build parameters
|
||||
########################################################################################################################
|
||||
|
||||
PREFIX ?= arm-none-eabi-
|
||||
|
||||
HOSTCC := gcc
|
||||
CC := $(PREFIX)gcc
|
||||
CPP := $(PREFIX)cpp
|
||||
CXX := $(PREFIX)g++
|
||||
LD := $(PREFIX)gcc
|
||||
AR := $(PREFIX)ar
|
||||
AS := $(PREFIX)as
|
||||
SIZE := $(PREFIX)size
|
||||
NM := $(PREFIX)nm
|
||||
OBJCOPY := $(PREFIX)objcopy
|
||||
OBJDUMP := $(PREFIX)objdump
|
||||
GDB := $(PREFIX)gdb
|
||||
|
||||
HOST_CC ?= $(HOST_PREFIX)gcc
|
||||
HOST_CXX ?= $(HOST_PREFIX)g++
|
||||
HOST_LD ?= $(HOST_PREFIX)gcc
|
||||
HOST_AR ?= $(HOST_PREFIX)ar
|
||||
HOST_AS ?= $(HOST_PREFIX)as
|
||||
HOST_OBJCOPY ?= $(HOST_PREFIX)objcopy
|
||||
HOST_OBJDUMP ?= $(HOST_PREFIX)objdump
|
||||
|
||||
PYTHON3 ?= python3
|
||||
DOT ?= dot
|
||||
|
||||
MUSL_DIR_ABS := $(abspath $(MUSL_DIR))
|
||||
CMSIS_DEVICE_DIR_ABS := $(abspath $(CMSIS_DEVICE_DIR))
|
||||
|
||||
DEVICE_FAMILY := $(shell echo $(DEVICE) | grep -Eio 'STM32[a-z]{1,2}[0-9]'|cut -c 6-)
|
||||
DEVICE_DEFINES := -DSTM32$(DEVICE_FAMILY) $(addprefix -D,$(shell cat stm32_buildinfo.defines))
|
||||
|
||||
ARCH_FLAGS ?= -mthumb -mcpu=cortex-m0 -mfloat-abi=soft
|
||||
SYSTEM_FLAGS ?= -nostdlib -ffreestanding -nostartfiles
|
||||
|
||||
COMMON_CFLAGS += -I$(abspath include)
|
||||
COMMON_CFLAGS += -I$(BUILDDIR)
|
||||
|
||||
CFLAGS += -I$(abspath tools/musl_include_shims)
|
||||
CFLAGS += -I$(abspath upstream/libusb_stm32/inc)
|
||||
CFLAGS += -I$(CMSIS_DEVICE_DIR_ABS)/Include
|
||||
|
||||
CFLAGS += $(ARCH_FLAGS) $(SYSTEM_FLAGS)
|
||||
CFLAGS += -fno-common -ffunction-sections -fdata-sections
|
||||
|
||||
COMMON_CFLAGS += -O$(OPT) -std=gnu2x -g
|
||||
COMMON_CFLAGS += $(DEVICE_DEFINES)
|
||||
COMMON_CFLAGS += -DDEBUG=$(DEBUG)
|
||||
|
||||
HOST_CFLAGS += $(COMMON_CFLAGS)
|
||||
|
||||
# for musl
|
||||
CFLAGS += -Dhidden=
|
||||
|
||||
SIM_CFLAGS += -lm -DSIMULATION
|
||||
SIM_CFLAGS += -Wall -Wextra -Wpedantic -Wshadow -Wimplicit-function-declaration -Wundef -Wno-unused-parameter
|
||||
|
||||
INT_CFLAGS += -Wall -Wextra -Wpedantic -Wshadow -Wimplicit-function-declaration -Wundef -Wno-unused-parameter
|
||||
INT_CFLAGS += -Wredundant-decls -Wmissing-prototypes -Wstrict-prototypes
|
||||
|
||||
CXXFLAGS += -Os -g
|
||||
CXXFLAGS += $(ARCH_FLAGS) $(SYSTEM_FLAGS)
|
||||
CXXFLAGS += -fno-common -ffunction-sections -fdata-sections
|
||||
CXXFLAGS += -Wall -Wextra -Wshadow -Wundef -Wredundant-decls
|
||||
CXXFLAGS += -I.
|
||||
|
||||
LDFLAGS += $(ARCH_FLAGS) $(SYSTEM_FLAGS)
|
||||
|
||||
LIBS += -lgcc
|
||||
#LDFLAGS += -Wl,--gc-sections
|
||||
|
||||
LINKMEM_FLAGS ?= --trim-stubs=startup.o --trace-sections .isr_vector --highlight-subdirs $(BUILDDIR)
|
||||
|
||||
OBJS := $(addprefix $(BUILDDIR)/,$(C_SOURCES:.c=.o) $(CXX_SOURCES:.cpp=.o) $(ASM_SOURCES:.s=.o))
|
||||
ALL_OBJS := $(OBJS)
|
||||
ALL_OBJS += $(BUILDDIR)/system.o
|
||||
# Add generated source here.
|
||||
|
||||
########################################################################################################################
|
||||
# Rules
|
||||
########################################################################################################################
|
||||
|
||||
all: binsize
|
||||
|
||||
.PHONY: binsize
|
||||
binsize: $(BUILDDIR)/$(BINARY) $(BUILDDIR)/$(BINARY:.elf=-symbol-sizes.pdf)
|
||||
$(LD) -T$(LDSCRIPT) $(LDFLAGS) -Wl,--print-memory-usage -o /dev/null $(ALL_OBJS) $(LIBS)
|
||||
@echo
|
||||
@echo "▐▬▬▬▌ SyMbOL sIzE HiGhScORe LiSt ▐▬▬▬▌"
|
||||
$(NM) --print-size --size-sort --radix=d $< | tail -n 20
|
||||
|
||||
.PRECIOUS: $(BUILDDIR)/$(BINARY)
|
||||
$(BUILDDIR)/$(BINARY) $(BUILDDIR)/$(BINARY:.elf=.map) &: $(ALL_OBJS)
|
||||
$(LD) -T$(LDSCRIPT) $(LDFLAGS) -o $@ -Wl,-Map=$(BUILDDIR)/$(BINARY:.elf=.map) $(ALL_OBJS) $(LIBS)
|
||||
|
||||
build/$(BINARY:.elf=-symbol-sizes.dot): $(ALL_OBJS)
|
||||
$(PYTHON3) tools/linkmem.py $(LINKMEM_FLAGS) $(LD) -T$(LDSCRIPT) $(LDFLAGS) $^ $(LIBS) > $@
|
||||
|
||||
%.pdf: %.dot
|
||||
$(DOT) -T pdf $< -o $@
|
||||
|
||||
%.dot: %.elf
|
||||
r2 -a arm -qc 'aa;agRd' $< 2>/dev/null >$@
|
||||
|
||||
$(BUILDDIR)/src/%.o: src/%.s
|
||||
mkdir -p $(@D)
|
||||
$(CC) $(COMMON_CFLAGS) $(CFLAGS) $(INT_CFLAGS) -o $@ -c $<
|
||||
|
||||
$(BUILDDIR)/src/%.o: src/%.c
|
||||
mkdir -p $(@D)
|
||||
$(CC) $(COMMON_CFLAGS) $(CFLAGS) $(INT_CFLAGS) -o $@ -c $<
|
||||
|
||||
$(BUILDDIR)/src/%.o: src/%.cpp
|
||||
mkdir -p $(@D)
|
||||
$(CXX) $(CXXFLAGS) -o $@ -c $<
|
||||
|
||||
$(BUILDDIR)/%.o: %.c
|
||||
mkdir -p $(@D)
|
||||
$(CC) $(COMMON_CFLAGS) $(CFLAGS) $(EXT_CFLAGS) -o $@ -c $<
|
||||
|
||||
$(BUILDDIR)/%.o: %.s
|
||||
mkdir -p $(@D)
|
||||
$(CC) $(COMMON_CFLAGS) $(CFLAGS) $(EXT_CFLAGS) -o $@ -c $<
|
||||
|
||||
venv:
|
||||
test -d venv || python3 -m venv --system-site-packages venv
|
||||
source venv/bin/activate && pip install cxxfilt pyelftools libarchive matplotlib
|
||||
|
||||
clean:
|
||||
rm -rf $(BUILDDIR)/src
|
||||
rm -f $(BUILDDIR)/**.o
|
||||
rm -f $(BUILDDIR)/$(BINARY)
|
||||
rm -f $(BUILDDIR)/$(BINARY:.elf=.map)
|
||||
rm -f $(BUILDDIR)/$(BINARY:.elf=-symbol-sizes.dot)
|
||||
rm -f $(BUILDDIR)/$(BINARY:.elf=-symbol-sizes.pdf)
|
||||
rm -f $(BUILDDIR)/crc32_test
|
||||
rm -f $(BUILDDIR)/microcobs_test_sg
|
||||
rm -f $(BUILDDIR)/microcobs_test
|
||||
rm -f $(BUILDDIR)/microcobs_decode_test
|
||||
|
||||
mrproper: clean
|
||||
rm -rf build
|
||||
|
||||
.PHONY: clean mrproper
|
||||
|
||||
-include $(OBJS:.o=.d)
|
||||
125
generic_stm32.ld
Normal file
125
generic_stm32.ld
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
/* Entry Point */
|
||||
ENTRY(Reset_Handler)
|
||||
|
||||
/* Generate a link error if heap and stack don't fit into RAM */
|
||||
_Min_Heap_Size = 0x200; /* required amount of heap */
|
||||
_Min_Stack_Size = 0x400; /* required amount of stack */
|
||||
|
||||
/* Specify the memory areas */
|
||||
MEMORY
|
||||
{
|
||||
INCLUDE memory_map.ldi
|
||||
}
|
||||
|
||||
/* Highest address of the user mode stack */
|
||||
PROVIDE(_estack = ORIGIN(RAM) + LENGTH(RAM));
|
||||
|
||||
/* Define output sections */
|
||||
SECTIONS
|
||||
{
|
||||
/* The startup code goes first into FLASH */
|
||||
.isr_vector :
|
||||
{
|
||||
. = ALIGN(4);
|
||||
KEEP(*(.isr_vector)) /* Startup code */
|
||||
. = ALIGN(4);
|
||||
} >FLASH
|
||||
|
||||
/* The program code and other data goes into FLASH */
|
||||
.text :
|
||||
{
|
||||
. = ALIGN(4);
|
||||
*(.text) /* .text sections (code) */
|
||||
*(.text*) /* .text* sections (code) */
|
||||
*(.glue_7) /* glue arm to thumb code */
|
||||
*(.glue_7t) /* glue thumb to arm code */
|
||||
*(.eh_frame)
|
||||
|
||||
KEEP (*(.init))
|
||||
KEEP (*(.fini))
|
||||
|
||||
. = ALIGN(4);
|
||||
_etext = .; /* define a global symbols at end of code */
|
||||
} >FLASH
|
||||
|
||||
/* Constant data goes into FLASH */
|
||||
.rodata :
|
||||
{
|
||||
. = ALIGN(4);
|
||||
*(.rodata) /* .rodata sections (constants, strings, etc.) */
|
||||
*(.rodata*) /* .rodata* sections (constants, strings, etc.) */
|
||||
. = ALIGN(4);
|
||||
} >FLASH
|
||||
|
||||
.ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH
|
||||
.ARM : {
|
||||
__exidx_start = .;
|
||||
*(.ARM.exidx*)
|
||||
__exidx_end = .;
|
||||
} >FLASH
|
||||
|
||||
.preinit_array :
|
||||
{
|
||||
PROVIDE_HIDDEN (__preinit_array_start = .);
|
||||
KEEP (*(.preinit_array*))
|
||||
PROVIDE_HIDDEN (__preinit_array_end = .);
|
||||
} >FLASH
|
||||
.init_array :
|
||||
{
|
||||
PROVIDE_HIDDEN (__init_array_start = .);
|
||||
KEEP (*(SORT(.init_array.*)))
|
||||
KEEP (*(.init_array*))
|
||||
PROVIDE_HIDDEN (__init_array_end = .);
|
||||
} >FLASH
|
||||
.fini_array :
|
||||
{
|
||||
PROVIDE_HIDDEN (__fini_array_start = .);
|
||||
KEEP (*(SORT(.fini_array.*)))
|
||||
KEEP (*(.fini_array*))
|
||||
PROVIDE_HIDDEN (__fini_array_end = .);
|
||||
} >FLASH
|
||||
|
||||
/* used by the startup to initialize data */
|
||||
_sidata = LOADADDR(.data);
|
||||
|
||||
/* Initialized data sections goes into RAM, load LMA copy after code */
|
||||
.data :
|
||||
{
|
||||
. = ALIGN(4);
|
||||
_sdata = .; /* create a global symbol at data start */
|
||||
*(.data) /* .data sections */
|
||||
*(.data*) /* .data* sections */
|
||||
|
||||
. = ALIGN(4);
|
||||
_edata = .; /* define a global symbol at data end */
|
||||
} >RAM AT> FLASH
|
||||
|
||||
/* Uninitialized data section */
|
||||
. = ALIGN(4);
|
||||
.bss :
|
||||
{
|
||||
/* This is used by the startup in order to initialize the .bss secion */
|
||||
_sbss = .; /* define a global symbol at bss start */
|
||||
__bss_start__ = _sbss;
|
||||
*(.bss)
|
||||
*(.bss*)
|
||||
*(COMMON)
|
||||
|
||||
. = ALIGN(4);
|
||||
_ebss = .; /* define a global symbol at bss end */
|
||||
__bss_end__ = _ebss;
|
||||
} >RAM
|
||||
|
||||
/* User_heap_stack section, used to check that there is enough RAM left */
|
||||
._user_heap_stack :
|
||||
{
|
||||
. = ALIGN(8);
|
||||
PROVIDE ( end = . );
|
||||
PROVIDE ( _end = . );
|
||||
. = . + _Min_Heap_Size;
|
||||
. = . + _Min_Stack_Size;
|
||||
. = ALIGN(8);
|
||||
} >RAM
|
||||
|
||||
.ARM.attributes 0 : { *(.ARM.attributes) }
|
||||
}
|
||||
283
include/cmsis_compiler.h
Normal file
283
include/cmsis_compiler.h
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
/**************************************************************************//**
|
||||
* @file cmsis_compiler.h
|
||||
* @brief CMSIS compiler generic header file
|
||||
* @version V5.1.0
|
||||
* @date 09. October 2018
|
||||
******************************************************************************/
|
||||
/*
|
||||
* Copyright (c) 2009-2018 Arm Limited. All rights reserved.
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the License); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef __CMSIS_COMPILER_H
|
||||
#define __CMSIS_COMPILER_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/*
|
||||
* Arm Compiler 4/5
|
||||
*/
|
||||
#if defined ( __CC_ARM )
|
||||
#include "cmsis_armcc.h"
|
||||
|
||||
|
||||
/*
|
||||
* Arm Compiler 6.6 LTM (armclang)
|
||||
*/
|
||||
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050) && (__ARMCC_VERSION < 6100100)
|
||||
#include "cmsis_armclang_ltm.h"
|
||||
|
||||
/*
|
||||
* Arm Compiler above 6.10.1 (armclang)
|
||||
*/
|
||||
#elif defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6100100)
|
||||
#include "cmsis_armclang.h"
|
||||
|
||||
|
||||
/*
|
||||
* GNU Compiler
|
||||
*/
|
||||
#elif defined ( __GNUC__ )
|
||||
#include "cmsis_gcc.h"
|
||||
|
||||
|
||||
/*
|
||||
* IAR Compiler
|
||||
*/
|
||||
#elif defined ( __ICCARM__ )
|
||||
#include <cmsis_iccarm.h>
|
||||
|
||||
|
||||
/*
|
||||
* TI Arm Compiler
|
||||
*/
|
||||
#elif defined ( __TI_ARM__ )
|
||||
#include <cmsis_ccs.h>
|
||||
|
||||
#ifndef __ASM
|
||||
#define __ASM __asm
|
||||
#endif
|
||||
#ifndef __INLINE
|
||||
#define __INLINE inline
|
||||
#endif
|
||||
#ifndef __STATIC_INLINE
|
||||
#define __STATIC_INLINE static inline
|
||||
#endif
|
||||
#ifndef __STATIC_FORCEINLINE
|
||||
#define __STATIC_FORCEINLINE __STATIC_INLINE
|
||||
#endif
|
||||
#ifndef __NO_RETURN
|
||||
#define __NO_RETURN __attribute__((noreturn))
|
||||
#endif
|
||||
#ifndef __USED
|
||||
#define __USED __attribute__((used))
|
||||
#endif
|
||||
#ifndef __WEAK
|
||||
#define __WEAK __attribute__((weak))
|
||||
#endif
|
||||
#ifndef __PACKED
|
||||
#define __PACKED __attribute__((packed))
|
||||
#endif
|
||||
#ifndef __PACKED_STRUCT
|
||||
#define __PACKED_STRUCT struct __attribute__((packed))
|
||||
#endif
|
||||
#ifndef __PACKED_UNION
|
||||
#define __PACKED_UNION union __attribute__((packed))
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT32 /* deprecated */
|
||||
struct __attribute__((packed)) T_UINT32 { uint32_t v; };
|
||||
#define __UNALIGNED_UINT32(x) (((struct T_UINT32 *)(x))->v)
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT16_WRITE
|
||||
__PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
|
||||
#define __UNALIGNED_UINT16_WRITE(addr, val) (void)((((struct T_UINT16_WRITE *)(void*)(addr))->v) = (val))
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT16_READ
|
||||
__PACKED_STRUCT T_UINT16_READ { uint16_t v; };
|
||||
#define __UNALIGNED_UINT16_READ(addr) (((const struct T_UINT16_READ *)(const void *)(addr))->v)
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT32_WRITE
|
||||
__PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
|
||||
#define __UNALIGNED_UINT32_WRITE(addr, val) (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT32_READ
|
||||
__PACKED_STRUCT T_UINT32_READ { uint32_t v; };
|
||||
#define __UNALIGNED_UINT32_READ(addr) (((const struct T_UINT32_READ *)(const void *)(addr))->v)
|
||||
#endif
|
||||
#ifndef __ALIGNED
|
||||
#define __ALIGNED(x) __attribute__((aligned(x)))
|
||||
#endif
|
||||
#ifndef __RESTRICT
|
||||
#define __RESTRICT __restrict
|
||||
#endif
|
||||
#ifndef __COMPILER_BARRIER
|
||||
#warning No compiler specific solution for __COMPILER_BARRIER. __COMPILER_BARRIER is ignored.
|
||||
#define __COMPILER_BARRIER() (void)0
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
* TASKING Compiler
|
||||
*/
|
||||
#elif defined ( __TASKING__ )
|
||||
/*
|
||||
* The CMSIS functions have been implemented as intrinsics in the compiler.
|
||||
* Please use "carm -?i" to get an up to date list of all intrinsics,
|
||||
* Including the CMSIS ones.
|
||||
*/
|
||||
|
||||
#ifndef __ASM
|
||||
#define __ASM __asm
|
||||
#endif
|
||||
#ifndef __INLINE
|
||||
#define __INLINE inline
|
||||
#endif
|
||||
#ifndef __STATIC_INLINE
|
||||
#define __STATIC_INLINE static inline
|
||||
#endif
|
||||
#ifndef __STATIC_FORCEINLINE
|
||||
#define __STATIC_FORCEINLINE __STATIC_INLINE
|
||||
#endif
|
||||
#ifndef __NO_RETURN
|
||||
#define __NO_RETURN __attribute__((noreturn))
|
||||
#endif
|
||||
#ifndef __USED
|
||||
#define __USED __attribute__((used))
|
||||
#endif
|
||||
#ifndef __WEAK
|
||||
#define __WEAK __attribute__((weak))
|
||||
#endif
|
||||
#ifndef __PACKED
|
||||
#define __PACKED __packed__
|
||||
#endif
|
||||
#ifndef __PACKED_STRUCT
|
||||
#define __PACKED_STRUCT struct __packed__
|
||||
#endif
|
||||
#ifndef __PACKED_UNION
|
||||
#define __PACKED_UNION union __packed__
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT32 /* deprecated */
|
||||
struct __packed__ T_UINT32 { uint32_t v; };
|
||||
#define __UNALIGNED_UINT32(x) (((struct T_UINT32 *)(x))->v)
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT16_WRITE
|
||||
__PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
|
||||
#define __UNALIGNED_UINT16_WRITE(addr, val) (void)((((struct T_UINT16_WRITE *)(void *)(addr))->v) = (val))
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT16_READ
|
||||
__PACKED_STRUCT T_UINT16_READ { uint16_t v; };
|
||||
#define __UNALIGNED_UINT16_READ(addr) (((const struct T_UINT16_READ *)(const void *)(addr))->v)
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT32_WRITE
|
||||
__PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
|
||||
#define __UNALIGNED_UINT32_WRITE(addr, val) (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT32_READ
|
||||
__PACKED_STRUCT T_UINT32_READ { uint32_t v; };
|
||||
#define __UNALIGNED_UINT32_READ(addr) (((const struct T_UINT32_READ *)(const void *)(addr))->v)
|
||||
#endif
|
||||
#ifndef __ALIGNED
|
||||
#define __ALIGNED(x) __align(x)
|
||||
#endif
|
||||
#ifndef __RESTRICT
|
||||
#warning No compiler specific solution for __RESTRICT. __RESTRICT is ignored.
|
||||
#define __RESTRICT
|
||||
#endif
|
||||
#ifndef __COMPILER_BARRIER
|
||||
#warning No compiler specific solution for __COMPILER_BARRIER. __COMPILER_BARRIER is ignored.
|
||||
#define __COMPILER_BARRIER() (void)0
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
* COSMIC Compiler
|
||||
*/
|
||||
#elif defined ( __CSMC__ )
|
||||
#include <cmsis_csm.h>
|
||||
|
||||
#ifndef __ASM
|
||||
#define __ASM _asm
|
||||
#endif
|
||||
#ifndef __INLINE
|
||||
#define __INLINE inline
|
||||
#endif
|
||||
#ifndef __STATIC_INLINE
|
||||
#define __STATIC_INLINE static inline
|
||||
#endif
|
||||
#ifndef __STATIC_FORCEINLINE
|
||||
#define __STATIC_FORCEINLINE __STATIC_INLINE
|
||||
#endif
|
||||
#ifndef __NO_RETURN
|
||||
// NO RETURN is automatically detected hence no warning here
|
||||
#define __NO_RETURN
|
||||
#endif
|
||||
#ifndef __USED
|
||||
#warning No compiler specific solution for __USED. __USED is ignored.
|
||||
#define __USED
|
||||
#endif
|
||||
#ifndef __WEAK
|
||||
#define __WEAK __weak
|
||||
#endif
|
||||
#ifndef __PACKED
|
||||
#define __PACKED @packed
|
||||
#endif
|
||||
#ifndef __PACKED_STRUCT
|
||||
#define __PACKED_STRUCT @packed struct
|
||||
#endif
|
||||
#ifndef __PACKED_UNION
|
||||
#define __PACKED_UNION @packed union
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT32 /* deprecated */
|
||||
@packed struct T_UINT32 { uint32_t v; };
|
||||
#define __UNALIGNED_UINT32(x) (((struct T_UINT32 *)(x))->v)
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT16_WRITE
|
||||
__PACKED_STRUCT T_UINT16_WRITE { uint16_t v; };
|
||||
#define __UNALIGNED_UINT16_WRITE(addr, val) (void)((((struct T_UINT16_WRITE *)(void *)(addr))->v) = (val))
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT16_READ
|
||||
__PACKED_STRUCT T_UINT16_READ { uint16_t v; };
|
||||
#define __UNALIGNED_UINT16_READ(addr) (((const struct T_UINT16_READ *)(const void *)(addr))->v)
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT32_WRITE
|
||||
__PACKED_STRUCT T_UINT32_WRITE { uint32_t v; };
|
||||
#define __UNALIGNED_UINT32_WRITE(addr, val) (void)((((struct T_UINT32_WRITE *)(void *)(addr))->v) = (val))
|
||||
#endif
|
||||
#ifndef __UNALIGNED_UINT32_READ
|
||||
__PACKED_STRUCT T_UINT32_READ { uint32_t v; };
|
||||
#define __UNALIGNED_UINT32_READ(addr) (((const struct T_UINT32_READ *)(const void *)(addr))->v)
|
||||
#endif
|
||||
#ifndef __ALIGNED
|
||||
#warning No compiler specific solution for __ALIGNED. __ALIGNED is ignored.
|
||||
#define __ALIGNED(x)
|
||||
#endif
|
||||
#ifndef __RESTRICT
|
||||
#warning No compiler specific solution for __RESTRICT. __RESTRICT is ignored.
|
||||
#define __RESTRICT
|
||||
#endif
|
||||
#ifndef __COMPILER_BARRIER
|
||||
#warning No compiler specific solution for __COMPILER_BARRIER. __COMPILER_BARRIER is ignored.
|
||||
#define __COMPILER_BARRIER() (void)0
|
||||
#endif
|
||||
|
||||
|
||||
#else
|
||||
#error Unknown compiler.
|
||||
#endif
|
||||
|
||||
|
||||
#endif /* __CMSIS_COMPILER_H */
|
||||
|
||||
2168
include/cmsis_gcc.h
Normal file
2168
include/cmsis_gcc.h
Normal file
File diff suppressed because it is too large
Load diff
39
include/cmsis_version.h
Normal file
39
include/cmsis_version.h
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
/**************************************************************************//**
|
||||
* @file cmsis_version.h
|
||||
* @brief CMSIS Core(M) Version definitions
|
||||
* @version V5.0.3
|
||||
* @date 24. June 2019
|
||||
******************************************************************************/
|
||||
/*
|
||||
* Copyright (c) 2009-2019 ARM Limited. All rights reserved.
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the License); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an AS IS BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#if defined ( __ICCARM__ )
|
||||
#pragma system_include /* treat file as system include file for MISRA check */
|
||||
#elif defined (__clang__)
|
||||
#pragma clang system_header /* treat file as system include file */
|
||||
#endif
|
||||
|
||||
#ifndef __CMSIS_VERSION_H
|
||||
#define __CMSIS_VERSION_H
|
||||
|
||||
/* CMSIS Version definitions */
|
||||
#define __CM_CMSIS_VERSION_MAIN ( 5U) /*!< [31:16] CMSIS Core(M) main version */
|
||||
#define __CM_CMSIS_VERSION_SUB ( 3U) /*!< [15:0] CMSIS Core(M) sub version */
|
||||
#define __CM_CMSIS_VERSION ((__CM_CMSIS_VERSION_MAIN << 16U) | \
|
||||
__CM_CMSIS_VERSION_SUB ) /*!< CMSIS Core(M) version number */
|
||||
#endif
|
||||
1937
include/core_cm3.h
Normal file
1937
include/core_cm3.h
Normal file
File diff suppressed because it is too large
Load diff
108
include/global.h
Normal file
108
include/global.h
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
|
||||
#ifndef __GLOBAL_H__
|
||||
#define __GLOBAL_H__
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h>
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
|
||||
/* The IRQ header must be included before stm32_device.h since ST defines a bunch of messy macros there. */
|
||||
#include <stm32_irqs.h> /* Header generated from stm32***_startup.s in Makefile */
|
||||
|
||||
#include <stm32f1xx.h>
|
||||
#include <core_cm3.h>
|
||||
|
||||
#define DMA_ISR_FLAGS_Pos(channel) (4 * ((channel) - 1))
|
||||
#define DMA_ISR_FLAGS_CH(channel) (0xf << DMA_ISR_FLAGS_Pos(channel))
|
||||
|
||||
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
|
||||
|
||||
#define APB1_PRESC (1<<(APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE1_Msk) >> RCC_CFGR_PPRE1_Pos]))
|
||||
#define AHB_PRESC (1<<(AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE_Msk) >> RCC_CFGR_HPRE_Pos]))
|
||||
|
||||
#define AFRL(pin, val) ((val) << ((pin)*4))
|
||||
#define AFRH(pin, val) ((val) << (((pin)-8)*4))
|
||||
#define AF(pin) (2<<(2*(pin)))
|
||||
#define OUT(pin) (1<<(2*(pin)))
|
||||
#define IN(pin) (0)
|
||||
#define ANALOG(pin) (3<<(2*(pin)))
|
||||
#define CLEAR(pin) (3<<(2*(pin)))
|
||||
#define PULLUP(pin) (1<<(2*pin))
|
||||
#define PULLDOWN(pin) (2<<(2*pin))
|
||||
#define BSRR_CLEAR(pin) ((1<<pin)<<16)
|
||||
#define BSRR_SET(pin) (1<<pin)
|
||||
#define BSRR_VALUE(pin, value) ((((!(value))<<pin)<<16) | ((!!(value))<<pin))
|
||||
|
||||
#ifndef SYSTICK_INTERVAL_US
|
||||
#define SYSTICK_INTERVAL_US 1000
|
||||
#endif /* SYSTICK_INTERVAL_US */
|
||||
|
||||
|
||||
enum ErrorCode {
|
||||
ERR_SUCCESS = 0,
|
||||
ERR_TIMEOUT,
|
||||
ERR_PHYSICAL_LAYER,
|
||||
ERR_FRAMING,
|
||||
ERR_PROTOCOL,
|
||||
ERR_DMA,
|
||||
ERR_BUSY,
|
||||
ERR_BUFFER_OVERFLOW,
|
||||
ERR_RX_OVERRUN,
|
||||
ERR_TX_OVERRUN,
|
||||
};
|
||||
|
||||
typedef enum ErrorCode ErrorCode;
|
||||
|
||||
enum board_config {
|
||||
BCFG_UNCONFIGURED = 0,
|
||||
|
||||
/* The board assumes one of three configurations depending on connected periphery.
|
||||
*
|
||||
*/
|
||||
|
||||
BCFG_DISPLAY,
|
||||
/* When an I2C 1602 display is connected to the LCD connector on powerup, the board assumes its display
|
||||
* configuration. In this configuration, the board scans the buttons connected on the Buttons connector and acts as
|
||||
* a peripheral on the RS-485 bus, relaying information between the bus and the HCI peripherals. In addition to the
|
||||
* LCD, the board controls three 8-digit 7-segment LED displays connected on the Buttons connector along with the
|
||||
* buttons.
|
||||
*
|
||||
* RS-485 board address: BADDR_DISPLAY
|
||||
*/
|
||||
|
||||
BCFG_MOTOR,
|
||||
/* When no LCD is connected and the BT0 input on the buttons connector is open, the board assumes its
|
||||
* motor configuration. In this configuration, the board controls a motor connected through the Buttons and LCD
|
||||
* connectors, and the USB control interface is enabled. The board acts as the host on the RS-485 bus.
|
||||
*
|
||||
* RS-485 board address: BADDR_MOTOR
|
||||
*/
|
||||
|
||||
BCFG_MEAS,
|
||||
/* When no LCD is connected and the BT0 input on the buttons connector is tied to ground, the board assumes its
|
||||
* senesor configuration. In this configuration, the board periodically. The board acts as a peripheral on the
|
||||
* RS-485 bus, relaying measurements on the bus when requested by the host. The board's bus address is set by pins
|
||||
* BT1 and BT0 of the buttons connector. Both pins have pullups enabled, and will read zero when tied to ground on
|
||||
* the connector. The address is the binary value of {BT2, BT1} added to BADDR_MES_BASE. With both pins open, the
|
||||
* address is 11 (decimal), with BT1 tied to ground it is 10 (decimal).
|
||||
*
|
||||
* RS-485 board address: BADDR_MEAS_BASE + [BT2:1]
|
||||
*/
|
||||
};
|
||||
|
||||
enum board_addr {
|
||||
BADDR_DISPLAY = 1,
|
||||
BADDR_MOTOR = 2,
|
||||
BADDR_MEAS_BASE = 8,
|
||||
};
|
||||
|
||||
void delay_us(int duration_us);
|
||||
uint64_t get_sync_time(void);
|
||||
|
||||
extern enum board_config board_config;
|
||||
extern volatile uint64_t sys_time_us;
|
||||
extern volatile uint64_t sync_time_us;
|
||||
|
||||
#endif /* __GLOBAL_H__ */
|
||||
14
include/iomacros.h
Normal file
14
include/iomacros.h
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
#ifndef __IOMACROS_H__
|
||||
#define __IOMACROS_H__
|
||||
|
||||
#define IN(pin) (0)
|
||||
#define OUT(pin) (1<<(2*(pin)))
|
||||
#define AF(pin) (2<<(2*(pin)))
|
||||
#define ANALOG(pin) (3<<(2*(pin)))
|
||||
|
||||
#define CLEAR(pin) (~(3<<(2*(pin))))
|
||||
|
||||
#define AFRL(pin, val) ((val) << ((pin)*4))
|
||||
#define AFRH(pin, val) ((val) << (((pin)-8)*4))
|
||||
|
||||
#endif __IOMACROS_H__
|
||||
56
include/irqs.h
Normal file
56
include/irqs.h
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/* AUTOGENERATED FILE! DO NOT MODIFY! */
|
||||
/* Generated {datetime.datetime.utcnow()} from {args.input} */
|
||||
|
||||
void _estack(void); /* 0 */
|
||||
void Reset_Handler(void); /* 1 */
|
||||
void NMI_Handler(void); /* 2 */
|
||||
void HardFault_Handler(void); /* 3 */
|
||||
/* IRQ 4 is undefined for this part. */
|
||||
/* IRQ 5 is undefined for this part. */
|
||||
/* IRQ 6 is undefined for this part. */
|
||||
/* IRQ 7 is undefined for this part. */
|
||||
/* IRQ 8 is undefined for this part. */
|
||||
/* IRQ 9 is undefined for this part. */
|
||||
/* IRQ 10 is undefined for this part. */
|
||||
void SVC_Handler(void); /* 11 */
|
||||
/* IRQ 12 is undefined for this part. */
|
||||
/* IRQ 13 is undefined for this part. */
|
||||
void PendSV_Handler(void); /* 14 */
|
||||
void SysTick_Handler(void); /* 15 */
|
||||
void WWDG_IRQHandler(void); /* 16 */
|
||||
void PVD_VDDIO2_IRQHandler(void); /* 17 */
|
||||
void RTC_IRQHandler(void); /* 18 */
|
||||
void FLASH_IRQHandler(void); /* 19 */
|
||||
void RCC_CRS_IRQHandler(void); /* 20 */
|
||||
void EXTI0_1_IRQHandler(void); /* 21 */
|
||||
void EXTI2_3_IRQHandler(void); /* 22 */
|
||||
void EXTI4_15_IRQHandler(void); /* 23 */
|
||||
void TSC_IRQHandler(void); /* 24 */
|
||||
void DMA1_Channel1_IRQHandler(void); /* 25 */
|
||||
void DMA1_Channel2_3_IRQHandler(void); /* 26 */
|
||||
void DMA1_Channel4_5_6_7_IRQHandler(void); /* 27 */
|
||||
void ADC1_COMP_IRQHandler(void); /* 28 */
|
||||
void TIM1_BRK_UP_TRG_COM_IRQHandler(void); /* 29 */
|
||||
void TIM1_CC_IRQHandler(void); /* 30 */
|
||||
void TIM2_IRQHandler(void); /* 31 */
|
||||
void TIM3_IRQHandler(void); /* 32 */
|
||||
void TIM6_DAC_IRQHandler(void); /* 33 */
|
||||
void TIM7_IRQHandler(void); /* 34 */
|
||||
void TIM14_IRQHandler(void); /* 35 */
|
||||
void TIM15_IRQHandler(void); /* 36 */
|
||||
void TIM16_IRQHandler(void); /* 37 */
|
||||
void TIM17_IRQHandler(void); /* 38 */
|
||||
void I2C1_IRQHandler(void); /* 39 */
|
||||
void I2C2_IRQHandler(void); /* 40 */
|
||||
void SPI1_IRQHandler(void); /* 41 */
|
||||
void SPI2_IRQHandler(void); /* 42 */
|
||||
void USART1_IRQHandler(void); /* 43 */
|
||||
void USART2_IRQHandler(void); /* 44 */
|
||||
void USART3_4_IRQHandler(void); /* 45 */
|
||||
void CEC_CAN_IRQHandler(void); /* 46 */
|
||||
void USB_IRQHandler(void); /* 47 */
|
||||
|
||||
#define NUM_IRQs 48
|
||||
extern uint32_t g_pfnVectors[NUM_IRQs];
|
||||
#define isr_vector g_pfnVectors
|
||||
|
||||
2
include/stm32.h
Normal file
2
include/stm32.h
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
/* libusb_stm compatibility file */
|
||||
#include "stm32f072xb.h"
|
||||
56
include/stm32_irqs.h
Normal file
56
include/stm32_irqs.h
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/* AUTOGENERATED FILE! DO NOT MODIFY! */
|
||||
/* Generated {datetime.datetime.utcnow()} from {args.input} */
|
||||
|
||||
void _estack(void); /* 0 */
|
||||
void Reset_Handler(void); /* 1 */
|
||||
void NMI_Handler(void); /* 2 */
|
||||
void HardFault_Handler(void); /* 3 */
|
||||
/* IRQ 4 is undefined for this part. */
|
||||
/* IRQ 5 is undefined for this part. */
|
||||
/* IRQ 6 is undefined for this part. */
|
||||
/* IRQ 7 is undefined for this part. */
|
||||
/* IRQ 8 is undefined for this part. */
|
||||
/* IRQ 9 is undefined for this part. */
|
||||
/* IRQ 10 is undefined for this part. */
|
||||
void SVC_Handler(void); /* 11 */
|
||||
/* IRQ 12 is undefined for this part. */
|
||||
/* IRQ 13 is undefined for this part. */
|
||||
void PendSV_Handler(void); /* 14 */
|
||||
void SysTick_Handler(void); /* 15 */
|
||||
void WWDG_IRQHandler(void); /* 16 */
|
||||
void PVD_VDDIO2_IRQHandler(void); /* 17 */
|
||||
void RTC_IRQHandler(void); /* 18 */
|
||||
void FLASH_IRQHandler(void); /* 19 */
|
||||
void RCC_CRS_IRQHandler(void); /* 20 */
|
||||
void EXTI0_1_IRQHandler(void); /* 21 */
|
||||
void EXTI2_3_IRQHandler(void); /* 22 */
|
||||
void EXTI4_15_IRQHandler(void); /* 23 */
|
||||
void TSC_IRQHandler(void); /* 24 */
|
||||
void DMA1_Channel1_IRQHandler(void); /* 25 */
|
||||
void DMA1_Channel2_3_IRQHandler(void); /* 26 */
|
||||
void DMA1_Channel4_5_6_7_IRQHandler(void); /* 27 */
|
||||
void ADC1_COMP_IRQHandler(void); /* 28 */
|
||||
void TIM1_BRK_UP_TRG_COM_IRQHandler(void); /* 29 */
|
||||
void TIM1_CC_IRQHandler(void); /* 30 */
|
||||
void TIM2_IRQHandler(void); /* 31 */
|
||||
void TIM3_IRQHandler(void); /* 32 */
|
||||
void TIM6_DAC_IRQHandler(void); /* 33 */
|
||||
void TIM7_IRQHandler(void); /* 34 */
|
||||
void TIM14_IRQHandler(void); /* 35 */
|
||||
void TIM15_IRQHandler(void); /* 36 */
|
||||
void TIM16_IRQHandler(void); /* 37 */
|
||||
void TIM17_IRQHandler(void); /* 38 */
|
||||
void I2C1_IRQHandler(void); /* 39 */
|
||||
void I2C2_IRQHandler(void); /* 40 */
|
||||
void SPI1_IRQHandler(void); /* 41 */
|
||||
void SPI2_IRQHandler(void); /* 42 */
|
||||
void USART1_IRQHandler(void); /* 43 */
|
||||
void USART2_IRQHandler(void); /* 44 */
|
||||
void USART3_4_IRQHandler(void); /* 45 */
|
||||
void CEC_CAN_IRQHandler(void); /* 46 */
|
||||
void USB_IRQHandler(void); /* 47 */
|
||||
|
||||
#define NUM_IRQs 48
|
||||
extern uint32_t g_pfnVectors[NUM_IRQs];
|
||||
#define isr_vector g_pfnVectors
|
||||
|
||||
10240
include/stm32f103xb.h
Normal file
10240
include/stm32f103xb.h
Normal file
File diff suppressed because it is too large
Load diff
273
include/stm32f1xx.h
Normal file
273
include/stm32f1xx.h
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
/**
|
||||
******************************************************************************
|
||||
* @file stm32f1xx.h
|
||||
* @author MCD Application Team
|
||||
* @brief CMSIS STM32F1xx Device Peripheral Access Layer Header File.
|
||||
*
|
||||
* The file is the unique include file that the application programmer
|
||||
* is using in the C source code, usually in main.c. This file contains:
|
||||
* - Configuration section that allows to select:
|
||||
* - The STM32F1xx device used in the target application
|
||||
* - To use or not the peripheral's drivers in application code(i.e.
|
||||
* code will be based on direct access to peripheral's registers
|
||||
* rather than drivers API), this option is controlled by
|
||||
* "#define USE_HAL_DRIVER"
|
||||
*
|
||||
******************************************************************************
|
||||
* @attention
|
||||
*
|
||||
* Copyright (c) 2017-2021 STMicroelectronics.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is licensed under terms that can be found in the LICENSE file
|
||||
* in the root directory of this software component.
|
||||
* If no LICENSE file comes with this software, it is provided AS-IS.
|
||||
*
|
||||
******************************************************************************
|
||||
*/
|
||||
|
||||
/** @addtogroup CMSIS
|
||||
* @{
|
||||
*/
|
||||
|
||||
/** @addtogroup stm32f1xx
|
||||
* @{
|
||||
*/
|
||||
|
||||
#ifndef __STM32F1XX_H
|
||||
#define __STM32F1XX_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif /* __cplusplus */
|
||||
|
||||
/** @addtogroup Library_configuration_section
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief STM32 Family
|
||||
*/
|
||||
#if !defined (STM32F1)
|
||||
#define STM32F1
|
||||
#endif /* STM32F1 */
|
||||
|
||||
/* Uncomment the line below according to the target STM32L device used in your
|
||||
application
|
||||
*/
|
||||
|
||||
#if !defined (STM32F100xB) && !defined (STM32F100xE) && !defined (STM32F101x6) && \
|
||||
!defined (STM32F101xB) && !defined (STM32F101xE) && !defined (STM32F101xG) && !defined (STM32F102x6) && !defined (STM32F102xB) && !defined (STM32F103x6) && \
|
||||
!defined (STM32F103xB) && !defined (STM32F103xE) && !defined (STM32F103xG) && !defined (STM32F105xC) && !defined (STM32F107xC)
|
||||
/* #define STM32F100xB */ /*!< STM32F100C4, STM32F100R4, STM32F100C6, STM32F100R6, STM32F100C8, STM32F100R8, STM32F100V8, STM32F100CB, STM32F100RB and STM32F100VB */
|
||||
/* #define STM32F100xE */ /*!< STM32F100RC, STM32F100VC, STM32F100ZC, STM32F100RD, STM32F100VD, STM32F100ZD, STM32F100RE, STM32F100VE and STM32F100ZE */
|
||||
/* #define STM32F101x6 */ /*!< STM32F101C4, STM32F101R4, STM32F101T4, STM32F101C6, STM32F101R6 and STM32F101T6 Devices */
|
||||
/* #define STM32F101xB */ /*!< STM32F101C8, STM32F101R8, STM32F101T8, STM32F101V8, STM32F101CB, STM32F101RB, STM32F101TB and STM32F101VB */
|
||||
/* #define STM32F101xE */ /*!< STM32F101RC, STM32F101VC, STM32F101ZC, STM32F101RD, STM32F101VD, STM32F101ZD, STM32F101RE, STM32F101VE and STM32F101ZE */
|
||||
/* #define STM32F101xG */ /*!< STM32F101RF, STM32F101VF, STM32F101ZF, STM32F101RG, STM32F101VG and STM32F101ZG */
|
||||
/* #define STM32F102x6 */ /*!< STM32F102C4, STM32F102R4, STM32F102C6 and STM32F102R6 */
|
||||
/* #define STM32F102xB */ /*!< STM32F102C8, STM32F102R8, STM32F102CB and STM32F102RB */
|
||||
/* #define STM32F103x6 */ /*!< STM32F103C4, STM32F103R4, STM32F103T4, STM32F103C6, STM32F103R6 and STM32F103T6 */
|
||||
/* #define STM32F103xB */ /*!< STM32F103C8, STM32F103R8, STM32F103T8, STM32F103V8, STM32F103CB, STM32F103RB, STM32F103TB and STM32F103VB */
|
||||
/* #define STM32F103xE */ /*!< STM32F103RC, STM32F103VC, STM32F103ZC, STM32F103RD, STM32F103VD, STM32F103ZD, STM32F103RE, STM32F103VE and STM32F103ZE */
|
||||
/* #define STM32F103xG */ /*!< STM32F103RF, STM32F103VF, STM32F103ZF, STM32F103RG, STM32F103VG and STM32F103ZG */
|
||||
/* #define STM32F105xC */ /*!< STM32F105R8, STM32F105V8, STM32F105RB, STM32F105VB, STM32F105RC and STM32F105VC */
|
||||
/* #define STM32F107xC */ /*!< STM32F107RB, STM32F107VB, STM32F107RC and STM32F107VC */
|
||||
#endif
|
||||
|
||||
/* Tip: To avoid modifying this file each time you need to switch between these
|
||||
devices, you can define the device in your toolchain compiler preprocessor.
|
||||
*/
|
||||
|
||||
#if !defined (USE_HAL_DRIVER)
|
||||
/**
|
||||
* @brief Comment the line below if you will not use the peripherals drivers.
|
||||
In this case, these drivers will not be included and the application code will
|
||||
be based on direct access to peripherals registers
|
||||
*/
|
||||
/*#define USE_HAL_DRIVER */
|
||||
#endif /* USE_HAL_DRIVER */
|
||||
|
||||
/**
|
||||
* @brief CMSIS Device version number
|
||||
*/
|
||||
#define __STM32F1_CMSIS_VERSION_MAIN (0x04) /*!< [31:24] main version */
|
||||
#define __STM32F1_CMSIS_VERSION_SUB1 (0x03) /*!< [23:16] sub1 version */
|
||||
#define __STM32F1_CMSIS_VERSION_SUB2 (0x04) /*!< [15:8] sub2 version */
|
||||
#define __STM32F1_CMSIS_VERSION_RC (0x00) /*!< [7:0] release candidate */
|
||||
#define __STM32F1_CMSIS_VERSION ((__STM32F1_CMSIS_VERSION_MAIN << 24)\
|
||||
|(__STM32F1_CMSIS_VERSION_SUB1 << 16)\
|
||||
|(__STM32F1_CMSIS_VERSION_SUB2 << 8 )\
|
||||
|(__STM32F1_CMSIS_VERSION_RC))
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/** @addtogroup Device_Included
|
||||
* @{
|
||||
*/
|
||||
|
||||
#if defined(STM32F100xB)
|
||||
#include "stm32f100xb.h"
|
||||
#elif defined(STM32F100xE)
|
||||
#include "stm32f100xe.h"
|
||||
#elif defined(STM32F101x6)
|
||||
#include "stm32f101x6.h"
|
||||
#elif defined(STM32F101xB)
|
||||
#include "stm32f101xb.h"
|
||||
#elif defined(STM32F101xE)
|
||||
#include "stm32f101xe.h"
|
||||
#elif defined(STM32F101xG)
|
||||
#include "stm32f101xg.h"
|
||||
#elif defined(STM32F102x6)
|
||||
#include "stm32f102x6.h"
|
||||
#elif defined(STM32F102xB)
|
||||
#include "stm32f102xb.h"
|
||||
#elif defined(STM32F103x6)
|
||||
#include "stm32f103x6.h"
|
||||
#elif defined(STM32F103xB)
|
||||
#include "stm32f103xb.h"
|
||||
#elif defined(STM32F103xE)
|
||||
#include "stm32f103xe.h"
|
||||
#elif defined(STM32F103xG)
|
||||
#include "stm32f103xg.h"
|
||||
#elif defined(STM32F105xC)
|
||||
#include "stm32f105xc.h"
|
||||
#elif defined(STM32F107xC)
|
||||
#include "stm32f107xc.h"
|
||||
#else
|
||||
#error "Please select first the target STM32F1xx device used in your application (in stm32f1xx.h file)"
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/** @addtogroup Exported_types
|
||||
* @{
|
||||
*/
|
||||
typedef enum
|
||||
{
|
||||
RESET = 0,
|
||||
SET = !RESET
|
||||
} FlagStatus, ITStatus;
|
||||
|
||||
typedef enum
|
||||
{
|
||||
DISABLE = 0,
|
||||
ENABLE = !DISABLE
|
||||
} FunctionalState;
|
||||
#define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE))
|
||||
|
||||
typedef enum
|
||||
{
|
||||
SUCCESS = 0U,
|
||||
ERROR = !SUCCESS
|
||||
} ErrorStatus;
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
|
||||
/** @addtogroup Exported_macros
|
||||
* @{
|
||||
*/
|
||||
#define SET_BIT(REG, BIT) ((REG) |= (BIT))
|
||||
|
||||
#define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT))
|
||||
|
||||
#define READ_BIT(REG, BIT) ((REG) & (BIT))
|
||||
|
||||
#define CLEAR_REG(REG) ((REG) = (0x0))
|
||||
|
||||
#define WRITE_REG(REG, VAL) ((REG) = (VAL))
|
||||
|
||||
#define READ_REG(REG) ((REG))
|
||||
|
||||
#define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK)))
|
||||
|
||||
#define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL)))
|
||||
|
||||
/* Use of CMSIS compiler intrinsics for register exclusive access */
|
||||
/* Atomic 32-bit register access macro to set one or several bits */
|
||||
#define ATOMIC_SET_BIT(REG, BIT) \
|
||||
do { \
|
||||
uint32_t val; \
|
||||
do { \
|
||||
val = __LDREXW((__IO uint32_t *)&(REG)) | (BIT); \
|
||||
} while ((__STREXW(val,(__IO uint32_t *)&(REG))) != 0U); \
|
||||
} while(0)
|
||||
|
||||
/* Atomic 32-bit register access macro to clear one or several bits */
|
||||
#define ATOMIC_CLEAR_BIT(REG, BIT) \
|
||||
do { \
|
||||
uint32_t val; \
|
||||
do { \
|
||||
val = __LDREXW((__IO uint32_t *)&(REG)) & ~(BIT); \
|
||||
} while ((__STREXW(val,(__IO uint32_t *)&(REG))) != 0U); \
|
||||
} while(0)
|
||||
|
||||
/* Atomic 32-bit register access macro to clear and set one or several bits */
|
||||
#define ATOMIC_MODIFY_REG(REG, CLEARMSK, SETMASK) \
|
||||
do { \
|
||||
uint32_t val; \
|
||||
do { \
|
||||
val = (__LDREXW((__IO uint32_t *)&(REG)) & ~(CLEARMSK)) | (SETMASK); \
|
||||
} while ((__STREXW(val,(__IO uint32_t *)&(REG))) != 0U); \
|
||||
} while(0)
|
||||
|
||||
/* Atomic 16-bit register access macro to set one or several bits */
|
||||
#define ATOMIC_SETH_BIT(REG, BIT) \
|
||||
do { \
|
||||
uint16_t val; \
|
||||
do { \
|
||||
val = __LDREXH((__IO uint16_t *)&(REG)) | (BIT); \
|
||||
} while ((__STREXH(val,(__IO uint16_t *)&(REG))) != 0U); \
|
||||
} while(0)
|
||||
|
||||
/* Atomic 16-bit register access macro to clear one or several bits */
|
||||
#define ATOMIC_CLEARH_BIT(REG, BIT) \
|
||||
do { \
|
||||
uint16_t val; \
|
||||
do { \
|
||||
val = __LDREXH((__IO uint16_t *)&(REG)) & ~(BIT); \
|
||||
} while ((__STREXH(val,(__IO uint16_t *)&(REG))) != 0U); \
|
||||
} while(0)
|
||||
|
||||
/* Atomic 16-bit register access macro to clear and set one or several bits */
|
||||
#define ATOMIC_MODIFYH_REG(REG, CLEARMSK, SETMASK) \
|
||||
do { \
|
||||
uint16_t val; \
|
||||
do { \
|
||||
val = (__LDREXH((__IO uint16_t *)&(REG)) & ~(CLEARMSK)) | (SETMASK); \
|
||||
} while ((__STREXH(val,(__IO uint16_t *)&(REG))) != 0U); \
|
||||
} while(0)
|
||||
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
#if defined (USE_HAL_DRIVER)
|
||||
#include "stm32f1xx_hal.h"
|
||||
#endif /* USE_HAL_DRIVER */
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#endif /* __STM32F1xx_H */
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
103
include/system_stm32f1xx.h
Normal file
103
include/system_stm32f1xx.h
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
/**
|
||||
******************************************************************************
|
||||
* @file system_stm32f0xx.h
|
||||
* @author MCD Application Team
|
||||
* @brief CMSIS Cortex-M0 Device System Source File for STM32F0xx devices.
|
||||
******************************************************************************
|
||||
* @attention
|
||||
*
|
||||
* Copyright (c) 2016 STMicroelectronics.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is licensed under terms that can be found in the LICENSE file
|
||||
* in the root directory of this software component.
|
||||
* If no LICENSE file comes with this software, it is provided AS-IS.
|
||||
*
|
||||
******************************************************************************
|
||||
*/
|
||||
/** @addtogroup CMSIS
|
||||
* @{
|
||||
*/
|
||||
|
||||
/** @addtogroup stm32f0xx_system
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Define to prevent recursive inclusion
|
||||
*/
|
||||
#ifndef __SYSTEM_STM32F1XX_H
|
||||
#define __SYSTEM_STM32F1XX_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** @addtogroup STM32F0xx_System_Includes
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
|
||||
/** @addtogroup STM32F0xx_System_Exported_types
|
||||
* @{
|
||||
*/
|
||||
/* This variable is updated in three ways:
|
||||
1) by calling CMSIS function SystemCoreClockUpdate()
|
||||
3) by calling HAL API function HAL_RCC_GetHCLKFreq()
|
||||
3) by calling HAL API function HAL_RCC_ClockConfig()
|
||||
Note: If you use this function to configure the system clock; then there
|
||||
is no need to call the 2 first functions listed above, since SystemCoreClock
|
||||
variable is updated automatically.
|
||||
*/
|
||||
extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */
|
||||
extern const uint8_t AHBPrescTable[16]; /*!< AHB prescalers table values */
|
||||
extern const uint8_t APBPrescTable[8]; /*!< APB prescalers table values */
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/** @addtogroup STM32F0xx_System_Exported_Constants
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/** @addtogroup STM32F0xx_System_Exported_Macros
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/** @addtogroup STM32F0xx_System_Exported_Functions
|
||||
* @{
|
||||
*/
|
||||
|
||||
extern void SystemInit(void);
|
||||
extern void SystemCoreClockUpdate(void);
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /*__SYSTEM_STM32F0XX_H */
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
2
memory_map.ldi
Normal file
2
memory_map.ldi
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
RAM (xrw): ORIGIN = 0x20000000, LENGTH = 20K
|
||||
FLASH (rx ): ORIGIN = 0x08000000, LENGTH = 64K
|
||||
9
openocd.cfg
Normal file
9
openocd.cfg
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
gdb_port 3333
|
||||
tcl_port disabled
|
||||
telnet_port disabled
|
||||
|
||||
source [find interface/stlink.cfg]
|
||||
source [find target/stm32f1x.cfg]
|
||||
|
||||
init
|
||||
arm semihosting enable
|
||||
297
src/main.c
Normal file
297
src/main.c
Normal file
|
|
@ -0,0 +1,297 @@
|
|||
|
||||
#include <global.h>
|
||||
#include <string.h>
|
||||
|
||||
enum indicator_index {
|
||||
IND_TLR, // 0
|
||||
IND_TLY, // 1
|
||||
IND_TLG, // 2
|
||||
IND_B1, // 3
|
||||
IND_B2, // 4
|
||||
IND_S3, // 5
|
||||
IND_S1, // 6
|
||||
IND_S2, // 7
|
||||
IND_R2, // 8
|
||||
IND_S4, // 9
|
||||
IND_R1, // 10
|
||||
};
|
||||
|
||||
enum andon_index {
|
||||
AND_G,
|
||||
AND_B,
|
||||
AND_Y,
|
||||
AND_R,
|
||||
};
|
||||
|
||||
uint32_t xorshift32()
|
||||
{
|
||||
/* https://en.wikipedia.org/wiki/Xorshift */
|
||||
static uint32_t x = 1;
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
return x;
|
||||
}
|
||||
|
||||
void set_indicators(int val) {
|
||||
int tlr = !!(val & (1<<0));
|
||||
int tly = !!(val & (1<<1));
|
||||
int tlg = !!(val & (1<<2));
|
||||
int b1 = !!(val & (1<<3));
|
||||
int b2 = !!(val & (1<<4));
|
||||
int r1 = !!(val & (1<<5));
|
||||
int r2 = !!(val & (1<<6));
|
||||
int s1 = !!(val & (1<<7));
|
||||
int s2 = !!(val & (1<<8));
|
||||
int s3 = !!(val & (1<<9));
|
||||
int s4 = !!(val & (1<<10));
|
||||
|
||||
GPIOB->BRR =
|
||||
(1 << 12) |
|
||||
(1 << 13) |
|
||||
(1 << 14) |
|
||||
(1 << 15) |
|
||||
(1 << 0) |
|
||||
(1 << 1) |
|
||||
(1 << 10) |
|
||||
(1 << 11) |
|
||||
(1 << 5) |
|
||||
(1 << 6) |
|
||||
(1 << 7);
|
||||
GPIOB->BSRR =
|
||||
(tlr << 12) |
|
||||
(tly << 13) |
|
||||
(tlg << 14) |
|
||||
( b1 << 15) |
|
||||
( b2 << 0) |
|
||||
( r1 << 1) |
|
||||
( r2 << 10) |
|
||||
( s1 << 11) |
|
||||
( s2 << 5) |
|
||||
( s3 << 6) |
|
||||
( s4 << 7);
|
||||
}
|
||||
|
||||
void set_andon(int val) {
|
||||
int a = !!(val & (1<<0));
|
||||
int b = !!(val & (1<<1));
|
||||
int c = !!(val & (1<<2));
|
||||
int d = !!(val & (1<<3));
|
||||
|
||||
GPIOB->BRR = (1<<8) | (1<<9) | (1<<4) | (1<<3);
|
||||
GPIOB->BSRR = (a<<3) | (b<<4) | (c<<8) | (d<<9);
|
||||
}
|
||||
|
||||
void buzz(int val) {
|
||||
GPIOA->BRR = 1;
|
||||
GPIOA->BSRR = !!val;
|
||||
}
|
||||
|
||||
ssize_t uart_pos = 0;
|
||||
ssize_t uart_nb = 0;
|
||||
struct ch9329_packet {
|
||||
uint8_t header[2];
|
||||
uint8_t addr;
|
||||
uint8_t cmd;
|
||||
uint8_t len;
|
||||
uint8_t data[9];
|
||||
} uart_buf;
|
||||
uint8_t *uart_p = (uint8_t *)&uart_buf;
|
||||
|
||||
void uart_tx(bool keyboard, bool press) {
|
||||
if (uart_nb > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
memset(&uart_buf, 0, sizeof(uart_buf));
|
||||
uart_buf.header[0] = 0x57;
|
||||
uart_buf.header[1] = 0xab;
|
||||
int dlen = sizeof(uart_buf);
|
||||
|
||||
if (keyboard) {
|
||||
uart_buf.len = 8;
|
||||
uart_buf.cmd = 2;
|
||||
uart_buf.data[0] = 0;
|
||||
uart_buf.data[1] = 0;
|
||||
uart_buf.data[2] = press ? 0x28 : 0; /* Enter */
|
||||
} else {
|
||||
uart_buf.len = 7;
|
||||
uart_buf.cmd = 4;
|
||||
dlen -= 1;
|
||||
uart_buf.data[0] = 2;
|
||||
uart_buf.data[1] = press ? 1 : 0;
|
||||
uart_buf.data[2] = 0;
|
||||
}
|
||||
|
||||
int checksum = 0;
|
||||
for (size_t i=0; i<dlen-1; i++) {
|
||||
checksum += uart_p[i];
|
||||
}
|
||||
uart_buf.data[uart_buf.len] = checksum;
|
||||
|
||||
uart_nb = dlen;
|
||||
}
|
||||
|
||||
int get_config_button() {
|
||||
return !(GPIOA->IDR & (1<<6));
|
||||
}
|
||||
|
||||
int get_trig_button() {
|
||||
return !(GPIOA->IDR & (1<<7));
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
RCC->CFGR = (0x7 << RCC_CFGR_PLLMULL_Pos);
|
||||
RCC->CR |= RCC_CR_PLLON;
|
||||
while (!(RCC->CR & RCC_CR_PLLRDY)) {
|
||||
/* Do nothing. */
|
||||
}
|
||||
|
||||
FLASH->ACR |= (1<<FLASH_ACR_LATENCY_Pos);
|
||||
|
||||
RCC->CFGR |= (2<<RCC_CFGR_SW_Pos);
|
||||
while (((RCC->CFGR >> RCC_CFGR_SWS_Pos) & 0x3) != 2) {
|
||||
/* Do nothing. */
|
||||
}
|
||||
|
||||
/* Enable peripheral clocks */
|
||||
RCC->APB2ENR |= RCC_APB2ENR_USART1EN | RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPBEN | RCC_APB2ENR_IOPCEN | RCC_APB2ENR_AFIOEN;
|
||||
|
||||
/* Disable JTAG NJTRST pin to free up GPIOB4*/
|
||||
AFIO->MAPR = (2<<AFIO_MAPR_SWJ_CFG_Pos);
|
||||
|
||||
/*
|
||||
* 76543210 */
|
||||
GPIOA->CRL = 0x88444443;
|
||||
/* 111111
|
||||
* 54321098 */
|
||||
GPIOA->CRH = 0x444444b4;
|
||||
|
||||
GPIOA->BSRR = (1<<6) | (1<<7); /* Enable button pull-ups */
|
||||
|
||||
/*
|
||||
* 76543210 */
|
||||
GPIOB->CRL = 0x33333433;
|
||||
/* 111111
|
||||
* 54321098 */
|
||||
GPIOB->CRH = 0x33333333;
|
||||
|
||||
/* 111111
|
||||
* 54321098 */
|
||||
GPIOC->CRH = 0x44344444;
|
||||
|
||||
USART1->CR1 = USART_CR1_UE | USART_CR1_TE;
|
||||
USART1->BRR = 0xea6; /* 9600 Bd, matches default baud rate of CH9329 */
|
||||
|
||||
SystemCoreClockUpdate();
|
||||
|
||||
set_indicators(0xffff);
|
||||
set_andon(0xf);
|
||||
|
||||
buzz(1);
|
||||
for (int i=0; i<3000000; i++) {
|
||||
asm volatile ("nop");
|
||||
}
|
||||
buzz(0);
|
||||
|
||||
int n = 0;
|
||||
int tl = 0;
|
||||
int spin = 0;
|
||||
int andr = 0;
|
||||
int blk = 0;
|
||||
int uart_ct = 0;
|
||||
while (23) {
|
||||
if ((uart_nb > 0) && (USART1->SR & USART_SR_TXE)) {
|
||||
USART1->DR = uart_p[uart_pos];
|
||||
uart_pos += 1;
|
||||
if (uart_pos == uart_nb) {
|
||||
uart_pos = 0;
|
||||
uart_nb = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (uart_ct == 0) {
|
||||
uart_tx(get_config_button(), get_trig_button());
|
||||
uart_ct = 1<<12;
|
||||
} else {
|
||||
uart_ct -= 1;
|
||||
}
|
||||
|
||||
n++;
|
||||
if (n&(1<<16)) {
|
||||
tl = (tl+1)%3;
|
||||
spin = (spin+1)%4;
|
||||
int r = xorshift32();
|
||||
|
||||
int ind = 0;
|
||||
ind |= (tl == 0 ? (1<<IND_TLR) : (tl == 1 ? (1<<IND_TLY) : (1<<IND_TLG)));
|
||||
ind |= (spin == 0 ? (1<<IND_S1) : (spin == 1 ? (1<<IND_S2) : (spin == 2 ? (1<<IND_S3) : (1<<IND_S4))));
|
||||
ind |= (r & 1) ? (1<<IND_B1) : 0;
|
||||
ind |= (r & 2) ? (1<<IND_B2) : 0;
|
||||
ind |= (r & 4) ? (1<<IND_R1) : (1<<IND_R2);
|
||||
set_indicators(ind);
|
||||
|
||||
andr = (andr + 1) % 18;
|
||||
blk = (blk + 1) % 32;
|
||||
int and = 0;
|
||||
and |= (andr > 12) ? (1<<AND_R) : 0;
|
||||
and |= (blk > 16) ? (1<<AND_Y) : 0;
|
||||
and |= (blk < 16) ? (1<<AND_G) : 0;
|
||||
and |= (r & 8) ? (1<<AND_B) : 0;
|
||||
set_andon(and);
|
||||
|
||||
n = 0;
|
||||
GPIOC->ODR ^= 1<<13;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void HardFault_Handler() {
|
||||
asm volatile ("bkpt");
|
||||
}
|
||||
|
||||
void delay_us(int duration_us) {
|
||||
while (duration_us--) {
|
||||
for (int i=0; i<3; i++) {
|
||||
asm volatile ("nop");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void *memcpy(void *restrict dest, const void *restrict src, size_t n)
|
||||
{
|
||||
unsigned char *d = dest;
|
||||
const unsigned char *s = src;
|
||||
|
||||
for (; n; n--) {
|
||||
*d++ = *s++;
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
|
||||
void *memmove(void *dest, const void *src, size_t n)
|
||||
{
|
||||
return memcpy(dest, src, n);
|
||||
}
|
||||
|
||||
void *memset(void *dest, int c, size_t n)
|
||||
{
|
||||
unsigned char *d = dest;
|
||||
while (n--) {
|
||||
*d++ = c;
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
|
||||
size_t strlen(const char *s)
|
||||
{
|
||||
const char *start = s;
|
||||
while (*s) {
|
||||
s++;
|
||||
}
|
||||
return s - start;
|
||||
}
|
||||
|
||||
void __libc_init_array (void) __attribute__((weak));
|
||||
void __libc_init_array () {
|
||||
}
|
||||
357
startup.s
Normal file
357
startup.s
Normal file
|
|
@ -0,0 +1,357 @@
|
|||
/**
|
||||
*************** (C) COPYRIGHT 2017 STMicroelectronics ************************
|
||||
* @file startup_stm32f103xb.s
|
||||
* @author MCD Application Team
|
||||
* @brief STM32F103xB Devices vector table for Atollic toolchain.
|
||||
* This module performs:
|
||||
* - Set the initial SP
|
||||
* - Set the initial PC == Reset_Handler,
|
||||
* - Set the vector table entries with the exceptions ISR address
|
||||
* - Configure the clock system
|
||||
* - Branches to main in the C library (which eventually
|
||||
* calls main()).
|
||||
* After Reset the Cortex-M3 processor is in Thread mode,
|
||||
* priority is Privileged, and the Stack is set to Main.
|
||||
* @attention
|
||||
*
|
||||
* Copyright (c) 2017 STMicroelectronics.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is licensed under terms that can be found in the LICENSE file
|
||||
* in the root directory of this software component.
|
||||
* If no LICENSE file comes with this software, it is provided AS-IS.
|
||||
*
|
||||
******************************************************************************
|
||||
*/
|
||||
|
||||
.syntax unified
|
||||
.cpu cortex-m3
|
||||
.fpu softvfp
|
||||
.thumb
|
||||
|
||||
.global g_pfnVectors
|
||||
.global Default_Handler
|
||||
|
||||
/* start address for the initialization values of the .data section.
|
||||
defined in linker script */
|
||||
.word _sidata
|
||||
/* start address for the .data section. defined in linker script */
|
||||
.word _sdata
|
||||
/* end address for the .data section. defined in linker script */
|
||||
.word _edata
|
||||
/* start address for the .bss section. defined in linker script */
|
||||
.word _sbss
|
||||
/* end address for the .bss section. defined in linker script */
|
||||
.word _ebss
|
||||
|
||||
.equ BootRAM, 0xF108F85F
|
||||
/**
|
||||
* @brief This is the code that gets called when the processor first
|
||||
* starts execution following a reset event. Only the absolutely
|
||||
* necessary set is performed, after which the application
|
||||
* supplied main() routine is called.
|
||||
* @param None
|
||||
* @retval : None
|
||||
*/
|
||||
|
||||
.section .text.Reset_Handler
|
||||
.weak Reset_Handler
|
||||
.type Reset_Handler, %function
|
||||
Reset_Handler:
|
||||
|
||||
/* Copy the data segment initializers from flash to SRAM */
|
||||
movs r1, #0
|
||||
b LoopCopyDataInit
|
||||
|
||||
CopyDataInit:
|
||||
ldr r3, =_sidata
|
||||
ldr r3, [r3, r1]
|
||||
str r3, [r0, r1]
|
||||
adds r1, r1, #4
|
||||
|
||||
LoopCopyDataInit:
|
||||
ldr r0, =_sdata
|
||||
ldr r3, =_edata
|
||||
adds r2, r0, r1
|
||||
cmp r2, r3
|
||||
bcc CopyDataInit
|
||||
ldr r2, =_sbss
|
||||
b LoopFillZerobss
|
||||
/* Zero fill the bss segment. */
|
||||
FillZerobss:
|
||||
movs r3, #0
|
||||
str r3, [r2], #4
|
||||
|
||||
LoopFillZerobss:
|
||||
ldr r3, = _ebss
|
||||
cmp r2, r3
|
||||
bcc FillZerobss
|
||||
|
||||
/* Call the clock system initialization function.*/
|
||||
bl SystemInit
|
||||
/* Call static constructors */
|
||||
bl __libc_init_array
|
||||
/* Call the application's entry point.*/
|
||||
bl main
|
||||
bx lr
|
||||
.size Reset_Handler, .-Reset_Handler
|
||||
|
||||
/**
|
||||
* @brief This is the code that gets called when the processor receives an
|
||||
* unexpected interrupt. This simply enters an infinite loop, preserving
|
||||
* the system state for examination by a debugger.
|
||||
*
|
||||
* @param None
|
||||
* @retval : None
|
||||
*/
|
||||
.section .text.Default_Handler,"ax",%progbits
|
||||
Default_Handler:
|
||||
Infinite_Loop:
|
||||
b Infinite_Loop
|
||||
.size Default_Handler, .-Default_Handler
|
||||
/******************************************************************************
|
||||
*
|
||||
* The minimal vector table for a Cortex M3. Note that the proper constructs
|
||||
* must be placed on this to ensure that it ends up at physical address
|
||||
* 0x0000.0000.
|
||||
*
|
||||
******************************************************************************/
|
||||
.section .isr_vector,"a",%progbits
|
||||
.type g_pfnVectors, %object
|
||||
.size g_pfnVectors, .-g_pfnVectors
|
||||
|
||||
|
||||
g_pfnVectors:
|
||||
|
||||
.word _estack
|
||||
.word Reset_Handler
|
||||
.word NMI_Handler
|
||||
.word HardFault_Handler
|
||||
.word MemManage_Handler
|
||||
.word BusFault_Handler
|
||||
.word UsageFault_Handler
|
||||
.word 0
|
||||
.word 0
|
||||
.word 0
|
||||
.word 0
|
||||
.word SVC_Handler
|
||||
.word DebugMon_Handler
|
||||
.word 0
|
||||
.word PendSV_Handler
|
||||
.word SysTick_Handler
|
||||
.word WWDG_IRQHandler
|
||||
.word PVD_IRQHandler
|
||||
.word TAMPER_IRQHandler
|
||||
.word RTC_IRQHandler
|
||||
.word FLASH_IRQHandler
|
||||
.word RCC_IRQHandler
|
||||
.word EXTI0_IRQHandler
|
||||
.word EXTI1_IRQHandler
|
||||
.word EXTI2_IRQHandler
|
||||
.word EXTI3_IRQHandler
|
||||
.word EXTI4_IRQHandler
|
||||
.word DMA1_Channel1_IRQHandler
|
||||
.word DMA1_Channel2_IRQHandler
|
||||
.word DMA1_Channel3_IRQHandler
|
||||
.word DMA1_Channel4_IRQHandler
|
||||
.word DMA1_Channel5_IRQHandler
|
||||
.word DMA1_Channel6_IRQHandler
|
||||
.word DMA1_Channel7_IRQHandler
|
||||
.word ADC1_2_IRQHandler
|
||||
.word USB_HP_CAN1_TX_IRQHandler
|
||||
.word USB_LP_CAN1_RX0_IRQHandler
|
||||
.word CAN1_RX1_IRQHandler
|
||||
.word CAN1_SCE_IRQHandler
|
||||
.word EXTI9_5_IRQHandler
|
||||
.word TIM1_BRK_IRQHandler
|
||||
.word TIM1_UP_IRQHandler
|
||||
.word TIM1_TRG_COM_IRQHandler
|
||||
.word TIM1_CC_IRQHandler
|
||||
.word TIM2_IRQHandler
|
||||
.word TIM3_IRQHandler
|
||||
.word TIM4_IRQHandler
|
||||
.word I2C1_EV_IRQHandler
|
||||
.word I2C1_ER_IRQHandler
|
||||
.word I2C2_EV_IRQHandler
|
||||
.word I2C2_ER_IRQHandler
|
||||
.word SPI1_IRQHandler
|
||||
.word SPI2_IRQHandler
|
||||
.word USART1_IRQHandler
|
||||
.word USART2_IRQHandler
|
||||
.word USART3_IRQHandler
|
||||
.word EXTI15_10_IRQHandler
|
||||
.word RTC_Alarm_IRQHandler
|
||||
.word USBWakeUp_IRQHandler
|
||||
.word 0
|
||||
.word 0
|
||||
.word 0
|
||||
.word 0
|
||||
.word 0
|
||||
.word 0
|
||||
.word 0
|
||||
.word BootRAM /* @0x108. This is for boot in RAM mode for
|
||||
STM32F10x Medium Density devices. */
|
||||
|
||||
/*******************************************************************************
|
||||
*
|
||||
* Provide weak aliases for each Exception handler to the Default_Handler.
|
||||
* As they are weak aliases, any function with the same name will override
|
||||
* this definition.
|
||||
*
|
||||
*******************************************************************************/
|
||||
|
||||
.weak NMI_Handler
|
||||
.thumb_set NMI_Handler,Default_Handler
|
||||
|
||||
.weak HardFault_Handler
|
||||
.thumb_set HardFault_Handler,Default_Handler
|
||||
|
||||
.weak MemManage_Handler
|
||||
.thumb_set MemManage_Handler,Default_Handler
|
||||
|
||||
.weak BusFault_Handler
|
||||
.thumb_set BusFault_Handler,Default_Handler
|
||||
|
||||
.weak UsageFault_Handler
|
||||
.thumb_set UsageFault_Handler,Default_Handler
|
||||
|
||||
.weak SVC_Handler
|
||||
.thumb_set SVC_Handler,Default_Handler
|
||||
|
||||
.weak DebugMon_Handler
|
||||
.thumb_set DebugMon_Handler,Default_Handler
|
||||
|
||||
.weak PendSV_Handler
|
||||
.thumb_set PendSV_Handler,Default_Handler
|
||||
|
||||
.weak SysTick_Handler
|
||||
.thumb_set SysTick_Handler,Default_Handler
|
||||
|
||||
.weak WWDG_IRQHandler
|
||||
.thumb_set WWDG_IRQHandler,Default_Handler
|
||||
|
||||
.weak PVD_IRQHandler
|
||||
.thumb_set PVD_IRQHandler,Default_Handler
|
||||
|
||||
.weak TAMPER_IRQHandler
|
||||
.thumb_set TAMPER_IRQHandler,Default_Handler
|
||||
|
||||
.weak RTC_IRQHandler
|
||||
.thumb_set RTC_IRQHandler,Default_Handler
|
||||
|
||||
.weak FLASH_IRQHandler
|
||||
.thumb_set FLASH_IRQHandler,Default_Handler
|
||||
|
||||
.weak RCC_IRQHandler
|
||||
.thumb_set RCC_IRQHandler,Default_Handler
|
||||
|
||||
.weak EXTI0_IRQHandler
|
||||
.thumb_set EXTI0_IRQHandler,Default_Handler
|
||||
|
||||
.weak EXTI1_IRQHandler
|
||||
.thumb_set EXTI1_IRQHandler,Default_Handler
|
||||
|
||||
.weak EXTI2_IRQHandler
|
||||
.thumb_set EXTI2_IRQHandler,Default_Handler
|
||||
|
||||
.weak EXTI3_IRQHandler
|
||||
.thumb_set EXTI3_IRQHandler,Default_Handler
|
||||
|
||||
.weak EXTI4_IRQHandler
|
||||
.thumb_set EXTI4_IRQHandler,Default_Handler
|
||||
|
||||
.weak DMA1_Channel1_IRQHandler
|
||||
.thumb_set DMA1_Channel1_IRQHandler,Default_Handler
|
||||
|
||||
.weak DMA1_Channel2_IRQHandler
|
||||
.thumb_set DMA1_Channel2_IRQHandler,Default_Handler
|
||||
|
||||
.weak DMA1_Channel3_IRQHandler
|
||||
.thumb_set DMA1_Channel3_IRQHandler,Default_Handler
|
||||
|
||||
.weak DMA1_Channel4_IRQHandler
|
||||
.thumb_set DMA1_Channel4_IRQHandler,Default_Handler
|
||||
|
||||
.weak DMA1_Channel5_IRQHandler
|
||||
.thumb_set DMA1_Channel5_IRQHandler,Default_Handler
|
||||
|
||||
.weak DMA1_Channel6_IRQHandler
|
||||
.thumb_set DMA1_Channel6_IRQHandler,Default_Handler
|
||||
|
||||
.weak DMA1_Channel7_IRQHandler
|
||||
.thumb_set DMA1_Channel7_IRQHandler,Default_Handler
|
||||
|
||||
.weak ADC1_2_IRQHandler
|
||||
.thumb_set ADC1_2_IRQHandler,Default_Handler
|
||||
|
||||
.weak USB_HP_CAN1_TX_IRQHandler
|
||||
.thumb_set USB_HP_CAN1_TX_IRQHandler,Default_Handler
|
||||
|
||||
.weak USB_LP_CAN1_RX0_IRQHandler
|
||||
.thumb_set USB_LP_CAN1_RX0_IRQHandler,Default_Handler
|
||||
|
||||
.weak CAN1_RX1_IRQHandler
|
||||
.thumb_set CAN1_RX1_IRQHandler,Default_Handler
|
||||
|
||||
.weak CAN1_SCE_IRQHandler
|
||||
.thumb_set CAN1_SCE_IRQHandler,Default_Handler
|
||||
|
||||
.weak EXTI9_5_IRQHandler
|
||||
.thumb_set EXTI9_5_IRQHandler,Default_Handler
|
||||
|
||||
.weak TIM1_BRK_IRQHandler
|
||||
.thumb_set TIM1_BRK_IRQHandler,Default_Handler
|
||||
|
||||
.weak TIM1_UP_IRQHandler
|
||||
.thumb_set TIM1_UP_IRQHandler,Default_Handler
|
||||
|
||||
.weak TIM1_TRG_COM_IRQHandler
|
||||
.thumb_set TIM1_TRG_COM_IRQHandler,Default_Handler
|
||||
|
||||
.weak TIM1_CC_IRQHandler
|
||||
.thumb_set TIM1_CC_IRQHandler,Default_Handler
|
||||
|
||||
.weak TIM2_IRQHandler
|
||||
.thumb_set TIM2_IRQHandler,Default_Handler
|
||||
|
||||
.weak TIM3_IRQHandler
|
||||
.thumb_set TIM3_IRQHandler,Default_Handler
|
||||
|
||||
.weak TIM4_IRQHandler
|
||||
.thumb_set TIM4_IRQHandler,Default_Handler
|
||||
|
||||
.weak I2C1_EV_IRQHandler
|
||||
.thumb_set I2C1_EV_IRQHandler,Default_Handler
|
||||
|
||||
.weak I2C1_ER_IRQHandler
|
||||
.thumb_set I2C1_ER_IRQHandler,Default_Handler
|
||||
|
||||
.weak I2C2_EV_IRQHandler
|
||||
.thumb_set I2C2_EV_IRQHandler,Default_Handler
|
||||
|
||||
.weak I2C2_ER_IRQHandler
|
||||
.thumb_set I2C2_ER_IRQHandler,Default_Handler
|
||||
|
||||
.weak SPI1_IRQHandler
|
||||
.thumb_set SPI1_IRQHandler,Default_Handler
|
||||
|
||||
.weak SPI2_IRQHandler
|
||||
.thumb_set SPI2_IRQHandler,Default_Handler
|
||||
|
||||
.weak USART1_IRQHandler
|
||||
.thumb_set USART1_IRQHandler,Default_Handler
|
||||
|
||||
.weak USART2_IRQHandler
|
||||
.thumb_set USART2_IRQHandler,Default_Handler
|
||||
|
||||
.weak USART3_IRQHandler
|
||||
.thumb_set USART3_IRQHandler,Default_Handler
|
||||
|
||||
.weak EXTI15_10_IRQHandler
|
||||
.thumb_set EXTI15_10_IRQHandler,Default_Handler
|
||||
|
||||
.weak RTC_Alarm_IRQHandler
|
||||
.thumb_set RTC_Alarm_IRQHandler,Default_Handler
|
||||
|
||||
.weak USBWakeUp_IRQHandler
|
||||
.thumb_set USBWakeUp_IRQHandler,Default_Handler
|
||||
1
stm32_buildinfo.defines
Normal file
1
stm32_buildinfo.defines
Normal file
|
|
@ -0,0 +1 @@
|
|||
STM32F103xB
|
||||
427
system.c
Normal file
427
system.c
Normal file
|
|
@ -0,0 +1,427 @@
|
|||
/**
|
||||
******************************************************************************
|
||||
* @file system_stm32f1xx.c
|
||||
* @author MCD Application Team
|
||||
* @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File.
|
||||
*
|
||||
* 1. This file provides two functions and one global variable to be called from
|
||||
* user application:
|
||||
* - SystemInit(): Setups the system clock (System clock source, PLL Multiplier
|
||||
* factors, AHB/APBx prescalers and Flash settings).
|
||||
* This function is called at startup just after reset and
|
||||
* before branch to main program. This call is made inside
|
||||
* the "startup_stm32f1xx_xx.s" file.
|
||||
*
|
||||
* - SystemCoreClock variable: Contains the core clock (HCLK), it can be used
|
||||
* by the user application to setup the SysTick
|
||||
* timer or configure other parameters.
|
||||
*
|
||||
* - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must
|
||||
* be called whenever the core clock is changed
|
||||
* during program execution.
|
||||
*
|
||||
* 2. After each device reset the HSI (8 MHz) is used as system clock source.
|
||||
* Then SystemInit() function is called, in "startup_stm32f1xx_xx.s" file, to
|
||||
* configure the system clock before to branch to main program.
|
||||
*
|
||||
* 4. The default value of HSE crystal is set to 8 MHz (or 25 MHz, depending on
|
||||
* the product used), refer to "HSE_VALUE".
|
||||
* When HSE is used as system clock source, directly or through PLL, and you
|
||||
* are using different crystal you have to adapt the HSE value to your own
|
||||
* configuration.
|
||||
*
|
||||
******************************************************************************
|
||||
* @attention
|
||||
*
|
||||
* Copyright (c) 2017 STMicroelectronics.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is licensed under terms that can be found in the LICENSE file
|
||||
* in the root directory of this software component.
|
||||
* If no LICENSE file comes with this software, it is provided AS-IS.
|
||||
*
|
||||
******************************************************************************
|
||||
*/
|
||||
|
||||
/** @addtogroup CMSIS
|
||||
* @{
|
||||
*/
|
||||
|
||||
/** @addtogroup stm32f1xx_system
|
||||
* @{
|
||||
*/
|
||||
|
||||
/** @addtogroup STM32F1xx_System_Private_Includes
|
||||
* @{
|
||||
*/
|
||||
|
||||
#include "stm32f1xx.h"
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/** @addtogroup STM32F1xx_System_Private_TypesDefinitions
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/** @addtogroup STM32F1xx_System_Private_Defines
|
||||
* @{
|
||||
*/
|
||||
|
||||
#if !defined (HSE_VALUE)
|
||||
#define HSE_VALUE 8000000U /*!< Default value of the External oscillator in Hz.
|
||||
This value can be provided and adapted by the user application. */
|
||||
#endif /* HSE_VALUE */
|
||||
|
||||
#if !defined (HSI_VALUE)
|
||||
#define HSI_VALUE 8000000U /*!< Default value of the Internal oscillator in Hz.
|
||||
This value can be provided and adapted by the user application. */
|
||||
#endif /* HSI_VALUE */
|
||||
|
||||
/*!< Uncomment the following line if you need to use external SRAM */
|
||||
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
|
||||
/* #define DATA_IN_ExtSRAM */
|
||||
#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */
|
||||
|
||||
/*!< Uncomment the following line if you need to relocate your vector Table in
|
||||
Internal SRAM. */
|
||||
/* #define VECT_TAB_SRAM */
|
||||
#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field.
|
||||
This value must be a multiple of 0x200. */
|
||||
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/** @addtogroup STM32F1xx_System_Private_Macros
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/** @addtogroup STM32F1xx_System_Private_Variables
|
||||
* @{
|
||||
*/
|
||||
/* This variable is updated in three ways:
|
||||
1) by calling CMSIS function SystemCoreClockUpdate()
|
||||
2) by calling HAL API function HAL_RCC_GetHCLKFreq()
|
||||
3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
|
||||
Note: If you use this function to configure the system clock; then there
|
||||
is no need to call the 2 first functions listed above, since SystemCoreClock
|
||||
variable is updated automatically.
|
||||
*/
|
||||
uint32_t SystemCoreClock = 16000000;
|
||||
const uint8_t AHBPrescTable[16U] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
|
||||
const uint8_t APBPrescTable[8U] = {0, 0, 0, 0, 1, 2, 3, 4};
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/** @addtogroup STM32F1xx_System_Private_FunctionPrototypes
|
||||
* @{
|
||||
*/
|
||||
|
||||
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
|
||||
#ifdef DATA_IN_ExtSRAM
|
||||
static void SystemInit_ExtMemCtl(void);
|
||||
#endif /* DATA_IN_ExtSRAM */
|
||||
#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/** @addtogroup STM32F1xx_System_Private_Functions
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Setup the microcontroller system
|
||||
* Initialize the Embedded Flash Interface, the PLL and update the
|
||||
* SystemCoreClock variable.
|
||||
* @note This function should be used only after reset.
|
||||
* @param None
|
||||
* @retval None
|
||||
*/
|
||||
void SystemInit (void)
|
||||
{
|
||||
/* Reset the RCC clock configuration to the default reset state(for debug purpose) */
|
||||
/* Set HSION bit */
|
||||
RCC->CR |= 0x00000001U;
|
||||
|
||||
/* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */
|
||||
#if !defined(STM32F105xC) && !defined(STM32F107xC)
|
||||
RCC->CFGR &= 0xF8FF0000U;
|
||||
#else
|
||||
RCC->CFGR &= 0xF0FF0000U;
|
||||
#endif /* STM32F105xC */
|
||||
|
||||
/* Reset HSEON, CSSON and PLLON bits */
|
||||
RCC->CR &= 0xFEF6FFFFU;
|
||||
|
||||
/* Reset HSEBYP bit */
|
||||
RCC->CR &= 0xFFFBFFFFU;
|
||||
|
||||
/* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */
|
||||
RCC->CFGR &= 0xFF80FFFFU;
|
||||
|
||||
#if defined(STM32F105xC) || defined(STM32F107xC)
|
||||
/* Reset PLL2ON and PLL3ON bits */
|
||||
RCC->CR &= 0xEBFFFFFFU;
|
||||
|
||||
/* Disable all interrupts and clear pending bits */
|
||||
RCC->CIR = 0x00FF0000U;
|
||||
|
||||
/* Reset CFGR2 register */
|
||||
RCC->CFGR2 = 0x00000000U;
|
||||
#elif defined(STM32F100xB) || defined(STM32F100xE)
|
||||
/* Disable all interrupts and clear pending bits */
|
||||
RCC->CIR = 0x009F0000U;
|
||||
|
||||
/* Reset CFGR2 register */
|
||||
RCC->CFGR2 = 0x00000000U;
|
||||
#else
|
||||
/* Disable all interrupts and clear pending bits */
|
||||
RCC->CIR = 0x009F0000U;
|
||||
#endif /* STM32F105xC */
|
||||
|
||||
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
|
||||
#ifdef DATA_IN_ExtSRAM
|
||||
SystemInit_ExtMemCtl();
|
||||
#endif /* DATA_IN_ExtSRAM */
|
||||
#endif
|
||||
|
||||
#ifdef VECT_TAB_SRAM
|
||||
SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */
|
||||
#else
|
||||
SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Update SystemCoreClock variable according to Clock Register Values.
|
||||
* The SystemCoreClock variable contains the core clock (HCLK), it can
|
||||
* be used by the user application to setup the SysTick timer or configure
|
||||
* other parameters.
|
||||
*
|
||||
* @note Each time the core clock (HCLK) changes, this function must be called
|
||||
* to update SystemCoreClock variable value. Otherwise, any configuration
|
||||
* based on this variable will be incorrect.
|
||||
*
|
||||
* @note - The system frequency computed by this function is not the real
|
||||
* frequency in the chip. It is calculated based on the predefined
|
||||
* constant and the selected clock source:
|
||||
*
|
||||
* - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*)
|
||||
*
|
||||
* - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**)
|
||||
*
|
||||
* - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**)
|
||||
* or HSI_VALUE(*) multiplied by the PLL factors.
|
||||
*
|
||||
* (*) HSI_VALUE is a constant defined in stm32f1xx.h file (default value
|
||||
* 8 MHz) but the real value may vary depending on the variations
|
||||
* in voltage and temperature.
|
||||
*
|
||||
* (**) HSE_VALUE is a constant defined in stm32f1xx.h file (default value
|
||||
* 8 MHz or 25 MHz, depending on the product used), user has to ensure
|
||||
* that HSE_VALUE is same as the real frequency of the crystal used.
|
||||
* Otherwise, this function may have wrong result.
|
||||
*
|
||||
* - The result of this function could be not correct when using fractional
|
||||
* value for HSE crystal.
|
||||
* @param None
|
||||
* @retval None
|
||||
*/
|
||||
void SystemCoreClockUpdate (void)
|
||||
{
|
||||
uint32_t tmp = 0U, pllmull = 0U, pllsource = 0U;
|
||||
|
||||
#if defined(STM32F105xC) || defined(STM32F107xC)
|
||||
uint32_t prediv1source = 0U, prediv1factor = 0U, prediv2factor = 0U, pll2mull = 0U;
|
||||
#endif /* STM32F105xC */
|
||||
|
||||
#if defined(STM32F100xB) || defined(STM32F100xE)
|
||||
uint32_t prediv1factor = 0U;
|
||||
#endif /* STM32F100xB or STM32F100xE */
|
||||
|
||||
/* Get SYSCLK source -------------------------------------------------------*/
|
||||
tmp = RCC->CFGR & RCC_CFGR_SWS;
|
||||
|
||||
switch (tmp)
|
||||
{
|
||||
case 0x00U: /* HSI used as system clock */
|
||||
SystemCoreClock = HSI_VALUE;
|
||||
break;
|
||||
case 0x04U: /* HSE used as system clock */
|
||||
SystemCoreClock = HSE_VALUE;
|
||||
break;
|
||||
case 0x08U: /* PLL used as system clock */
|
||||
|
||||
/* Get PLL clock source and multiplication factor ----------------------*/
|
||||
pllmull = RCC->CFGR & RCC_CFGR_PLLMULL;
|
||||
pllsource = RCC->CFGR & RCC_CFGR_PLLSRC;
|
||||
|
||||
#if !defined(STM32F105xC) && !defined(STM32F107xC)
|
||||
pllmull = ( pllmull >> 18U) + 2U;
|
||||
|
||||
if (pllsource == 0x00U)
|
||||
{
|
||||
/* HSI oscillator clock divided by 2 selected as PLL clock entry */
|
||||
SystemCoreClock = (HSI_VALUE >> 1U) * pllmull;
|
||||
}
|
||||
else
|
||||
{
|
||||
#if defined(STM32F100xB) || defined(STM32F100xE)
|
||||
prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U;
|
||||
/* HSE oscillator clock selected as PREDIV1 clock entry */
|
||||
SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
|
||||
#else
|
||||
/* HSE selected as PLL clock entry */
|
||||
if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t)RESET)
|
||||
{/* HSE oscillator clock divided by 2 */
|
||||
SystemCoreClock = (HSE_VALUE >> 1U) * pllmull;
|
||||
}
|
||||
else
|
||||
{
|
||||
SystemCoreClock = HSE_VALUE * pllmull;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#else
|
||||
pllmull = pllmull >> 18U;
|
||||
|
||||
if (pllmull != 0x0DU)
|
||||
{
|
||||
pllmull += 2U;
|
||||
}
|
||||
else
|
||||
{ /* PLL multiplication factor = PLL input clock * 6.5 */
|
||||
pllmull = 13U / 2U;
|
||||
}
|
||||
|
||||
if (pllsource == 0x00U)
|
||||
{
|
||||
/* HSI oscillator clock divided by 2 selected as PLL clock entry */
|
||||
SystemCoreClock = (HSI_VALUE >> 1U) * pllmull;
|
||||
}
|
||||
else
|
||||
{/* PREDIV1 selected as PLL clock entry */
|
||||
|
||||
/* Get PREDIV1 clock source and division factor */
|
||||
prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC;
|
||||
prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U;
|
||||
|
||||
if (prediv1source == 0U)
|
||||
{
|
||||
/* HSE oscillator clock selected as PREDIV1 clock entry */
|
||||
SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
|
||||
}
|
||||
else
|
||||
{/* PLL2 clock selected as PREDIV1 clock entry */
|
||||
|
||||
/* Get PREDIV2 division factor and PLL2 multiplication factor */
|
||||
prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4U) + 1U;
|
||||
pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8U) + 2U;
|
||||
SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull;
|
||||
}
|
||||
}
|
||||
#endif /* STM32F105xC */
|
||||
break;
|
||||
|
||||
default:
|
||||
SystemCoreClock = HSI_VALUE;
|
||||
break;
|
||||
}
|
||||
|
||||
/* Compute HCLK clock frequency ----------------*/
|
||||
/* Get HCLK prescaler */
|
||||
tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4U)];
|
||||
/* HCLK clock frequency */
|
||||
SystemCoreClock >>= tmp;
|
||||
}
|
||||
|
||||
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
|
||||
/**
|
||||
* @brief Setup the external memory controller. Called in startup_stm32f1xx.s
|
||||
* before jump to __main
|
||||
* @param None
|
||||
* @retval None
|
||||
*/
|
||||
#ifdef DATA_IN_ExtSRAM
|
||||
/**
|
||||
* @brief Setup the external memory controller.
|
||||
* Called in startup_stm32f1xx_xx.s/.c before jump to main.
|
||||
* This function configures the external SRAM mounted on STM3210E-EVAL
|
||||
* board (STM32 High density devices). This SRAM will be used as program
|
||||
* data memory (including heap and stack).
|
||||
* @param None
|
||||
* @retval None
|
||||
*/
|
||||
void SystemInit_ExtMemCtl(void)
|
||||
{
|
||||
__IO uint32_t tmpreg;
|
||||
/*!< FSMC Bank1 NOR/SRAM3 is used for the STM3210E-EVAL, if another Bank is
|
||||
required, then adjust the Register Addresses */
|
||||
|
||||
/* Enable FSMC clock */
|
||||
RCC->AHBENR = 0x00000114U;
|
||||
|
||||
/* Delay after an RCC peripheral clock enabling */
|
||||
tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_FSMCEN);
|
||||
|
||||
/* Enable GPIOD, GPIOE, GPIOF and GPIOG clocks */
|
||||
RCC->APB2ENR = 0x000001E0U;
|
||||
|
||||
/* Delay after an RCC peripheral clock enabling */
|
||||
tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPDEN);
|
||||
|
||||
(void)(tmpreg);
|
||||
|
||||
/* --------------- SRAM Data lines, NOE and NWE configuration ---------------*/
|
||||
/*---------------- SRAM Address lines configuration -------------------------*/
|
||||
/*---------------- NOE and NWE configuration --------------------------------*/
|
||||
/*---------------- NE3 configuration ----------------------------------------*/
|
||||
/*---------------- NBL0, NBL1 configuration ---------------------------------*/
|
||||
|
||||
GPIOD->CRL = 0x44BB44BBU;
|
||||
GPIOD->CRH = 0xBBBBBBBBU;
|
||||
|
||||
GPIOE->CRL = 0xB44444BBU;
|
||||
GPIOE->CRH = 0xBBBBBBBBU;
|
||||
|
||||
GPIOF->CRL = 0x44BBBBBBU;
|
||||
GPIOF->CRH = 0xBBBB4444U;
|
||||
|
||||
GPIOG->CRL = 0x44BBBBBBU;
|
||||
GPIOG->CRH = 0x444B4B44U;
|
||||
|
||||
/*---------------- FSMC Configuration ---------------------------------------*/
|
||||
/*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/
|
||||
|
||||
FSMC_Bank1->BTCR[4U] = 0x00001091U;
|
||||
FSMC_Bank1->BTCR[5U] = 0x00110212U;
|
||||
}
|
||||
#endif /* DATA_IN_ExtSRAM */
|
||||
#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
88
tools/decode_logic_analzyer.py
Normal file
88
tools/decode_logic_analzyer.py
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
import sys
|
||||
import subprocess
|
||||
import binascii
|
||||
from statistics import mean
|
||||
from dataclasses import dataclass, fields
|
||||
import struct
|
||||
from pprint import pprint
|
||||
|
||||
from cobs import cobs
|
||||
|
||||
time = [*sys.argv, '1s'][1]
|
||||
proc = subprocess.run(f'sigrok-cli --driver dreamsourcelab-dslogic --config samplerate=10M --channels 0,1 --protocol-decoders uart:baudrate=250000:rx=1 --protocol-decoder-annotations uart=rx-data,uart=tx-data --time {time}'.split(), check=True, capture_output=True, text=True)
|
||||
data = [line.partition(':')[2] for line in proc.stdout.splitlines()]
|
||||
data = bytes([int(x, 16) for x in data if x])
|
||||
|
||||
class Serialized:
|
||||
@classmethod
|
||||
def deserialize(kls, data):
|
||||
fields = struct.unpack(kls._struct_format(), data)
|
||||
mapped = [cast(val) for cast, val in zip(kls._struct_casts(), fields)]
|
||||
return kls(*mapped)
|
||||
|
||||
@classmethod
|
||||
def _struct_format(kls):
|
||||
return kls._parse_fields()[0]
|
||||
|
||||
@classmethod
|
||||
def _struct_casts(kls):
|
||||
return kls._parse_fields()[1]
|
||||
|
||||
@classmethod
|
||||
def _parse_fields(kls):
|
||||
fmt = '<'
|
||||
casts = []
|
||||
for field in fields(kls):
|
||||
if isinstance(field.type, tuple):
|
||||
struct_type, cast = field.type
|
||||
else:
|
||||
struct_type, cast = field.type, int
|
||||
fmt += struct_type
|
||||
casts.append(cast)
|
||||
return fmt, casts
|
||||
|
||||
@dataclass
|
||||
class Header(Serialized):
|
||||
crc: 'I'
|
||||
src: 'B'
|
||||
dst: 'B'
|
||||
pid: 'B'
|
||||
packet_type: 'B'
|
||||
|
||||
@dataclass
|
||||
class ADCPacket(Serialized):
|
||||
timestamp: 'Q'
|
||||
sampling_interval: 'I'
|
||||
total_samples: 'I'
|
||||
sample_count: 'I'
|
||||
samples: ('96s', bytes)
|
||||
|
||||
def __post_init__(self):
|
||||
data = self.samples
|
||||
foo = lambda x: x if x < 0x800000 else x-0x1000000
|
||||
self.samples = [[
|
||||
foo(struct.unpack('<I', data[3*(2*sample + channel):][:3] + b'\0')[0])
|
||||
for sample in range(16)
|
||||
] for channel in range(2)]
|
||||
|
||||
|
||||
norm_a, norm_b = 0, 0
|
||||
for packet in data.split(b'\0'):
|
||||
try:
|
||||
packet = cobs.decode(packet)
|
||||
hdr = Header.deserialize(packet[:8])
|
||||
if hdr.packet_type == 2:
|
||||
packet = ADCPacket.deserialize(packet[8:])
|
||||
diff_a = max([abs(x - norm_a) for x in packet.samples[0][:packet.sample_count]])
|
||||
diff_b = max([abs(x - norm_b) for x in packet.samples[1][:packet.sample_count]])
|
||||
if diff_a > 10000 or diff_b > 10000:
|
||||
pprint(packet)
|
||||
norm_a = mean(packet.samples[0][:packet.sample_count])
|
||||
norm_b = mean(packet.samples[1][:packet.sample_count])
|
||||
elif any(x != 0 for x in packet.samples[0][packet.sample_count:] + packet.samples[1][packet.sample_count:]):
|
||||
pprint('nonzero', packet)
|
||||
except (cobs.DecodeError, struct.error):
|
||||
print('Decoding error')
|
||||
|
||||
11
tools/extract_pinmap.py
Normal file
11
tools/extract_pinmap.py
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
import click
|
||||
|
||||
@click.command()
|
||||
@click.option('sch_file')
|
||||
def cli():
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
cli()
|
||||
66
tools/gen_isr_header.py
Normal file
66
tools/gen_isr_header.py
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import subprocess
|
||||
import os
|
||||
import re
|
||||
import datetime
|
||||
|
||||
def cpp_preprocess(input_path, cpp='cpp'):
|
||||
return subprocess.check_output([cpp, '-P', input_path]).decode()
|
||||
|
||||
def gen_isr_header(f, cpp='cpp'):
|
||||
stripped_code = cpp_preprocess(args.input, args.use_cpp)
|
||||
|
||||
armed = False
|
||||
for line in stripped_code.splitlines():
|
||||
line = line.strip()
|
||||
|
||||
if armed:
|
||||
if not line.startswith('.word'):
|
||||
break
|
||||
|
||||
word, value = line.split()
|
||||
assert word == '.word'
|
||||
if value == '0':
|
||||
yield None
|
||||
else:
|
||||
yield value
|
||||
|
||||
else:
|
||||
if line.startswith('g_pfnVectors:'):
|
||||
armed = True
|
||||
|
||||
else:
|
||||
raise ValueError('Cannot find interrupt vector definition!')
|
||||
|
||||
if __name__ == '__main__':
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--use-cpp', type=str, default=os.getenv('CPP', 'cpp'), help='cpp (C preprocessor) executable to use')
|
||||
parser.add_argument('-g', '--generate-include-guards', action='store_true', help='Whether to generate include guards')
|
||||
parser.add_argument('input', help='Input stm32****_startup.s file')
|
||||
args = parser.parse_args()
|
||||
|
||||
print('/* AUTOGENERATED FILE! DO NOT MODIFY! */')
|
||||
print('/* Generated {datetime.datetime.utcnow()} from {args.input} */')
|
||||
if args.generate_include_guards:
|
||||
include_guard_id = '__ISR_HEADER_' + re.sub('[^A-Za-z0-9]', '_', args.input.split('/')[-1]) + '__'
|
||||
print(f'#ifndef {include_guard_id}')
|
||||
print(f'#define {include_guard_id}')
|
||||
|
||||
print()
|
||||
for i, handler_name in enumerate(gen_isr_header(args.input, args.use_cpp)):
|
||||
if handler_name is None:
|
||||
print(f'/* IRQ {i} is undefined for this part. */')
|
||||
else:
|
||||
print(f'void {handler_name}(void); {" " * (30-len(handler_name))} /* {i:> 3} */')
|
||||
print()
|
||||
|
||||
print(f'#define NUM_IRQs {i+1}')
|
||||
print('extern uint32_t g_pfnVectors[NUM_IRQs];')
|
||||
print('#define isr_vector g_pfnVectors')
|
||||
print()
|
||||
|
||||
if args.generate_include_guards:
|
||||
print(f'#endif /* {include_guard_id} */')
|
||||
|
||||
126
tools/ldparser.py
Normal file
126
tools/ldparser.py
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
|
||||
import sys
|
||||
|
||||
import pyparsing as pp
|
||||
from pyparsing import pyparsing_common as ppc
|
||||
|
||||
LPAREN, RPAREN, LBRACE, RBRACE, LBROK, RBROK, COLON, SEMICOLON, EQUALS, COMMA = map(pp.Suppress, '(){}<>:;=,')
|
||||
|
||||
parse_suffix_int = lambda lit: int(lit[:-1]) * (10**(3*(1 + 'kmgtpe'.find(lit[-1].lower()))))
|
||||
si_suffix = pp.oneOf('k m g t p e', caseless=True)
|
||||
|
||||
numeric_literal = pp.Regex('0x[0-9a-fA-F]+').setName('hex int').setParseAction(pp.tokenMap(int, 16)) \
|
||||
| (pp.Regex('[0-9]+[kKmMgGtTpPeE]')).setName('size int').setParseAction(pp.tokenMap(parse_suffix_int)) \
|
||||
| pp.Word(pp.nums).setName('int').setParseAction(pp.tokenMap(int))
|
||||
access_def = pp.Regex('[rR]?[wW]?[xX]?').setName('access literal').setParseAction(pp.tokenMap(str.lower))
|
||||
|
||||
origin_expr = pp.Suppress(pp.CaselessKeyword('ORIGIN')) + EQUALS + numeric_literal
|
||||
length_expr = pp.Suppress(pp.CaselessKeyword('LENGTH')) + EQUALS + numeric_literal
|
||||
mem_expr = pp.Group(ppc.identifier + LPAREN + access_def + RPAREN + COLON + origin_expr + COMMA + length_expr)
|
||||
mem_contents = pp.ZeroOrMore(mem_expr)
|
||||
|
||||
mem_toplevel = pp.CaselessKeyword("MEMORY") + pp.Group(LBRACE + pp.Optional(mem_contents, []) + RBRACE)
|
||||
|
||||
glob = pp.Word(pp.alphanums + '._*')
|
||||
match_expr = pp.Forward()
|
||||
assignment = pp.Forward()
|
||||
funccall = pp.Group(pp.Word(pp.alphas + '_') + LPAREN + (assignment | numeric_literal | match_expr | glob | ppc.identifier) + RPAREN + pp.Optional(SEMICOLON))
|
||||
value = numeric_literal | funccall | ppc.identifier | '.'
|
||||
formula = (value + pp.oneOf('+ = * / %') + value) | value
|
||||
# suppress stray semicolons
|
||||
assignment << (SEMICOLON | pp.Group((ppc.identifier | '.') + EQUALS + (formula | value) + pp.Optional(SEMICOLON)))
|
||||
match_expr << (glob + LPAREN + pp.OneOrMore(funccall | glob) + RPAREN)
|
||||
|
||||
section_contents = pp.ZeroOrMore(assignment | funccall | match_expr);
|
||||
|
||||
section_name = pp.Regex('\.[a-zA-Z0-9_.]+')
|
||||
section_def = pp.Group(section_name + pp.Optional(numeric_literal) + COLON + LBRACE + pp.Group(section_contents) +
|
||||
RBRACE + pp.Optional(RBROK + ppc.identifier + pp.Optional('AT' + RBROK + ppc.identifier)))
|
||||
sec_contents = pp.ZeroOrMore(section_def | assignment)
|
||||
|
||||
sections_toplevel = pp.Group(pp.CaselessKeyword("SECTIONS").suppress() + LBRACE + sec_contents + RBRACE)
|
||||
|
||||
toplevel_elements = mem_toplevel | funccall | sections_toplevel | assignment
|
||||
ldscript = pp.Group(pp.ZeroOrMore(toplevel_elements))
|
||||
ldscript.ignore(pp.cppStyleComment)
|
||||
|
||||
if __name__ == '__main__':
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('linker_script', type=argparse.FileType('r'))
|
||||
args = parser.parse_args()
|
||||
|
||||
#print(mem_expr.parseString('FLASH (rx) : ORIGIN = 0x0800000, LENGTH = 512K', parseAll=True))
|
||||
# print(ldscript.parseString('''
|
||||
# /* Entry Point */
|
||||
# ENTRY(Reset_Handler)
|
||||
#
|
||||
# /* Highest address of the user mode stack */
|
||||
# _estack = 0x20020000; /* end of RAM */
|
||||
# /* Generate a link error if heap and stack don't fit into RAM */
|
||||
# _Min_Heap_Size = 0x200;; /* required amount of heap */
|
||||
# _Min_Stack_Size = 0x400;; /* required amount of stack */
|
||||
# ''', parseAll=True))
|
||||
|
||||
print(ldscript.parseFile(args.linker_script, parseAll=True))
|
||||
#print(funccall.parseString('KEEP(*(.isr_vector))'))
|
||||
#print(section_contents.parseString('''
|
||||
# . = ALIGN(4);
|
||||
# KEEP(*(.isr_vector)) /* Startup code */
|
||||
# . = ALIGN(4);
|
||||
# ''', parseAll=True))
|
||||
|
||||
#print(section_def.parseString('''
|
||||
# .text :
|
||||
# {
|
||||
# . = ALIGN(4);
|
||||
# *(.text) /* .text sections (code) */
|
||||
# *(.text*) /* .text* sections (code) */
|
||||
# *(.glue_7) /* glue arm to thumb code */
|
||||
# *(.glue_7t) /* glue thumb to arm code */
|
||||
# *(.eh_frame)
|
||||
#
|
||||
# KEEP (*(.init))
|
||||
# KEEP (*(.fini))
|
||||
#
|
||||
# . = ALIGN(4);
|
||||
# _etext = .; /* define a global symbols at end of code */
|
||||
# } >FLASH
|
||||
# ''', parseAll=True))
|
||||
|
||||
#print(section_def.parseString('.ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH', parseAll=True))
|
||||
|
||||
#print(assignment.parseString('__preinit_array_start = .', parseAll=True))
|
||||
#print(assignment.parseString('a = 23', parseAll=True))
|
||||
#print(funccall.parseString('foo (a=23)', parseAll=True))
|
||||
#print(funccall.parseString('PROVIDE_HIDDEN (__preinit_array_start = .);', parseAll=True))
|
||||
#print(section_def.parseString('''
|
||||
# .preinit_array :
|
||||
# {
|
||||
# PROVIDE_HIDDEN (__preinit_array_start = .);
|
||||
# KEEP (*(.preinit_array*))
|
||||
# PROVIDE_HIDDEN (__preinit_array_end = .);
|
||||
# } >FLASH''', parseAll=True))
|
||||
#print(match_expr.parseString('*(SORT(.init_array.*))', parseAll=True))
|
||||
#print(funccall.parseString('KEEP (*(SORT(.init_array.*)))', parseAll=True))
|
||||
#print(section_def.parseString('''
|
||||
# .init_array :
|
||||
# {
|
||||
# PROVIDE_HIDDEN (__init_array_start = .);
|
||||
# KEEP (*(SORT(.init_array.*)))
|
||||
# KEEP (*(.init_array*))
|
||||
# PROVIDE_HIDDEN (__init_array_end = .);
|
||||
# } >FLASH
|
||||
# ''', parseAll=True))
|
||||
|
||||
#print(match_expr.parseString('*(.ARM.extab* .gnu.linkonce.armextab.*)', parseAll=True))
|
||||
#print(formula.parseString('. + _Min_Heap_Size', parseAll=True))
|
||||
#print(assignment.parseString('. = . + _Min_Heap_Size;', parseAll=True))
|
||||
#print(sections_toplevel.parseString('''
|
||||
# SECTIONS
|
||||
# {
|
||||
# .ARMattributes : { }
|
||||
# }
|
||||
# ''', parseAll=True))
|
||||
#sys.exit(0)
|
||||
|
||||
276
tools/linkmem.py
Normal file
276
tools/linkmem.py
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
|
||||
import tempfile
|
||||
import os
|
||||
from os import path
|
||||
import sys
|
||||
import re
|
||||
import subprocess
|
||||
from contextlib import contextmanager
|
||||
from collections import defaultdict
|
||||
import colorsys
|
||||
|
||||
import cxxfilt
|
||||
from elftools.elf.elffile import ELFFile
|
||||
from elftools.elf.enums import ENUM_ST_SHNDX
|
||||
from elftools.elf.descriptions import describe_symbol_type, describe_sh_type
|
||||
import libarchive
|
||||
import matplotlib.cm
|
||||
|
||||
@contextmanager
|
||||
def chdir(newdir):
|
||||
old_cwd = os.getcwd()
|
||||
try:
|
||||
os.chdir(newdir)
|
||||
yield
|
||||
finally:
|
||||
os.chdir(old_cwd)
|
||||
|
||||
def keep_last(it, first=None):
|
||||
last = first
|
||||
for elem in it:
|
||||
yield last, elem
|
||||
last = elem
|
||||
|
||||
def delim(start, end, it, first_only=True):
|
||||
found = False
|
||||
for elem in it:
|
||||
if end(elem):
|
||||
if first_only:
|
||||
return
|
||||
found = False
|
||||
elif start(elem):
|
||||
found = True
|
||||
elif found:
|
||||
yield elem
|
||||
|
||||
def delim_prefix(start, end, it):
|
||||
yield from delim(lambda l: l.startswith(start), lambda l: end is not None and l.startswith(end), it)
|
||||
|
||||
def trace_source_files(linker, cmdline, trace_sections=[], total_sections=['.text', '.data', '.rodata']):
|
||||
with tempfile.TemporaryDirectory() as tempdir:
|
||||
out_path = path.join(tempdir, 'output.elf')
|
||||
output = subprocess.check_output([linker, '-o', out_path, f'-Wl,--print-map', *cmdline])
|
||||
lines = [ line.strip() for line in output.decode().splitlines() ]
|
||||
# FIXME also find isr vector table references
|
||||
|
||||
defs = {}
|
||||
objs = defaultdict(lambda: 0)
|
||||
aliases = {}
|
||||
sec_name = None
|
||||
last_loc = None
|
||||
last_sym = None
|
||||
line_cont = None
|
||||
for last_line, line in keep_last(delim_prefix('Linker script and memory map', 'OUTPUT', lines), first=''):
|
||||
if not line or line.startswith('LOAD '):
|
||||
sec_name = None
|
||||
continue
|
||||
|
||||
# first part of continuation line
|
||||
if m := re.match(r'^(\.[0-9a-zA-Z-_.]+)$', line):
|
||||
line_cont = line
|
||||
sec_name = None
|
||||
continue
|
||||
|
||||
if line_cont:
|
||||
line = line_cont + ' ' + line
|
||||
line_cont = None
|
||||
|
||||
# -ffunction-sections/-fdata-sections section
|
||||
if m := re.match(r'^(\.[0-9a-zA-Z-_.]+)\.([0-9a-zA-Z-_.]+)\s+(0x[0-9a-f]+)\s+(0x[0-9a-f]+)\s+(\S+)$', line):
|
||||
sec, sym, loc, size, obj = m.groups()
|
||||
*_, sym = sym.rpartition('.')
|
||||
sym = cxxfilt.demangle(sym)
|
||||
size = int(size, 16)
|
||||
obj = path.abspath(obj)
|
||||
|
||||
if sec not in total_sections:
|
||||
size = 0
|
||||
|
||||
objs[obj] += size
|
||||
defs[sym] = (sec, size, obj)
|
||||
|
||||
sec_name, last_loc, last_sym = sec, loc, sym
|
||||
continue
|
||||
|
||||
# regular (no -ffunction-sections/-fdata-sections) section
|
||||
if m := re.match(r'^(\.[0-9a-zA-Z-_]+)\s+(0x[0-9a-f]+)\s+(0x[0-9a-f]+)\s+(\S+)$', line):
|
||||
sec, _loc, size, obj = m.groups()
|
||||
size = int(size, 16)
|
||||
obj = path.abspath(obj)
|
||||
|
||||
if sec in total_sections:
|
||||
objs[obj] += size
|
||||
|
||||
sec_name = sec
|
||||
last_loc, last_sym = None, None
|
||||
continue
|
||||
|
||||
# symbol def
|
||||
if m := re.match(r'^(0x[0-9a-f]+)\s+(\S+)$', line):
|
||||
loc, sym = m.groups()
|
||||
sym = cxxfilt.demangle(sym)
|
||||
loc = int(loc, 16)
|
||||
if sym in defs:
|
||||
continue
|
||||
|
||||
if loc == last_loc:
|
||||
assert last_sym is not None
|
||||
aliases[sym] = last_sym
|
||||
else:
|
||||
assert sec_name
|
||||
defs[sym] = (sec_name, None, obj)
|
||||
last_loc, last_sym = loc, sym
|
||||
|
||||
continue
|
||||
|
||||
refs = defaultdict(lambda: set())
|
||||
for sym, (sec, size, obj) in defs.items():
|
||||
fn, _, member = re.match(r'^([^()]+)(\((.+)\))?$', obj).groups()
|
||||
fn = path.abspath(fn)
|
||||
|
||||
if member:
|
||||
subprocess.check_call(['ar', 'x', '--output', tempdir, fn, member])
|
||||
fn = path.join(tempdir, member)
|
||||
|
||||
with open(fn, 'rb') as f:
|
||||
elf = ELFFile(f)
|
||||
|
||||
symtab = elf.get_section_by_name('.symtab')
|
||||
|
||||
symtab_demangled = { cxxfilt.demangle(nsym.name).replace(' ', ''): i
|
||||
for i, nsym in enumerate(symtab.iter_symbols()) }
|
||||
|
||||
s = set()
|
||||
sec_map = { sec.name: i for i, sec in enumerate(elf.iter_sections()) }
|
||||
matches = [ i for name, i in sec_map.items() if re.match(fr'\.rel\..*\.{sym}', name) ]
|
||||
if matches:
|
||||
sec = elf.get_section(matches[0])
|
||||
for reloc in sec.iter_relocations():
|
||||
refsym = symtab.get_symbol(reloc['r_info_sym'])
|
||||
name = refsym.name if refsym.name else elf.get_section(refsym['st_shndx']).name.split('.')[-1]
|
||||
s.add(name)
|
||||
refs[sym] = s
|
||||
|
||||
for tsec in trace_sections:
|
||||
matches = [ i for name, i in sec_map.items() if name == f'.rel{tsec}' ]
|
||||
s = set()
|
||||
if matches:
|
||||
sec = elf.get_section(matches[0])
|
||||
for reloc in sec.iter_relocations():
|
||||
refsym = symtab.get_symbol(reloc['r_info_sym'])
|
||||
s.add(refsym.name)
|
||||
refs[tsec.replace('.', '_')] |= s
|
||||
|
||||
return objs, aliases, defs, refs
|
||||
|
||||
@contextmanager
|
||||
def wrap(leader='', print=print, left='{', right='}'):
|
||||
print(leader, left)
|
||||
yield lambda *args, **kwargs: print(' ', *args, **kwargs)
|
||||
print(right)
|
||||
|
||||
def mangle(name):
|
||||
return re.sub('[^a-zA-Z0-9_]', '_', name)
|
||||
|
||||
hexcolor = lambda r, g, b, *_a: f'#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}'
|
||||
def vhex(val):
|
||||
r,g,b,_a = matplotlib.cm.viridis(1.0-val)
|
||||
fc = hexcolor(r, g, b)
|
||||
h,s,v = colorsys.rgb_to_hsv(r,g,b)
|
||||
cc = '#000000' if v > 0.8 else '#ffffff'
|
||||
return fc, cc
|
||||
|
||||
if __name__ == '__main__':
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--trace-sections', type=str, action='append', default=[])
|
||||
parser.add_argument('--trim-stubs', type=str, action='append', default=[])
|
||||
parser.add_argument('--highlight-subdirs', type=str, default=None)
|
||||
parser.add_argument('linker_binary')
|
||||
parser.add_argument('linker_args', nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args()
|
||||
|
||||
trace_sections = args.trace_sections
|
||||
trace_sections_mangled = { sec.replace('.', '_') for sec in trace_sections }
|
||||
objs, aliases, syms, refs = trace_source_files(args.linker_binary, args.linker_args, trace_sections)
|
||||
|
||||
clusters = defaultdict(lambda: [])
|
||||
for sym, (sec, size, obj) in syms.items():
|
||||
clusters[obj].append((sym, sec, size))
|
||||
|
||||
max_ssize = max(size or 0 for _sec, size, _obj in syms.values())
|
||||
max_osize = max(objs.values())
|
||||
|
||||
subdir_prefix = path.abspath(args.highlight_subdirs) + '/' if args.highlight_subdirs else '### NO HIGHLIGHT ###'
|
||||
first_comp = lambda le_path: path.dirname(le_path).partition(os.sep)[0]
|
||||
subdir_colors = sorted({ first_comp(obj[len(subdir_prefix):]) for obj in objs if obj.startswith(subdir_prefix) })
|
||||
subdir_colors = { path: hexcolor(*matplotlib.cm.Pastel1(i/len(subdir_colors))) for i, path in enumerate(subdir_colors) }
|
||||
|
||||
subdir_sizes = defaultdict(lambda: 0)
|
||||
for obj, size in objs.items():
|
||||
if not isinstance(size, int):
|
||||
continue
|
||||
if obj.startswith(subdir_prefix):
|
||||
subdir_sizes[first_comp(obj[len(subdir_prefix):])] += size
|
||||
else:
|
||||
subdir_sizes['<others>'] += size
|
||||
|
||||
print('Subdir sizes:', file=sys.stderr)
|
||||
for subdir, size in sorted(subdir_sizes.items(), key=lambda x: x[1]):
|
||||
print(f'{subdir:>20}: {size:>6,d} B', file=sys.stderr)
|
||||
|
||||
def lookup_highlight(path):
|
||||
if args.highlight_subdirs:
|
||||
if obj.startswith(subdir_prefix):
|
||||
highlight_head = first_comp(path[len(subdir_prefix):])
|
||||
return subdir_colors[highlight_head], highlight_head
|
||||
else:
|
||||
return '#e0e0e0', None
|
||||
else:
|
||||
return '#ddf7f4', None
|
||||
|
||||
with wrap('digraph G', print) as lvl1print:
|
||||
print('size="23.4,16.5!";')
|
||||
print('graph [fontsize=40];')
|
||||
print('node [fontsize=40];')
|
||||
#print('ratio="fill";')
|
||||
|
||||
print('rankdir=LR;')
|
||||
print('ranksep=5;')
|
||||
print('nodesep=0.2;')
|
||||
print()
|
||||
|
||||
for i, (obj, obj_syms) in enumerate(clusters.items()):
|
||||
with wrap(f'subgraph cluster_{i}', lvl1print) as lvl2print:
|
||||
print('style = "filled";')
|
||||
highlight_color, highlight_head = lookup_highlight(obj)
|
||||
print(f'bgcolor = "{highlight_color}";')
|
||||
print('pencolor = none;')
|
||||
fc, cc = vhex(objs[obj]/max_osize)
|
||||
highlight_subdir_part = f'<font face="carlito" color="{cc}" point-size="40">{highlight_head} / </font>' if highlight_head else ''
|
||||
lvl2print(f'label = <<table border="0"><tr><td border="0" cellpadding="5" bgcolor="{fc}">'
|
||||
f'{highlight_subdir_part}'
|
||||
f'<font face="carlito" color="{cc}"><b>{path.basename(obj)} ({objs[obj]}B)</b></font>'
|
||||
f'</td></tr></table>>;')
|
||||
lvl2print()
|
||||
for sym, sec, size in obj_syms:
|
||||
has_size = isinstance(size, int) and size > 0
|
||||
size_s = f' ({size}B)' if has_size else ''
|
||||
fc, cc = vhex(size/max_ssize) if has_size else ('#ffffff', '#000000')
|
||||
shape = 'box' if sec == '.text' else 'oval'
|
||||
lvl2print(f'{mangle(sym)}[label = "{sym}{size_s}", style="rounded,filled", shape="{shape}", fillcolor="{fc}", fontname="carlito", fontcolor="{cc}" color=none];')
|
||||
lvl1print()
|
||||
|
||||
edges = set()
|
||||
for start, ends in refs.items():
|
||||
for end in ends:
|
||||
end = aliases.get(end, end)
|
||||
if (start in syms or start in trace_sections_mangled) and end in syms:
|
||||
edges.add((start, end))
|
||||
|
||||
for start, end in edges:
|
||||
lvl1print(f'{mangle(start)} -> {mangle(end)} [style="bold", color="#333333"];')
|
||||
|
||||
for sec in trace_sections:
|
||||
lvl1print(f'{sec.replace(".", "_")} [label = "section {sec}", shape="box", style="filled,bold"];')
|
||||
|
||||
62
tools/linksize.py
Normal file
62
tools/linksize.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
def parse_linker_script(data):
|
||||
pass
|
||||
|
||||
def link(groups):
|
||||
defined_symbols = {}
|
||||
undefined_symbols = set()
|
||||
for group, files in groups:
|
||||
while True:
|
||||
found_something = False
|
||||
|
||||
for fn in files:
|
||||
symbols = load_symbols(fn)
|
||||
for symbol in symbols:
|
||||
if symbol in defined_symbols:
|
||||
|
||||
if not group or not found_something:
|
||||
break
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-T', '--script', type=str, help='Linker script to use')
|
||||
parser.add_argument('-o', '--output', type=str, help='Output file to produce')
|
||||
args, rest = parser.parse_known_intermixed_args()
|
||||
print(rest)
|
||||
|
||||
addprefix = lambda *xs: [ prefix + opt for opt in xs for prefix in ('', '-Wl,') ]
|
||||
START_GROUP = addprefix('-(', '--start-group')
|
||||
END_GROUP = addprefix('-)', '--end-group')
|
||||
GROUP_OPTS = [*START_GROUP, *END_GROUP]
|
||||
input_files = [ arg for arg in rest if not arg.startswith('-') or arg in GROUP_OPTS ]
|
||||
|
||||
def input_file_iter(input_files):
|
||||
group = False
|
||||
files = []
|
||||
for arg in input_files:
|
||||
if arg in START_GROUP:
|
||||
assert not group
|
||||
|
||||
if files:
|
||||
yield False, files # nested -Wl,--start-group
|
||||
group, files = True, []
|
||||
|
||||
elif arg in END_GROUP:
|
||||
assert group # missing -Wl,--start-group
|
||||
if files:
|
||||
yield True, files
|
||||
group, files = False, []
|
||||
|
||||
else:
|
||||
files.append(arg)
|
||||
|
||||
assert not group # missing -Wl,--end-group
|
||||
if files:
|
||||
yield False, files
|
||||
|
||||
|
||||
|
||||
118
tools/linktracer.py
Normal file
118
tools/linktracer.py
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import pprint
|
||||
|
||||
ARCHIVE_RE = r'([^(]*)(\([^)]*\))?'
|
||||
|
||||
def trace_source_files(linker, cmdline):
|
||||
with tempfile.NamedTemporaryFile() as mapfile:
|
||||
output = subprocess.check_output([linker, f'-Wl,--Map={mapfile.name}', *cmdline])
|
||||
|
||||
# intentionally use generator here
|
||||
idx = 0
|
||||
lines = [ line.rstrip() for line in mapfile.read().decode().splitlines() if line.strip() ]
|
||||
|
||||
for idx, line in enumerate(lines[idx:], start=idx):
|
||||
#print('Dropping', line)
|
||||
if line == 'Linker script and memory map':
|
||||
break
|
||||
|
||||
idx += 1
|
||||
objects = []
|
||||
symbols = {}
|
||||
sections = {}
|
||||
current_object = None
|
||||
last_offset = None
|
||||
last_symbol = None
|
||||
cont_sec = None
|
||||
cont_ind = None
|
||||
current_section = None
|
||||
for idx, line in enumerate(lines[idx:], start=idx):
|
||||
print(f'Processing >{line}')
|
||||
if line.startswith('LOAD'):
|
||||
_load, obj = line.split()
|
||||
objects.append(obj)
|
||||
continue
|
||||
|
||||
if line.startswith('OUTPUT'):
|
||||
break
|
||||
|
||||
m = re.match(r'^( ?)([^ ]+)? +(0x[0-9a-z]+) +(0x[0-9a-z]+)?(.*)?$', line)
|
||||
if m is None:
|
||||
m = re.match(r'^( ?)([^ ]+)?$', line)
|
||||
if m:
|
||||
cont_ind, cont_sec = m.groups()
|
||||
else:
|
||||
cont_ind, cont_sec = None, None
|
||||
last_offset, last_symbol = None, None
|
||||
continue
|
||||
indent, sec, offx, size, sym_or_src = m.groups()
|
||||
if sec is None:
|
||||
sec = cont_sec
|
||||
ind = cont_ind
|
||||
cont_sec = None
|
||||
cont_ind = None
|
||||
print(f'vals: indent={indent} sec={sec} offx={offx} size={size} sym_or_src={sym_or_src}')
|
||||
if not re.match('^[a-zA-Z_0-9<>():*]+$', sym_or_src):
|
||||
continue
|
||||
|
||||
if indent == '':
|
||||
print(f'Section: {sec} 0x{size:x}')
|
||||
current_section = sec
|
||||
sections[sec] = size
|
||||
last_offset = None
|
||||
last_symbol = None
|
||||
continue
|
||||
|
||||
if offx is not None:
|
||||
offx = int(offx, 16)
|
||||
if size is not None:
|
||||
size = int(size, 16)
|
||||
|
||||
if size is not None and sym_or_src is not None:
|
||||
# archive/object line
|
||||
archive, _member = re.match(ARCHIVE_RE, sym_or_src).groups()
|
||||
current_object = archive
|
||||
last_offset = offx
|
||||
else:
|
||||
if sym_or_src is not None:
|
||||
assert size is None
|
||||
if last_offset is not None:
|
||||
last_size = offx - last_offset
|
||||
symbols[last_symbol] = (last_size, current_section)
|
||||
print(f'Symbol: {last_symbol} 0x{last_size:x} @{current_section}')
|
||||
last_offset = offx
|
||||
last_symbol = sym_or_src
|
||||
|
||||
idx += 1
|
||||
|
||||
for idx, line in enumerate(lines[idx:], start=idx):
|
||||
if line == 'Cross Reference Table':
|
||||
break
|
||||
|
||||
idx += 1
|
||||
|
||||
# map which symbol was pulled from which object in the end
|
||||
used_defs = {}
|
||||
for line in lines:
|
||||
*left, right = line.split()
|
||||
|
||||
archive, _member = re.match(ARCHIVE_RE, right).groups()
|
||||
if left:
|
||||
used_defs[''.join(left)] = archive
|
||||
|
||||
#pprint.pprint(symbols)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('linker_binary')
|
||||
parser.add_argument('linker_args', nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args()
|
||||
|
||||
source_files = trace_source_files(args.linker_binary, args.linker_args)
|
||||
|
||||
129
tools/mapparse.py
Normal file
129
tools/mapparse.py
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
|
||||
import re
|
||||
from collections import defaultdict, namedtuple
|
||||
|
||||
Section = namedtuple('Section', ['name', 'offset', 'objects'])
|
||||
ObjectEntry = namedtuple('ObjectEntry', ['filename', 'object', 'offset', 'size'])
|
||||
FileEntry = namedtuple('FileEntry', ['section', 'object', 'offset', 'length'])
|
||||
|
||||
class Memory:
|
||||
def __init__(self, name, origin, length, attrs=''):
|
||||
self.name, self.origin, self.length, self.attrs = name, origin, length, attrs
|
||||
self.sections = {}
|
||||
self.files = defaultdict(lambda: [])
|
||||
self.totals = defaultdict(lambda: 0)
|
||||
|
||||
def add_toplevel(self, name, offx, length):
|
||||
self.sections[name] = Section(offx, length, [])
|
||||
|
||||
def add_obj(self, name, offx, length, fn, obj):
|
||||
base_section, sep, subsec = name[1:].partition('.')
|
||||
base_section = '.'+base_section
|
||||
if base_section in self.sections:
|
||||
sec = secname, secoffx, secobjs = self.sections[base_section]
|
||||
secobjs.append(ObjectEntry(fn, obj, offx, length))
|
||||
else:
|
||||
sec = None
|
||||
self.files[fn].append(FileEntry(sec, obj, offx, length))
|
||||
self.totals[fn] += length
|
||||
|
||||
class MapFile:
|
||||
def __init__(self, s):
|
||||
self._lines = s.splitlines()
|
||||
self.memcfg = {}
|
||||
self.defaultmem = Memory('default', 0, 0xffffffffffffffff)
|
||||
self._parse()
|
||||
|
||||
def __getitem__(self, offx_or_name):
|
||||
''' Lookup a memory area by name or address '''
|
||||
if offx_or_name in self.memcfg:
|
||||
return self.memcfg[offx_or_name]
|
||||
|
||||
elif isinstance(offx_or_name, int):
|
||||
for mem in self.memcfg.values():
|
||||
if mem.origin <= offx_or_name < mem.origin+mem.length:
|
||||
return mem
|
||||
else:
|
||||
return self.defaultmem
|
||||
|
||||
raise ValueError('Invalid argument type for indexing')
|
||||
|
||||
def _skip(self, regex):
|
||||
matcher = re.compile(regex)
|
||||
for l in self:
|
||||
if matcher.match(l):
|
||||
break
|
||||
|
||||
def __iter__(self):
|
||||
while self._lines:
|
||||
yield self._lines.pop(0)
|
||||
|
||||
def _parse(self):
|
||||
self._skip('^Memory Configuration')
|
||||
|
||||
# Parse memory segmentation info
|
||||
self._skip('^Name')
|
||||
for l in self:
|
||||
if not l:
|
||||
break
|
||||
name, origin, length, *attrs = l.split()
|
||||
if not name.startswith('*'):
|
||||
self.memcfg[name] = Memory(name, int(origin, 16), int(length, 16), attrs[0] if attrs else '')
|
||||
|
||||
# Parse section information
|
||||
toplevel_m = re.compile('^(\.[a-zA-Z0-9_.]+)\s+(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)')
|
||||
secondlevel_m = re.compile('^ (\.[a-zA-Z0-9_.]+)\s+(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)\s+(.*)$')
|
||||
secondlevel_linebreak_m = re.compile('^ (\.[a-zA-Z0-9_.]+)\n')
|
||||
filelike = re.compile('^(/?[^()]*\.[a-zA-Z0-9-_]+)(\(.*\))?')
|
||||
linebreak_section = None
|
||||
for l in self:
|
||||
# Toplevel section
|
||||
match = toplevel_m.match(l)
|
||||
if match:
|
||||
name, offx, length = match.groups()
|
||||
offx, length = int(offx, 16), int(length, 16)
|
||||
self[offx].add_toplevel(name, offx, length)
|
||||
|
||||
match = secondlevel_linebreak_m.match(l)
|
||||
if match:
|
||||
linebreak_section, = match.groups()
|
||||
continue
|
||||
|
||||
if linebreak_section:
|
||||
l = ' {} {}'.format(linebreak_section, l)
|
||||
linebreak_section = None
|
||||
|
||||
# Second-level section
|
||||
match = secondlevel_m.match(l)
|
||||
if match:
|
||||
name, offx, length, misc = match.groups()
|
||||
match = filelike.match(misc)
|
||||
if match:
|
||||
fn, obj = match.groups()
|
||||
obj = obj.strip('()') if obj else None
|
||||
offx, length = int(offx, 16), int(length, 16)
|
||||
self[offx].add_obj(name, offx, length, fn, obj)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description='Parser GCC map file')
|
||||
parser.add_argument('mapfile', type=argparse.FileType('r'), help='The GCC .map file to parse')
|
||||
parser.add_argument('-m', '--memory', type=str, help='The memory segments to print, comma-separated')
|
||||
args = parser.parse_args()
|
||||
mf = MapFile(args.mapfile.read())
|
||||
args.mapfile.close()
|
||||
|
||||
mems = args.memory.split(',') if args.memory else mf.memcfg.keys()
|
||||
|
||||
for name in mems:
|
||||
mem = mf.memcfg[name]
|
||||
print('Symbols by file for memory', name)
|
||||
for tot, fn in reversed(sorted( (tot, fn) for fn, tot in mem.totals.items() )):
|
||||
print(' {:>8} {}'.format(tot, fn))
|
||||
for length, offx, sec, obj in reversed(sorted(( (length, offx, sec, obj) for sec, obj, offx, length in
|
||||
mem.files[fn] ), key=lambda e: e[0] )):
|
||||
name = sec.name if sec else None
|
||||
print(' {:>8} {:>#08x} {}'.format(length, offx, obj))
|
||||
#print('{:>16} 0x{:016x} 0x{:016x} ({:>24}) {}'.format(name, origin, length, length, attrs))
|
||||
|
||||
23
tools/musl_include_shims/bits/alltypes.h
Normal file
23
tools/musl_include_shims/bits/alltypes.h
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
|
||||
/* shim file for musl */
|
||||
|
||||
#ifndef __MUSL_SHIM_BITS_ALLTYPES_H__
|
||||
#define __MUSL_SHIM_BITS_ALLTYPES_H__
|
||||
|
||||
#define _REDIR_TIME64 1
|
||||
#define _Addr int
|
||||
#define _Int64 long long
|
||||
#define _Reg int
|
||||
|
||||
#define __BYTE_ORDER 1234
|
||||
|
||||
#define __LONG_MAX 0x7fffffffL
|
||||
|
||||
#ifndef __cplusplus
|
||||
typedef unsigned wchar_t;
|
||||
#endif
|
||||
|
||||
typedef float float_t;
|
||||
typedef double double_t;
|
||||
|
||||
#endif /* __MUSL_SHIM_BITS_ALLTYPES_H__ */
|
||||
80
tools/musl_include_shims/endian.h
Normal file
80
tools/musl_include_shims/endian.h
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
#ifndef _ENDIAN_H
|
||||
#define _ENDIAN_H
|
||||
|
||||
#include <features.h>
|
||||
|
||||
#define __NEED_uint16_t
|
||||
#define __NEED_uint32_t
|
||||
#define __NEED_uint64_t
|
||||
|
||||
#include <bits/alltypes.h>
|
||||
|
||||
#define __PDP_ENDIAN 3412
|
||||
|
||||
#define BIG_ENDIAN __BIG_ENDIAN
|
||||
#define LITTLE_ENDIAN __LITTLE_ENDIAN
|
||||
#define PDP_ENDIAN __PDP_ENDIAN
|
||||
#define BYTE_ORDER __BYTE_ORDER
|
||||
|
||||
static __inline uint16_t __bswap16(uint16_t __x)
|
||||
{
|
||||
return __x<<8 | __x>>8;
|
||||
}
|
||||
|
||||
static __inline uint32_t __bswap32(uint32_t __x)
|
||||
{
|
||||
return __x>>24 | __x>>8&0xff00 | __x<<8&0xff0000 | __x<<24;
|
||||
}
|
||||
|
||||
static __inline uint64_t __bswap64(uint64_t __x)
|
||||
{
|
||||
return __bswap32(__x)+0ULL<<32 | __bswap32(__x>>32);
|
||||
}
|
||||
|
||||
#if __BYTE_ORDER == __LITTLE_ENDIAN
|
||||
#define htobe16(x) __bswap16(x)
|
||||
#define be16toh(x) __bswap16(x)
|
||||
#define htobe32(x) __bswap32(x)
|
||||
#define be32toh(x) __bswap32(x)
|
||||
#define htobe64(x) __bswap64(x)
|
||||
#define be64toh(x) __bswap64(x)
|
||||
#define htole16(x) (uint16_t)(x)
|
||||
#define le16toh(x) (uint16_t)(x)
|
||||
#define htole32(x) (uint32_t)(x)
|
||||
#define le32toh(x) (uint32_t)(x)
|
||||
#define htole64(x) (uint64_t)(x)
|
||||
#define le64toh(x) (uint64_t)(x)
|
||||
#else
|
||||
#define htobe16(x) (uint16_t)(x)
|
||||
#define be16toh(x) (uint16_t)(x)
|
||||
#define htobe32(x) (uint32_t)(x)
|
||||
#define be32toh(x) (uint32_t)(x)
|
||||
#define htobe64(x) (uint64_t)(x)
|
||||
#define be64toh(x) (uint64_t)(x)
|
||||
#define htole16(x) __bswap16(x)
|
||||
#define le16toh(x) __bswap16(x)
|
||||
#define htole32(x) __bswap32(x)
|
||||
#define le32toh(x) __bswap32(x)
|
||||
#define htole64(x) __bswap64(x)
|
||||
#define le64toh(x) __bswap64(x)
|
||||
#endif
|
||||
|
||||
#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
|
||||
#if __BYTE_ORDER == __LITTLE_ENDIAN
|
||||
#define betoh16(x) __bswap16(x)
|
||||
#define betoh32(x) __bswap32(x)
|
||||
#define betoh64(x) __bswap64(x)
|
||||
#define letoh16(x) (uint16_t)(x)
|
||||
#define letoh32(x) (uint32_t)(x)
|
||||
#define letoh64(x) (uint64_t)(x)
|
||||
#else
|
||||
#define betoh16(x) (uint16_t)(x)
|
||||
#define betoh32(x) (uint32_t)(x)
|
||||
#define betoh64(x) (uint64_t)(x)
|
||||
#define letoh16(x) __bswap16(x)
|
||||
#define letoh32(x) __bswap32(x)
|
||||
#define letoh64(x) __bswap64(x)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#endif
|
||||
40
tools/musl_include_shims/features.h
Normal file
40
tools/musl_include_shims/features.h
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
#ifndef _FEATURES_H
|
||||
#define _FEATURES_H
|
||||
|
||||
#if defined(_ALL_SOURCE) && !defined(_GNU_SOURCE)
|
||||
#define _GNU_SOURCE 1
|
||||
#endif
|
||||
|
||||
#if defined(_DEFAULT_SOURCE) && !defined(_BSD_SOURCE)
|
||||
#define _BSD_SOURCE 1
|
||||
#endif
|
||||
|
||||
#if !defined(_POSIX_SOURCE) && !defined(_POSIX_C_SOURCE) \
|
||||
&& !defined(_XOPEN_SOURCE) && !defined(_GNU_SOURCE) \
|
||||
&& !defined(_BSD_SOURCE) && !defined(__STRICT_ANSI__)
|
||||
#define _BSD_SOURCE 1
|
||||
#define _XOPEN_SOURCE 700
|
||||
#endif
|
||||
|
||||
#if __STDC_VERSION__ >= 199901L
|
||||
#define __restrict restrict
|
||||
#elif !defined(__GNUC__)
|
||||
#define __restrict
|
||||
#endif
|
||||
|
||||
#if __STDC_VERSION__ >= 199901L || defined(__cplusplus)
|
||||
#define __inline inline
|
||||
#elif !defined(__GNUC__)
|
||||
#define __inline
|
||||
#endif
|
||||
|
||||
#if __STDC_VERSION__ >= 201112L
|
||||
#elif defined(__GNUC__)
|
||||
#define _Noreturn __attribute__((__noreturn__))
|
||||
#else
|
||||
#define _Noreturn
|
||||
#endif
|
||||
|
||||
#define __REDIR(x,y) __typeof__(x) x __asm__(#y)
|
||||
|
||||
#endif
|
||||
6
tools/musl_include_shims/fp_arch.h
Normal file
6
tools/musl_include_shims/fp_arch.h
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
#ifndef __MUSL_SHIM_FP_ARCH_H__
|
||||
#define __MUSL_SHIM_FP_ARCH_H__
|
||||
|
||||
#define hidden
|
||||
|
||||
#endif /* __MUSL_SHIM_FP_ARCH_H__ */
|
||||
270
tools/musl_include_shims/libm.h
Normal file
270
tools/musl_include_shims/libm.h
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
#ifndef _LIBM_H
|
||||
#define _LIBM_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <float.h>
|
||||
#include <math.h>
|
||||
#include <endian.h>
|
||||
#include "fp_arch.h"
|
||||
|
||||
#if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
|
||||
#elif LDBL_MANT_DIG == 64 && LDBL_MAX_EXP == 16384 && __BYTE_ORDER == __LITTLE_ENDIAN
|
||||
union ldshape {
|
||||
long double f;
|
||||
struct {
|
||||
uint64_t m;
|
||||
uint16_t se;
|
||||
} i;
|
||||
};
|
||||
#elif LDBL_MANT_DIG == 64 && LDBL_MAX_EXP == 16384 && __BYTE_ORDER == __BIG_ENDIAN
|
||||
/* This is the m68k variant of 80-bit long double, and this definition only works
|
||||
* on archs where the alignment requirement of uint64_t is <= 4. */
|
||||
union ldshape {
|
||||
long double f;
|
||||
struct {
|
||||
uint16_t se;
|
||||
uint16_t pad;
|
||||
uint64_t m;
|
||||
} i;
|
||||
};
|
||||
#elif LDBL_MANT_DIG == 113 && LDBL_MAX_EXP == 16384 && __BYTE_ORDER == __LITTLE_ENDIAN
|
||||
union ldshape {
|
||||
long double f;
|
||||
struct {
|
||||
uint64_t lo;
|
||||
uint32_t mid;
|
||||
uint16_t top;
|
||||
uint16_t se;
|
||||
} i;
|
||||
struct {
|
||||
uint64_t lo;
|
||||
uint64_t hi;
|
||||
} i2;
|
||||
};
|
||||
#elif LDBL_MANT_DIG == 113 && LDBL_MAX_EXP == 16384 && __BYTE_ORDER == __BIG_ENDIAN
|
||||
union ldshape {
|
||||
long double f;
|
||||
struct {
|
||||
uint16_t se;
|
||||
uint16_t top;
|
||||
uint32_t mid;
|
||||
uint64_t lo;
|
||||
} i;
|
||||
struct {
|
||||
uint64_t hi;
|
||||
uint64_t lo;
|
||||
} i2;
|
||||
};
|
||||
#else
|
||||
#error Unsupported long double representation
|
||||
#endif
|
||||
|
||||
/* Support non-nearest rounding mode. */
|
||||
#define WANT_ROUNDING 1
|
||||
/* Support signaling NaNs. */
|
||||
#define WANT_SNAN 0
|
||||
|
||||
#if WANT_SNAN
|
||||
#error SNaN is unsupported
|
||||
#else
|
||||
#define issignalingf_inline(x) 0
|
||||
#define issignaling_inline(x) 0
|
||||
#endif
|
||||
|
||||
#ifndef TOINT_INTRINSICS
|
||||
#define TOINT_INTRINSICS 0
|
||||
#endif
|
||||
|
||||
#if TOINT_INTRINSICS
|
||||
/* Round x to nearest int in all rounding modes, ties have to be rounded
|
||||
consistently with converttoint so the results match. If the result
|
||||
would be outside of [-2^31, 2^31-1] then the semantics is unspecified. */
|
||||
static double_t roundtoint(double_t);
|
||||
|
||||
/* Convert x to nearest int in all rounding modes, ties have to be rounded
|
||||
consistently with roundtoint. If the result is not representible in an
|
||||
int32_t then the semantics is unspecified. */
|
||||
static int32_t converttoint(double_t);
|
||||
#endif
|
||||
|
||||
/* Helps static branch prediction so hot path can be better optimized. */
|
||||
#ifdef __GNUC__
|
||||
#define predict_true(x) __builtin_expect(!!(x), 1)
|
||||
#define predict_false(x) __builtin_expect(x, 0)
|
||||
#else
|
||||
#define predict_true(x) (x)
|
||||
#define predict_false(x) (x)
|
||||
#endif
|
||||
|
||||
/* Evaluate an expression as the specified type. With standard excess
|
||||
precision handling a type cast or assignment is enough (with
|
||||
-ffloat-store an assignment is required, in old compilers argument
|
||||
passing and return statement may not drop excess precision). */
|
||||
|
||||
static inline float eval_as_float(float x)
|
||||
{
|
||||
float y = x;
|
||||
return y;
|
||||
}
|
||||
|
||||
static inline double eval_as_double(double x)
|
||||
{
|
||||
double y = x;
|
||||
return y;
|
||||
}
|
||||
|
||||
/* fp_barrier returns its input, but limits code transformations
|
||||
as if it had a side-effect (e.g. observable io) and returned
|
||||
an arbitrary value. */
|
||||
|
||||
#ifndef fp_barrierf
|
||||
#define fp_barrierf fp_barrierf
|
||||
static inline float fp_barrierf(float x)
|
||||
{
|
||||
volatile float y = x;
|
||||
return y;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef fp_barrier
|
||||
#define fp_barrier fp_barrier
|
||||
static inline double fp_barrier(double x)
|
||||
{
|
||||
volatile double y = x;
|
||||
return y;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef fp_barrierl
|
||||
#define fp_barrierl fp_barrierl
|
||||
static inline long double fp_barrierl(long double x)
|
||||
{
|
||||
volatile long double y = x;
|
||||
return y;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* fp_force_eval ensures that the input value is computed when that's
|
||||
otherwise unused. To prevent the constant folding of the input
|
||||
expression, an additional fp_barrier may be needed or a compilation
|
||||
mode that does so (e.g. -frounding-math in gcc). Then it can be
|
||||
used to evaluate an expression for its fenv side-effects only. */
|
||||
|
||||
#ifndef fp_force_evalf
|
||||
#define fp_force_evalf fp_force_evalf
|
||||
static inline void fp_force_evalf(float x)
|
||||
{
|
||||
volatile float y;
|
||||
y = x;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef fp_force_eval
|
||||
#define fp_force_eval fp_force_eval
|
||||
static inline void fp_force_eval(double x)
|
||||
{
|
||||
volatile double y;
|
||||
y = x;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef fp_force_evall
|
||||
#define fp_force_evall fp_force_evall
|
||||
static inline void fp_force_evall(long double x)
|
||||
{
|
||||
volatile long double y;
|
||||
y = x;
|
||||
}
|
||||
#endif
|
||||
|
||||
#define FORCE_EVAL(x) do { \
|
||||
if (sizeof(x) == sizeof(float)) { \
|
||||
fp_force_evalf(x); \
|
||||
} else if (sizeof(x) == sizeof(double)) { \
|
||||
fp_force_eval(x); \
|
||||
} else { \
|
||||
fp_force_evall(x); \
|
||||
} \
|
||||
} while(0)
|
||||
|
||||
#define asuint(f) ((union{float _f; uint32_t _i;}){f})._i
|
||||
#define asfloat(i) ((union{uint32_t _i; float _f;}){i})._f
|
||||
#define asuint64(f) ((union{double _f; uint64_t _i;}){f})._i
|
||||
#define asdouble(i) ((union{uint64_t _i; double _f;}){i})._f
|
||||
|
||||
#define EXTRACT_WORDS(hi,lo,d) \
|
||||
do { \
|
||||
uint64_t __u = asuint64(d); \
|
||||
(hi) = __u >> 32; \
|
||||
(lo) = (uint32_t)__u; \
|
||||
} while (0)
|
||||
|
||||
#define GET_HIGH_WORD(hi,d) \
|
||||
do { \
|
||||
(hi) = asuint64(d) >> 32; \
|
||||
} while (0)
|
||||
|
||||
#define GET_LOW_WORD(lo,d) \
|
||||
do { \
|
||||
(lo) = (uint32_t)asuint64(d); \
|
||||
} while (0)
|
||||
|
||||
#define INSERT_WORDS(d,hi,lo) \
|
||||
do { \
|
||||
(d) = asdouble(((uint64_t)(hi)<<32) | (uint32_t)(lo)); \
|
||||
} while (0)
|
||||
|
||||
#define SET_HIGH_WORD(d,hi) \
|
||||
INSERT_WORDS(d, hi, (uint32_t)asuint64(d))
|
||||
|
||||
#define SET_LOW_WORD(d,lo) \
|
||||
INSERT_WORDS(d, asuint64(d)>>32, lo)
|
||||
|
||||
#define GET_FLOAT_WORD(w,d) \
|
||||
do { \
|
||||
(w) = asuint(d); \
|
||||
} while (0)
|
||||
|
||||
#define SET_FLOAT_WORD(d,w) \
|
||||
do { \
|
||||
(d) = asfloat(w); \
|
||||
} while (0)
|
||||
|
||||
hidden int __rem_pio2_large(double*,double*,int,int,int);
|
||||
|
||||
hidden int __rem_pio2(double,double*);
|
||||
hidden double __sin(double,double,int);
|
||||
hidden double __cos(double,double);
|
||||
hidden double __tan(double,double,int);
|
||||
hidden double __expo2(double);
|
||||
|
||||
hidden int __rem_pio2f(float,double*);
|
||||
hidden float __sindf(double);
|
||||
hidden float __cosdf(double);
|
||||
hidden float __tandf(double,int);
|
||||
hidden float __expo2f(float);
|
||||
|
||||
hidden int __rem_pio2l(long double, long double *);
|
||||
hidden long double __sinl(long double, long double, int);
|
||||
hidden long double __cosl(long double, long double);
|
||||
hidden long double __tanl(long double, long double, int);
|
||||
|
||||
hidden long double __polevll(long double, const long double *, int);
|
||||
hidden long double __p1evll(long double, const long double *, int);
|
||||
|
||||
hidden double __lgamma_r(double, int *);
|
||||
hidden float __lgammaf_r(float, int *);
|
||||
|
||||
/* error handling functions */
|
||||
hidden float __math_xflowf(uint32_t, float);
|
||||
hidden float __math_uflowf(uint32_t);
|
||||
hidden float __math_oflowf(uint32_t);
|
||||
hidden float __math_divzerof(uint32_t);
|
||||
hidden float __math_invalidf(float);
|
||||
hidden double __math_xflow(uint32_t, double);
|
||||
hidden double __math_uflow(uint32_t);
|
||||
hidden double __math_oflow(uint32_t);
|
||||
hidden double __math_divzero(uint32_t);
|
||||
hidden double __math_invalid(double);
|
||||
|
||||
#endif
|
||||
188
tools/usb_test.py
Normal file
188
tools/usb_test.py
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
import time
|
||||
from pprint import pprint
|
||||
from enum import Enum
|
||||
from functools import cache
|
||||
from dataclasses import dataclass, fields, astuple
|
||||
import struct
|
||||
import binascii
|
||||
|
||||
import numpy as np
|
||||
import click
|
||||
import serial
|
||||
from cobs import cobs
|
||||
|
||||
class CobsSerial:
|
||||
def __init__(self, port, timeout):
|
||||
self.ser = serial.Serial(port, timeout=timeout)
|
||||
self.ser.flushOutput()
|
||||
self.ser.flushInput()
|
||||
self.ser.write(bytes([0])) # synchronize
|
||||
self.ser.flushOutput()
|
||||
|
||||
def write_packet(self, data):
|
||||
self.ser.write(cobs.encode(data))
|
||||
self.ser.write(bytes([0]))
|
||||
self.ser.flushOutput()
|
||||
|
||||
def read_packet(self):
|
||||
data = b''
|
||||
while (b := self.ser.read(1)):
|
||||
if b[0] == 0:
|
||||
break
|
||||
data += b
|
||||
|
||||
if data:
|
||||
return parse_packet(cobs.decode(data))
|
||||
else:
|
||||
return None
|
||||
|
||||
def command(self, command, args=b''):
|
||||
self.write_packet(bytes([command.value]) + args)
|
||||
return self.read_packet()
|
||||
|
||||
|
||||
class SerializableEnum(Enum):
|
||||
def __int__(self):
|
||||
return self.value
|
||||
|
||||
class PacketType(SerializableEnum):
|
||||
USBP_GET_STATUS = 0
|
||||
USBP_GET_MEASUREMENTS = 1
|
||||
USBP_SET_MOTOR = 2
|
||||
|
||||
class ErrorCode(Enum):
|
||||
ERR_SUCCESS = 0
|
||||
ERR_TIMEOUT = 1
|
||||
ERR_PHYSICAL_LAYER = 2
|
||||
ERR_FRAMING = 3
|
||||
ERR_PROTOCOL = 4
|
||||
ERR_DMA = 5
|
||||
ERR_BUSY = 6
|
||||
ERR_BUFFER_OVERFLOW = 7
|
||||
ERR_RX_OVERRUN = 8
|
||||
ERR_TX_OVERRUN = 9
|
||||
|
||||
class BoardConfig(Enum):
|
||||
BCFG_UNCONFIGURED = 0
|
||||
BCFG_DISPLAY = 1
|
||||
BCFG_MOTOR = 2
|
||||
BCFG_MEAS = 3
|
||||
|
||||
class Serialized:
|
||||
@classmethod
|
||||
def deserialize(kls, data):
|
||||
fields = struct.unpack(kls._struct_format(), data)
|
||||
mapped = [cast(val) for cast, val in zip(kls._struct_casts(), fields)]
|
||||
return kls(*mapped)
|
||||
|
||||
def serialize(self):
|
||||
mapped = [uncast(val) for uncast, val in zip(self._struct_uncasts(), astuple(self))]
|
||||
return struct.pack(self._struct_format(), *mapped)
|
||||
|
||||
@classmethod
|
||||
@cache
|
||||
def _struct_format(kls):
|
||||
return kls._parse_fields()[0]
|
||||
|
||||
@classmethod
|
||||
@cache
|
||||
def _struct_casts(kls):
|
||||
return kls._parse_fields()[1]
|
||||
|
||||
@classmethod
|
||||
@cache
|
||||
def _struct_uncasts(kls):
|
||||
return kls._parse_fields()[2]
|
||||
|
||||
@classmethod
|
||||
def _parse_fields(kls):
|
||||
fmt = '<'
|
||||
casts = []
|
||||
uncasts = []
|
||||
for field in fields(kls):
|
||||
if isinstance(field.type, tuple):
|
||||
struct_type, cast, uncast, *_ = *field.type, int
|
||||
else:
|
||||
struct_type, cast, uncast = field.type, int, int
|
||||
fmt += struct_type
|
||||
casts.append(cast)
|
||||
uncasts.append(uncast)
|
||||
return fmt, casts, uncasts
|
||||
|
||||
def timestamp(value):
|
||||
return float(value) / 1e6
|
||||
|
||||
@dataclass
|
||||
class StatusPacket(Serialized):
|
||||
packet_type: ('B', PacketType)
|
||||
sys_time_us: ('Q', timestamp)
|
||||
has_lcd: ('B', bool)
|
||||
has_adc: ('B', bool)
|
||||
board_config: ('B', BoardConfig)
|
||||
bus_addr: 'B'
|
||||
last_uart_error: ('B', ErrorCode)
|
||||
last_uart_error_timestamp: ('Q', timestamp)
|
||||
last_uart_rx: ('Q', timestamp)
|
||||
last_uart_tx: ('Q', timestamp)
|
||||
last_bus_error: ('B', ErrorCode)
|
||||
last_bus_error_timestamp: ('Q', timestamp)
|
||||
|
||||
@dataclass
|
||||
class MotorPacket(Serialized):
|
||||
packet_type: ('B', PacketType)
|
||||
speed_rpm: 'i'
|
||||
|
||||
def parse_packet(data):
|
||||
packet_type = PacketType(data[0])
|
||||
if packet_type == PacketType.USBP_GET_STATUS:
|
||||
return StatusPacket.deserialize(data)
|
||||
if packet_type == PacketType.USBP_GET_MEASUREMENTS:
|
||||
return MeasurementPacket.deserialize(data)
|
||||
else:
|
||||
raise ValueError(f'Unsupported packet type {packet_type}')
|
||||
|
||||
@dataclass
|
||||
class MeasurementPacket(Serialized):
|
||||
packet_type: ('B', PacketType)
|
||||
num_channels: 'B'
|
||||
_num_samples_a: 'I'
|
||||
_num_samples_b: 'I'
|
||||
_measurements_raw: ('240s', bytes)
|
||||
|
||||
@property
|
||||
def measurements(self):
|
||||
return np.frombuffer(self._measurements_raw, np.dtype(np.int32).newbyteorder('<')).reshape([2, 2, -1])
|
||||
|
||||
@property
|
||||
def num_samples(self):
|
||||
return [self._num_samples_a, self._num_samples_b]
|
||||
|
||||
@click.group()
|
||||
def cli():
|
||||
pass
|
||||
|
||||
@cli.command()
|
||||
@click.argument('port')
|
||||
@click.option('--timeout', type=float, default=1)
|
||||
def probe(port, timeout):
|
||||
ser = CobsSerial(port, timeout)
|
||||
pprint(ser.command(PacketType.USBP_GET_STATUS))
|
||||
while True:
|
||||
time.sleep(0.01)
|
||||
packet = ser.command(PacketType.USBP_GET_MEASUREMENTS)
|
||||
for i in range(packet.num_samples[1]):
|
||||
print(packet.measurements[1,1,i], packet.num_samples[1])
|
||||
|
||||
@cli.command()
|
||||
@click.argument('port')
|
||||
@click.argument('speed_rpm', type=int, default=0)
|
||||
@click.option('--timeout', type=float, default=1)
|
||||
def motor(port, speed_rpm, timeout):
|
||||
ser = CobsSerial(port, timeout)
|
||||
packet = MotorPacket(PacketType.USBP_SET_MOTOR, speed_rpm)
|
||||
ser.write_packet(packet.serialize())
|
||||
|
||||
if __name__ == '__main__':
|
||||
cli()
|
||||
Loading…
Add table
Add a link
Reference in a new issue