change F303's Makefile to version control; fixed bugs in F303 usb ringbuffer, add two buffers like in F0x2

This commit is contained in:
Edward Emelianov 2023-01-18 21:03:56 +03:00
parent 5230ad14e3
commit 7f9057b65c
22 changed files with 544 additions and 174 deletions

View File

@ -9,12 +9,8 @@ MCU ?= F303xb
ARMARCH = __ARM_ARCH_7M__ ARMARCH = __ARM_ARCH_7M__
# change this linking script depending on particular MCU model, # change this linking script depending on particular MCU model,
LDSCRIPT ?= stm32f303xB.ld LDSCRIPT ?= stm32f303xB.ld
# debug
#DEFS = -DEBUG
INDEPENDENT_HEADERS= FP_FLAGS ?= -mfpu=fpv4-sp-d16 -mfloat-abi=hard -fsingle-precision-constant -mlittle-endian -DARM_MATH_CM4
FP_FLAGS ?= -mfpu=fpv4-sp-d16 -mfloat-abi=softfp -fsingle-precision-constant -mlittle-endian -DARM_MATH_CM4
ASM_FLAGS ?= -mthumb -mcpu=cortex-m4 ASM_FLAGS ?= -mthumb -mcpu=cortex-m4
ARCH_FLAGS = $(ASM_FLAGS) $(FP_FLAGS) -D $(ARMARCH) ARCH_FLAGS = $(ASM_FLAGS) $(FP_FLAGS) -D $(ARMARCH)
@ -42,6 +38,10 @@ DFUUTIL := $(shell which dfu-util)
############################################################################### ###############################################################################
# Source files # Source files
OBJDIR := mk OBJDIR := mk
# target (debug/release)
TARGFILE := $(OBJDIR)/TARGET
# autoincremental version & build date
VERSION_FILE = version.inc
SRC := $(wildcard *.c) SRC := $(wildcard *.c)
OBJS := $(addprefix $(OBJDIR)/, $(SRC:%.c=%.o)) OBJS := $(addprefix $(OBJDIR)/, $(SRC:%.c=%.o))
STARTUP := $(OBJDIR)/startup.o STARTUP := $(OBJDIR)/startup.o
@ -59,16 +59,15 @@ LIB_DIR := $(INC_DIR)/ld
# C flags # C flags
CFLAGS += -g -gdwarf-2 # debuggin symbols in listing CFLAGS += -g -gdwarf-2 # debuggin symbols in listing
CFLAGS += -O2 -D__thumb2__=1 -MD CFLAGS += -O2 -D__thumb2__=1 -MD
CFLAGS += -Wall -Werror -Wextra -Wshadow CFLAGS += -Wall -Wextra -Wshadow
CFLAGS += -fshort-enums -ffunction-sections -fdata-sections CFLAGS += -fshort-enums -ffunction-sections -fdata-sections
#CFLAGS += -fno-common -ffunction-sections -fdata-sections -fno-stack-protector #CFLAGS += -fno-common -fno-stack-protector
CFLAGS += $(ARCH_FLAGS) CFLAGS += $(ARCH_FLAGS)
############################################################################### ###############################################################################
# Linker flags # Linker flags
#LDFLAGS += -nostartfiles --static -nostdlib -specs=nosys.specs -specs=nano.specs LDFLAGS += -nostartfiles --static -specs=nosys.specs -specs=nano.specs
LDFLAGS += $(ARCH_FLAGS) LDFLAGS += $(ARCH_FLAGS)
LDFLAGS += -specs=nano.specs -specs=nosys.specs
LDFLAGS += -L$(LIB_DIR) LDFLAGS += -L$(LIB_DIR)
#-L$(TOOLCHLIB) #-L$(TOOLCHLIB)
LDFLAGS += -T$(LDSCRIPT) LDFLAGS += -T$(LDSCRIPT)
@ -76,7 +75,7 @@ LDFLAGS += -Wl,-Map=$(MAP),--cref -Wl,--gc-sections -Wl,--print-memory-usage
############################################################################### ###############################################################################
# Used libraries # Used libraries
#LDLIBS += -lc $(shell $(CC) $(CFLAGS) -print-libgcc-file-name) LDLIBS += -lm -lc $(shell $(CC) $(CFLAGS) -print-libgcc-file-name)
DEFS += -DSTM32$(FAMILY) -DSTM32$(MCU) DEFS += -DSTM32$(FAMILY) -DSTM32$(MCU)
@ -85,7 +84,36 @@ LIST := $(OBJDIR)/$(BINARY).list
BIN := $(BINARY).bin BIN := $(BINARY).bin
HEX := $(BINARY).hex HEX := $(BINARY).hex
all: bin list size ifeq ($(shell test -e $(TARGFILE) && echo -n yes),yes)
TARGET := $(file < $(TARGFILE))
else
TARGET := RELEASE
endif
ifeq ($(TARGET), DEBUG)
.DEFAULT_GOAL := debug
endif
ifeq ($(shell test -e $(VERSION_FILE) && echo -n yes), yes)
NEXTVER := $(shell expr $$(awk '/#define BUILD_NUMBER/' $(VERSION_FILE) | tr -cd "[0-9]") + 1)
else
NEXTVER := "1"
endif
BUILDDATE := $(shell date +%Y-%m-%d)
# release: add LTO
release: CFLAGS += -flto
release: LDFLAGS += -flto
release: $(TARGFILE) bin list size
#debug: add debug flags
debug: CFLAGS += -DEBUG -Werror -g3
debug: TARGET := DEBUG
debug: $(TARGFILE) bin list size
$(TARGFILE): $(OBJDIR)
@echo -e "\t\tTARGET: $(TARGET)"
@echo "$(TARGET)" > $(TARGFILE)
elf: $(ELF) elf: $(ELF)
bin: $(BIN) bin: $(BIN)
@ -102,6 +130,14 @@ $(OBJDIR):
$(STARTUP): $(INC_DIR)/startup/vector.c $(STARTUP): $(INC_DIR)/startup/vector.c
$(CC) $(CFLAGS) $(DEFS) $(INCLUDE) -o $@ -c $< $(CC) $(CFLAGS) $(DEFS) $(INCLUDE) -o $@ -c $<
$(VERSION_FILE): *.[ch]
@[ -f $(VERSION_FILE) ] || echo -e "#define BUILD_NUMBER \"0\"\n#define BUILD_DATE \"none\"" > $(VERSION_FILE)
@echo " Generate version: $(NEXTVER) for date $(BUILDDATE)"
@sed -i "s/#define BUILD_NUMBER.*/#define BUILD_NUMBER \"$(NEXTVER)\"/" $(VERSION_FILE)
@sed -i "s/#define BUILD_DATE.*/#define BUILD_DATE \"$(BUILDDATE)\"/" $(VERSION_FILE)
$(OBJDIR)/proto.o: proto.c $(VERSION_FILE)
$(OBJDIR)/%.o: %.c $(OBJDIR)/%.o: %.c
@echo " CC $<" @echo " CC $<"
$(CC) $(CFLAGS) $(DEFS) $(INCLUDE) -o $@ -c $< $(CC) $(CFLAGS) $(DEFS) $(INCLUDE) -o $@ -c $<
@ -127,8 +163,7 @@ size: $(ELF)
clean: clean:
@echo " CLEAN" @echo " CLEAN"
$(RM) $(OBJS) $(DEPS) $(ELF) $(HEX) $(LIST) $(MAP) @rm -rf $(OBJDIR) 2>/dev/null || true
@rmdir $(OBJDIR) 2>/dev/null || true
flash: $(BIN) flash: $(BIN)
@ -143,4 +178,10 @@ dfuboot: $(BIN)
@echo " LOAD $(BIN) THROUGH DFU" @echo " LOAD $(BIN) THROUGH DFU"
$(DFUUTIL) -a0 -D $(BIN) -s 0x08000000 $(DFUUTIL) -a0 -D $(BIN) -s 0x08000000
.PHONY: clean flash boot openocd:
openocd -f openocd.cfg
dbg:
arm-none-eabi-gdb $(ELF) -ex 'target remote localhost:3333' -ex 'monitor reset halt'
.PHONY: size clean flash boot dfuboot openocd dbg

View File

@ -21,7 +21,7 @@
#include "usart.h" #include "usart.h"
#include "usb.h" #include "usb.h"
#define USBBUFSZ 127 #define MAXSTRLEN RBINSZ
const char *test = "123456789A123456789B123456789C123456789D123456789E123456789F123456789G123456789H123456789I123456789J123456789K123456789L123456789M123456789N123456789O123456789P123456789Q123456789R123456789S123456789T123456789U123456789V123456789W123456789X123456789Y\n" const char *test = "123456789A123456789B123456789C123456789D123456789E123456789F123456789G123456789H123456789I123456789J123456789K123456789L123456789M123456789N123456789O123456789P123456789Q123456789R123456789S123456789T123456789U123456789V123456789W123456789X123456789Y\n"
"123456789A123456789B123456789C123456789D123456789E123456789F123456789G123456789H123456789I123456789J123456789K123456789L123456789M123456789N123456789O123456789P123456789Q123456789R123456789S123456789T123456789U123456789V123456789W123456789X123456789Y\n"; "123456789A123456789B123456789C123456789D123456789E123456789F123456789G123456789H123456789I123456789J123456789K123456789L123456789M123456789N123456789O123456789P123456789Q123456789R123456789S123456789T123456789U123456789V123456789W123456789X123456789Y\n";
@ -32,28 +32,8 @@ void sys_tick_handler(void){
++Tms; ++Tms;
} }
// usb getline
char *get_USB(){
static char tmpbuf[USBBUFSZ+1], *curptr = tmpbuf;
static int rest = USBBUFSZ;
uint8_t x = USB_receive(curptr);
if(!x) return NULL;
curptr[x] = 0;
if(curptr[x-1] == '\n'){
curptr = tmpbuf;
rest = USBBUFSZ;
return tmpbuf;
}
curptr += x; rest -= x;
if(rest <= 0){ // buffer overflow
curptr = tmpbuf;
rest = USBBUFSZ;
USB_send("USB buffer overflow\n");
}
return NULL;
}
int main(void){ int main(void){
char inbuff[MAXSTRLEN+1];
int hse = 0; int hse = 0;
if(StartHSE()){ if(StartHSE()){
hse = 1; hse = 1;
@ -85,20 +65,24 @@ int main(void){
const char *ans = parse_cmd(txt); const char *ans = parse_cmd(txt);
if(ans) usart_send(ans); if(ans) usart_send(ans);
} }
usb_proc(); USB_proc();
if((txt = get_USB())){ int l = USB_receivestr(inbuff, MAXSTRLEN);
usart_send("Get by USB: "); if(l < 0) USB_sendstr("ERROR: USB buffer overflow or string was too long\n");
usart_send(txt); usart_putchar('\n'); else if(l){
const char *ans = parse_cmd(txt); usart_send("Get by USB ");
if(ans) USB_send(ans); usart_send(u2str(l)); usart_send(" bytes:");
} usart_send(inbuff); usart_putchar('\n');
if(Tlast){ const char *ans = parse_cmd(inbuff);
usart_send("Tlast="); usart_send(u2str(Tlast)); usart_putchar('\n'); if(ans) USB_sendstr(ans);
Tlast = 0;
} }
if(starttest){ if(starttest){
--starttest; USB_sendstr(test);
USB_send(test); if(0 == --starttest){
#define SENDBOTH(x) do{char *_ = x; usart_send(_); USB_sendstr(_);}while(0)
SENDBOTH("ENDT=");
SENDBOTH(u2str(Tms));
usart_putchar('\n'); USB_putbyte('\n');
}
} }
} }
} }

Binary file not shown.

View File

@ -0,0 +1 @@
-std=c17

View File

@ -0,0 +1,7 @@
// Add predefined macros for your project here. For example:
// #define THE_ANSWER 42
#define EBUG
#define STM32F3
#define STM32F303xb
#define __thumb2__ 1
#define __ARM_ARCH_7M__

View File

@ -0,0 +1 @@
[General]

View File

@ -0,0 +1,171 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 8.0.2, 2023-01-18T20:42:42. -->
<qtcreator>
<data>
<variable>EnvironmentId</variable>
<value type="QByteArray">{7bd84e39-ca37-46d3-be9d-99ebea85bc0d}</value>
</data>
<data>
<variable>ProjectExplorer.Project.ActiveTarget</variable>
<value type="int">0</value>
</data>
<data>
<variable>ProjectExplorer.Project.EditorSettings</variable>
<valuemap type="QVariantMap">
<value type="bool" key="EditorConfiguration.AutoIndent">true</value>
<value type="bool" key="EditorConfiguration.AutoSpacesForTabs">false</value>
<value type="bool" key="EditorConfiguration.CamelCaseNavigation">true</value>
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0">
<value type="QString" key="language">Cpp</value>
<valuemap type="QVariantMap" key="value">
<value type="QByteArray" key="CurrentPreferences">CppGlobal</value>
</valuemap>
</valuemap>
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.1">
<value type="QString" key="language">QmlJS</value>
<valuemap type="QVariantMap" key="value">
<value type="QByteArray" key="CurrentPreferences">QmlJSGlobal</value>
</valuemap>
</valuemap>
<value type="int" key="EditorConfiguration.CodeStyle.Count">2</value>
<value type="QByteArray" key="EditorConfiguration.Codec">KOI8-R</value>
<value type="bool" key="EditorConfiguration.ConstrainTooltips">false</value>
<value type="int" key="EditorConfiguration.IndentSize">4</value>
<value type="bool" key="EditorConfiguration.KeyboardTooltips">false</value>
<value type="int" key="EditorConfiguration.MarginColumn">80</value>
<value type="bool" key="EditorConfiguration.MouseHiding">true</value>
<value type="bool" key="EditorConfiguration.MouseNavigation">true</value>
<value type="int" key="EditorConfiguration.PaddingMode">1</value>
<value type="bool" key="EditorConfiguration.PreferSingleLineComments">false</value>
<value type="bool" key="EditorConfiguration.ScrollWheelZooming">true</value>
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</value>
<value type="bool" key="EditorConfiguration.SmartSelectionChanging">true</value>
<value type="bool" key="EditorConfiguration.SpacesForTabs">true</value>
<value type="int" key="EditorConfiguration.TabKeyBehavior">0</value>
<value type="int" key="EditorConfiguration.TabSize">8</value>
<value type="bool" key="EditorConfiguration.UseGlobal">true</value>
<value type="bool" key="EditorConfiguration.UseIndenter">false</value>
<value type="int" key="EditorConfiguration.Utf8BomBehavior">1</value>
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
<value type="bool" key="EditorConfiguration.cleanIndentation">false</value>
<value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
<value type="QString" key="EditorConfiguration.ignoreFileTypes">*.md, *.MD, Makefile</value>
<value type="bool" key="EditorConfiguration.inEntireDocument">false</value>
<value type="bool" key="EditorConfiguration.skipTrailingWhitespace">true</value>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.PluginSettings</variable>
<valuemap type="QVariantMap">
<valuemap type="QVariantMap" key="AutoTest.ActiveFrameworks">
<value type="bool" key="AutoTest.Framework.Boost">true</value>
<value type="bool" key="AutoTest.Framework.CTest">false</value>
<value type="bool" key="AutoTest.Framework.Catch">true</value>
<value type="bool" key="AutoTest.Framework.GTest">true</value>
<value type="bool" key="AutoTest.Framework.QtQuickTest">true</value>
<value type="bool" key="AutoTest.Framework.QtTest">true</value>
</valuemap>
<valuemap type="QVariantMap" key="AutoTest.CheckStates"/>
<value type="int" key="AutoTest.RunAfterBuild">0</value>
<value type="bool" key="AutoTest.UseGlobal">true</value>
<valuemap type="QVariantMap" key="ClangTools">
<value type="bool" key="ClangTools.AnalyzeOpenFiles">true</value>
<value type="bool" key="ClangTools.BuildBeforeAnalysis">true</value>
<value type="QString" key="ClangTools.DiagnosticConfig">Builtin.DefaultTidyAndClazy</value>
<value type="int" key="ClangTools.ParallelJobs">2</value>
<valuelist type="QVariantList" key="ClangTools.SelectedDirs"/>
<valuelist type="QVariantList" key="ClangTools.SelectedFiles"/>
<valuelist type="QVariantList" key="ClangTools.SuppressedDiagnostics"/>
<value type="bool" key="ClangTools.UseGlobalSettings">true</value>
</valuemap>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.Target.0</variable>
<valuemap type="QVariantMap">
<value type="QString" key="DeviceType">Desktop</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Desktop</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Desktop</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">{65a14f9e-e008-4c1b-89df-4eaa4774b6e3}</value>
<value type="int" key="ProjectExplorer.Target.ActiveBuildConfiguration">0</value>
<value type="int" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value>
<value type="int" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.0">
<value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">/Big/Data/00__Electronics/STM32/F303-nolib/blink</value>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<valuelist type="QVariantList" key="GenericProjectManager.GenericMakeStep.BuildTargets">
<value type="QString">all</value>
</valuelist>
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericMakeStep</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Сборка</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Сборка</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<valuelist type="QVariantList" key="GenericProjectManager.GenericMakeStep.BuildTargets">
<value type="QString">clean</value>
</valuelist>
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericMakeStep</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Очистка</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Очистка</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value>
<value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.CustomParsers"/>
<value type="bool" key="ProjectExplorer.BuildConfiguration.ParseStandardOutput">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Default</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericBuildConfiguration</value>
</valuemap>
<value type="int" key="ProjectExplorer.Target.BuildConfigurationCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">0</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Развёртывание</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Развёртывание</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Deploy</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.DeployConfiguration.CustomData"/>
<value type="bool" key="ProjectExplorer.DeployConfiguration.CustomDataEnabled">false</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.DefaultDeployConfiguration</value>
</valuemap>
<value type="int" key="ProjectExplorer.Target.DeployConfigurationCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.RunConfiguration.0">
<valuelist type="QVariantList" key="CustomOutputParsers"/>
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value>
<value type="QString" key="ProjectExplorer.RunConfiguration.BuildKey"></value>
<value type="bool" key="RunConfiguration.UseCppDebugger">false</value>
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
<value type="bool" key="RunConfiguration.UseQmlDebugger">false</value>
<value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value>
</valuemap>
<value type="int" key="ProjectExplorer.Target.RunConfigurationCount">1</value>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.TargetCount</variable>
<value type="int">1</value>
</data>
<data>
<variable>ProjectExplorer.Project.Updater.FileVersion</variable>
<value type="int">22</value>
</data>
<data>
<variable>Version</variable>
<value type="int">22</value>
</data>
</qtcreator>

View File

@ -0,0 +1 @@
-std=c++17

View File

@ -0,0 +1,15 @@
hardware.c
hardware.h
main.c
proto.c
proto.h
ringbuffer.c
ringbuffer.h
usart.c
usart.h
usb.c
usb.h
usb_lib.c
usb_lib.h
usbhw.c
usbhw.h

View File

@ -0,0 +1,6 @@
.
../inc
../inc/Fx
../inc/cm
../inc/ld
../inc/startup

View File

@ -19,6 +19,7 @@
#include "proto.h" #include "proto.h"
#include "usart.h" #include "usart.h"
#include "usb.h" #include "usb.h"
#include "version.inc"
uint8_t starttest = 50; uint8_t starttest = 50;
@ -153,6 +154,7 @@ char *getnum(const char *txt, uint32_t *N){
} }
const char* helpmsg = const char* helpmsg =
"https://github.com/eddyem/stm32samples/tree/master/F3:F303/PL2303 build#" BUILD_NUMBER " @ " BUILD_DATE "\n"
"'i' - print USB->ISTR state\n" "'i' - print USB->ISTR state\n"
"'p' - toggle USB pullup\n" "'p' - toggle USB pullup\n"
"'N' - read number (dec, 0xhex, 0oct, bbin) and show it in decimal\n" "'N' - read number (dec, 0xhex, 0oct, bbin) and show it in decimal\n"
@ -192,7 +194,7 @@ const char *parse_cmd(const char *buf){
else add2buf("on\n"); else add2buf("on\n");
break; break;
case 'R': case 'R':
USB_send("Soft reset\n"); USB_sendstr("Soft reset\n");
usart_send("Soft reset\n"); usart_send("Soft reset\n");
NVIC_SystemReset(); NVIC_SystemReset();
break; break;
@ -208,7 +210,7 @@ const char *parse_cmd(const char *buf){
add2buf("\n"); add2buf("\n");
break; break;
case 'W': case 'W':
USB_send("Wait for reboot\n"); USB_sendstr("Wait for reboot\n");
usart_send("Wait for reboot\n"); usart_send("Wait for reboot\n");
while(1){nop();}; while(1){nop();};
break; break;

View File

@ -16,71 +16,109 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <string.h>
#include <stm32f3.h>
#include "ringbuffer.h" #include "ringbuffer.h"
#include "usb.h"
#include "usb_lib.h"
// ring buffer // stored data length
static char ringbuffer[RBSIZE]; int RB_datalen(ringbuffer *b){
// head - position of first data byte if(b->tail >= b->head) return (b->tail - b->head);
// tail - position of last data byte + 1 else return (b->length - b->head + b->tail);
// head == tail - empty! So, buffer can't store more than RBSIZE-1 bytes of data!
static volatile int head = 0, tail = 0;
static int datalen(){
if(tail >= head) return (tail - head);
else return (RBSIZE - head + tail);
}
static int restlen(){
return (RBSIZE - 1 - datalen());
} }
TRUE_INLINE void incr(volatile int *what, int n){ /**
* @brief RB_hasbyte - check if buffer has given byte stored
* @param b - buffer
* @param byte - byte to find
* @return index if found, -1 if none
*/
int RB_hasbyte(ringbuffer *b, uint8_t byte){
if(b->head == b->tail) return -1; // no data in buffer
int startidx = b->head;
if(b->head > b->tail){ //
for(int found = b->head; found < b->length; ++found)
if(b->data[found] == byte) return found;
startidx = 0;
}
for(int found = startidx; found < b->tail; ++found)
if(b->data[found] == byte) return found;
return -1;
}
// poor memcpy
static void mcpy(uint8_t *targ, const uint8_t *src, int l){
while(l--) *targ++ = *src++;
}
// increment head or tail
TRUE_INLINE void incr(ringbuffer *b, volatile int *what, int n){
*what += n; *what += n;
if(*what >= RBSIZE) *what -= RBSIZE; if(*what >= b->length) *what -= b->length;
} }
int RB_read(char s[BLOCKSIZE]){ /**
int l = datalen(); * @brief RB_read - read data from ringbuffer
* @param b - buffer
* @param s - array to write data
* @param len - max len of `s`
* @return bytes read
*/
int RB_read(ringbuffer *b, uint8_t *s, int len){
int l = RB_datalen(b);
if(!l) return 0; if(!l) return 0;
if(l > BLOCKSIZE) l = BLOCKSIZE; if(l > len) l = len;
int _1st = RBSIZE - head; int _1st = b->length - b->head;
if(_1st > l) _1st = l; if(_1st > l) _1st = l;
if(_1st > BLOCKSIZE) _1st = BLOCKSIZE; if(_1st > len) _1st = len;
memcpy(s, ringbuffer+head, _1st); mcpy(s, b->data + b->head, _1st);
if(_1st < BLOCKSIZE && l > _1st){ if(_1st < len && l > _1st){
memcpy(s+_1st, ringbuffer, l-_1st); mcpy(s+_1st, b->data, l - _1st);
incr(&head, l); incr(b, &b->head, l);
return l; return l;
} }
incr(&head ,_1st); incr(b, &b->head, _1st);
return _1st; return _1st;
} }
static int addportion(const char *str, int l){ /**
int r = restlen(); * @brief RB_readto fill array `s` with data until byte `byte` (with it)
* @param b - ringbuffer
* @param byte - check byte
* @param s - buffer to write data
* @param len - length of `s`
* @return amount of bytes written (negative, if len<data in buffer)
*/
int RB_readto(ringbuffer *b, uint8_t byte, uint8_t *s, int len){
int idx = RB_hasbyte(b, byte);
if(idx < 0) return 0;
int partlen = idx + 1 - b->head;
// now calculate length of new data portion
if(idx < b->head) partlen += b->length;
if(partlen > len) return -RB_read(b, s, len);
return RB_read(b, s, partlen);
}
/**
* @brief RB_write - write some data to ringbuffer
* @param b - buffer
* @param str - data
* @param l - length
* @return amount of bytes written
*/
int RB_write(ringbuffer *b, const uint8_t *str, int l){
int r = b->length - 1 - RB_datalen(b); // rest length
if(l > r) l = r; if(l > r) l = r;
if(!l) return 0; if(!l) return 0;
int _1st = RBSIZE - tail; int _1st = b->length - b->tail;
if(_1st > l) _1st = l; if(_1st > l) _1st = l;
memcpy(ringbuffer+tail, str, _1st); mcpy(b->data + b->tail, str, _1st);
if(_1st < l){ // add another piece from start if(_1st < l){ // add another piece from start
memcpy(ringbuffer, str+_1st, l-_1st); mcpy(b->data, str+_1st, l-_1st);
} }
incr(&tail, l); incr(b, &b->tail, l);
return l; return l;
} }
void RB_write(const char *str, int l){ // just delete all information in buffer `b`
if(!str || !*str) return; void RB_clearbuf(ringbuffer *b){
if(!usbON) return; b->head = 0;
while(l){ b->tail = 0;
send_next();
int a = addportion(str, l);
l -= a;
str += a;
}
} }

View File

@ -20,14 +20,20 @@
#ifndef RINGBUFFER_H__ #ifndef RINGBUFFER_H__
#define RINGBUFFER_H__ #define RINGBUFFER_H__
#include "usbhw.h" #include <stm32f3.h>
// ring buffer size in bytes typedef struct{
#define RBSIZE (512) uint8_t *data; // data buffer
// max reading portion size const int length; // its length
#define BLOCKSIZE (USB_TXBUFSZ) int head; // head index
int tail; // tail index
} ringbuffer;
int RB_read(char s[BLOCKSIZE]); int RB_read(ringbuffer *b, uint8_t *s, int len);
void RB_write(const char *str, int l); int RB_readto(ringbuffer *b, uint8_t byte, uint8_t *s, int len);
int RB_hasbyte(ringbuffer *b, uint8_t byte);
int RB_write(ringbuffer *b, const uint8_t *str, int l);
int RB_datalen(ringbuffer *b);
void RB_clearbuf(ringbuffer *b);
#endif // RINGBUFFER_H__ #endif // RINGBUFFER_H__

View File

@ -23,32 +23,105 @@
#include "usb.h" #include "usb.h"
#include "usb_lib.h" #include "usb_lib.h"
static char usbbuff[USB_TXBUFSZ]; // temporary buffer for sending data static uint8_t usbbuff[USB_TXBUFSZ]; // temporary buffer for sending data
static volatile uint8_t tx_succesfull = 1; // ring buffers for incoming and outgoing data
static volatile uint8_t rxNE = 0; static uint8_t obuf[RBOUTSZ], ibuf[RBINSZ];
static ringbuffer out = {.data = obuf, .length = RBOUTSZ, .head = 0, .tail = 0};
static ringbuffer in = {.data = ibuf, .length = RBINSZ, .head = 0, .tail = 0};
// transmission is succesfull
static volatile uint8_t bufisempty = 1;
static volatile uint8_t bufovrfl = 0;
volatile uint32_t Tlast = 0; static void send_next(){
if(bufisempty) return;
void send_next(){
static int lastdsz = 0; static int lastdsz = 0;
if(!tx_succesfull) return; int buflen = RB_read(&out, usbbuff, USB_TXBUFSZ);
int buflen = RB_read(usbbuff);
if(!buflen){ if(!buflen){
if(lastdsz) Tlast = Tms;
if(lastdsz == 64) EP_Write(3, NULL, 0); // send ZLP after 64 bits packet when nothing more to send if(lastdsz == 64) EP_Write(3, NULL, 0); // send ZLP after 64 bits packet when nothing more to send
lastdsz = 0; lastdsz = 0;
bufisempty = 1;
return; return;
} }
tx_succesfull = 0; EP_Write(3, usbbuff, buflen);
EP_Write(3, (uint8_t*)usbbuff, buflen);
lastdsz = buflen; lastdsz = buflen;
} }
// blocking send full content of ring buffer
int USB_sendall(){
while(!bufisempty){
if(!usbON) return 0;
}
return 1;
}
// put `buf` into queue to send // put `buf` into queue to send
void USB_send(const char *buf){ int USB_send(const uint8_t *buf, int len){
int len = strlen(buf); if(!buf || !usbON || !len) return 0;
if(!usbON || !len) return; while(len){
RB_write(buf, len); // this is a blocking procedure if there's too little free memory in buffer int a = RB_write(&out, buf, len);
len -= a;
buf += a;
if(bufisempty){
bufisempty = 0;
send_next();
}
}
return 1;
}
int USB_putbyte(uint8_t byte){
if(!usbON) return 0;
while(0 == RB_write(&out, &byte, 1)){
if(bufisempty){
bufisempty = 0;
send_next();
}
}
return 1;
}
int USB_sendstr(const char *string){
if(!string || !usbON) return 0;
int len = 0;
const char *b = string;
while(*b++) ++len;
if(!len) return 0;
return USB_send((const uint8_t*)string, len);
}
/**
* @brief USB_receive - get binary data from receiving ring-buffer
* @param buf (i) - buffer for received data
* @param len - length of `buf`
* @return amount of received bytes (negative, if overfull happened)
*/
int USB_receive(uint8_t *buf, int len){
int sz = RB_read(&in, buf, len);
if(bufovrfl){
RB_clearbuf(&in);
if(!sz) sz = -1;
else sz = -sz;
bufovrfl = 0;
}
return sz;
}
/**
* @brief USB_receivestr - get string up to '\n' and replace '\n' with 0
* @param buf - receiving buffer
* @param len - its length
* @return strlen or negative value indicating overflow (if so, string won't be ends with 0 and buffer should be cleared)
*/
int USB_receivestr(char *buf, int len){
int l = RB_readto(&in, '\n', (uint8_t*)buf, len);
if(l < 0 || bufovrfl) RB_clearbuf(&in);
else buf[l] = 0; // replace '\n' with strend
if(bufovrfl){
if(l > 0) l = -l;
else l = -1;
bufovrfl = 0;
}
return l;
} }
// interrupt IN handler (never used?) // interrupt IN handler (never used?)
@ -63,7 +136,6 @@ static void EP1_Handler(){
// data IN/OUT handlers // data IN/OUT handlers
static void transmit_Handler(){ // EP3IN static void transmit_Handler(){ // EP3IN
tx_succesfull = 1;
uint16_t epstatus = KEEP_DTOG_STAT(USB->EPnR[3]); uint16_t epstatus = KEEP_DTOG_STAT(USB->EPnR[3]);
// clear CTR keep DTOGs & STATs // clear CTR keep DTOGs & STATs
USB->EPnR[3] = (epstatus & ~(USB_EPnR_CTR_TX)); // clear TX ctr USB->EPnR[3] = (epstatus & ~(USB_EPnR_CTR_TX)); // clear TX ctr
@ -71,12 +143,17 @@ static void transmit_Handler(){ // EP3IN
} }
static void receive_Handler(){ // EP2OUT static void receive_Handler(){ // EP2OUT
rxNE = 1; uint8_t buf[USB_RXBUFSZ];
uint16_t epstatus = KEEP_DTOG_STAT(USB->EPnR[2]); uint16_t epstatus = KEEP_DTOG(USB->EPnR[2]);
USB->EPnR[2] = (epstatus & ~(USB_EPnR_CTR_RX)); // clear RX ctr uint8_t sz = EP_Read(2, (uint16_t*)buf);
if(sz){
if(RB_write(&in, buf, sz) != sz) bufovrfl = 1;
}
// keep stat_tx & set ACK rx, clear RX ctr
USB->EPnR[2] = (epstatus & ~USB_EPnR_CTR_RX) ^ USB_EPnR_STAT_RX;
} }
void usb_proc(){ void USB_proc(){
switch(USB_Dev.USB_Status){ switch(USB_Dev.USB_Status){
case USB_STATE_CONFIGURED: case USB_STATE_CONFIGURED:
// make new BULK endpoint // make new BULK endpoint
@ -94,21 +171,5 @@ void usb_proc(){
break; break;
default: // USB_STATE_CONNECTED - send next data portion default: // USB_STATE_CONNECTED - send next data portion
if(!usbON) return; if(!usbON) return;
send_next();
} }
} }
/**
* @brief USB_receive
* @param buf (i) - buffer[64] for received data
* @return amount of received bytes
*/
int USB_receive(char *buf){
if(!usbON || !rxNE) return 0;
int sz = EP_Read(2, (uint16_t*)buf);
uint16_t epstatus = KEEP_DTOG(USB->EPnR[2]);
// keep stat_tx & set ACK rx
USB->EPnR[2] = (epstatus & ~(USB_EPnR_STAT_TX)) ^ USB_EPnR_STAT_RX;
rxNE = 0;
return sz;
}

View File

@ -22,13 +22,17 @@
#include "usbhw.h" #include "usbhw.h"
#define BUFFSIZE (64) // sizes of ringbuffers for outgoing and incoming data
#define RBOUTSZ (512)
#define RBINSZ (512)
extern volatile uint32_t Tlast; void USB_proc();
int USB_sendall();
int USB_send(const uint8_t *buf, int len);
int USB_putbyte(uint8_t byte);
int USB_sendstr(const char *string);
int USB_receive(uint8_t *buf, int len);
int USB_receivestr(char *buf, int len);
void usb_proc();
void send_next();
void USB_send(const char *buf);
int USB_receive(char *buf);
#endif // __USB_H__ #endif // __USB_H__

View File

@ -0,0 +1,2 @@
#define BUILD_NUMBER "14"
#define BUILD_DATE "2023-01-18"

View File

@ -10,8 +10,6 @@ ARMARCH = __ARM_ARCH_7M__
# change this linking script depending on particular MCU model, # change this linking script depending on particular MCU model,
LDSCRIPT ?= stm32f303xB.ld LDSCRIPT ?= stm32f303xB.ld
INDEPENDENT_HEADERS=
FP_FLAGS ?= -mfpu=fpv4-sp-d16 -mfloat-abi=hard -fsingle-precision-constant -mlittle-endian -DARM_MATH_CM4 FP_FLAGS ?= -mfpu=fpv4-sp-d16 -mfloat-abi=hard -fsingle-precision-constant -mlittle-endian -DARM_MATH_CM4
ASM_FLAGS ?= -mthumb -mcpu=cortex-m4 ASM_FLAGS ?= -mthumb -mcpu=cortex-m4
ARCH_FLAGS = $(ASM_FLAGS) $(FP_FLAGS) -D $(ARMARCH) ARCH_FLAGS = $(ASM_FLAGS) $(FP_FLAGS) -D $(ARMARCH)
@ -42,6 +40,8 @@ DFUUTIL := $(shell which dfu-util)
OBJDIR := mk OBJDIR := mk
# target (debug/release) # target (debug/release)
TARGFILE := $(OBJDIR)/TARGET TARGFILE := $(OBJDIR)/TARGET
# autoincremental version & build date
VERSION_FILE = version.inc
SRC := $(wildcard *.c) SRC := $(wildcard *.c)
OBJS := $(addprefix $(OBJDIR)/, $(SRC:%.c=%.o)) OBJS := $(addprefix $(OBJDIR)/, $(SRC:%.c=%.o))
STARTUP := $(OBJDIR)/startup.o STARTUP := $(OBJDIR)/startup.o
@ -94,6 +94,13 @@ ifeq ($(TARGET), DEBUG)
.DEFAULT_GOAL := debug .DEFAULT_GOAL := debug
endif endif
ifeq ($(shell test -e $(VERSION_FILE) && echo -n yes), yes)
NEXTVER := $(shell expr $$(awk '/#define BUILD_NUMBER/' $(VERSION_FILE) | tr -cd "[0-9]") + 1)
else
NEXTVER := "1"
endif
BUILDDATE := $(shell date +%Y-%m-%d)
# release: add LTO # release: add LTO
release: CFLAGS += -flto release: CFLAGS += -flto
release: LDFLAGS += -flto release: LDFLAGS += -flto
@ -123,6 +130,14 @@ $(OBJDIR):
$(STARTUP): $(INC_DIR)/startup/vector.c $(STARTUP): $(INC_DIR)/startup/vector.c
$(CC) $(CFLAGS) $(DEFS) $(INCLUDE) -o $@ -c $< $(CC) $(CFLAGS) $(DEFS) $(INCLUDE) -o $@ -c $<
$(VERSION_FILE): *.[ch]
@[ -f $(VERSION_FILE) ] || echo -e "#define BUILD_NUMBER \"0\"\n#define BUILD_DATE \"none\"" > $(VERSION_FILE)
@echo " Generate version: $(NEXTVER) for date $(BUILDDATE)"
@sed -i "s/#define BUILD_NUMBER.*/#define BUILD_NUMBER \"$(NEXTVER)\"/" $(VERSION_FILE)
@sed -i "s/#define BUILD_DATE.*/#define BUILD_DATE \"$(BUILDDATE)\"/" $(VERSION_FILE)
#$(OBJDIR)/proto.o: proto.c $(VERSION_FILE)
$(OBJDIR)/%.o: %.c $(OBJDIR)/%.o: %.c
@echo " CC $<" @echo " CC $<"
$(CC) $(CFLAGS) $(DEFS) $(INCLUDE) -o $@ -c $< $(CC) $(CFLAGS) $(DEFS) $(INCLUDE) -o $@ -c $<

Binary file not shown.

View File

@ -101,7 +101,7 @@ NAN, INFINITY, -INFINITY};
#define TESTN 12 #define TESTN 12
int main(void){ int main(void){
sysreset(); // sysreset();
if(!StartHSE()) StartHSI(); if(!StartHSE()) StartHSI();
SysTick_Config((uint32_t)72000); // 1ms SysTick_Config((uint32_t)72000); // 1ms
hw_setup(); hw_setup();

View File

@ -32,15 +32,7 @@
#define VECT_TAB_OFFSET 0x0 /*!< Vector Table base offset field. #define VECT_TAB_OFFSET 0x0 /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */ This value must be a multiple of 0x200. */
/* #if 0
TRUE_INLINE void enable_FPU(){
SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); // set CP10 and CP11 Full Access
}*/
//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 */
/** /**
* @brief Setup the microcontroller system * @brief Setup the microcontroller system
* Initialize the FPU setting, vector table location and the PLL configuration is reset. * Initialize the FPU setting, vector table location and the PLL configuration is reset.
@ -80,52 +72,57 @@ TRUE_INLINE void sysreset(void) // not usable
SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */
#endif #endif
} }
#endif
TRUE_INLINE void StartHSI(){ // system bus 48MHz from PLL, USBPPRE=1 #define WAITWHILE(x) do{StartUpCounter = 0; while((x) && (++StartUpCounter < 3600000)){nop();}}while(0)
TRUE_INLINE void StartHSI(){ // system bus 48MHz from PLL
__IO uint32_t StartUpCounter = 0; __IO uint32_t StartUpCounter = 0;
#define WAITWHILE(x) do{StartUpCounter = 0; while((x) && (++StartUpCounter < 0xffffff)){nop();}}while(0) RCC->CR |= RCC_CR_HSION;
RCC->CR = (RCC->CR & ~RCC_CR_PLLON) | RCC_CR_HSION;
// To adjust HSI set value of HSITRIM here // To adjust HSI set value of HSITRIM here
WAITWHILE(!(RCC->CR & RCC_CR_HSIRDY)); WAITWHILE(!(RCC->CR & RCC_CR_HSIRDY));
RCC->CFGR &= ~RCC_CFGR_SW; // set sysclock to HSI
WAITWHILE(RCC->CFGR & RCC_CFGR_SWS);
RCC->CR &= ~(RCC_CR_PLLON | RCC_CR_HSEON);
WAITWHILE(RCC->CR & RCC_CR_PLLRDY); // wait while PLL will be off
FLASH->ACR = (FLASH->ACR & ~(FLASH_ACR_LATENCY)) | FLASH->ACR = (FLASH->ACR & ~(FLASH_ACR_LATENCY)) |
FLASH_ACR_LATENCY_0 | FLASH_ACR_PRFTBE; FLASH_ACR_LATENCY_1 | FLASH_ACR_PRFTBE;
RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_HPRE | RCC_CFGR_PPRE1 | RCC_CFGR_PPRE2 | RCC->CFGR = RCC_CFGR_PLLSRC_HSI_DIV2 | RCC_CFGR_PLLMUL12 | RCC_CFGR_USBPRE_DIV1 | RCC_CFGR_PPRE1_DIV2;
RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMUL | RCC_CFGR_USBPRE)
) | RCC_CFGR_PLLSRC_HSI_DIV2 | RCC_CFGR_PLLMUL12 | RCC_CFGR_USBPRE_DIV1;
RCC->CR |= RCC_CR_PLLON; // Enable PLL RCC->CR |= RCC_CR_PLLON; // Enable PLL
// Wait till PLL is ready // Wait till PLL is ready
WAITWHILE(!(RCC->CR & RCC_CR_PLLRDY)); WAITWHILE(!(RCC->CR & RCC_CR_PLLRDY));
// Select PLL as system clock source // Select PLL as system clock source
RCC->CFGR = (RCC->CFGR & ~RCC_CFGR_SW) | RCC_CFGR_SW_PLL; RCC->CFGR = (RCC->CFGR & ~RCC_CFGR_SW) | RCC_CFGR_SW_PLL;
// Wait till PLL is used as system clock source // Wait till PLL is used as system clock source
WAITWHILE((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_1); WAITWHILE((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL);
#undef WAITWHILE SysFreq = 48000000;
} }
// @return 1 if OK, 0 if failed // @return 1 if OK, 0 if failed
TRUE_INLINE int StartHSE(){ // system bus 72MHz from PLL TRUE_INLINE int StartHSE(){ // system bus 72MHz from PLL
__IO uint32_t StartUpCounter = 0; __IO uint32_t StartUpCounter = 0;
#define WAITWHILE(x) do{StartUpCounter = 0; while((x) && (++StartUpCounter < 0xffffff)){nop();}; if(x) return 0;}while(0) RCC->CFGR &= ~RCC_CFGR_SW; // set sysclock to HSI
RCC->CR = (RCC->CR & ~RCC_CR_PLLON) | RCC_CR_HSEON; // disable PLL to reconfigure, enable HSE WAITWHILE(RCC->CFGR & RCC_CFGR_SWS);
RCC->CR &= ~RCC_CR_PLLON;
WAITWHILE(RCC->CR & RCC_CR_PLLRDY); // wait while PLL will be off
RCC->CR |= RCC_CR_HSEON; // disable PLL to reconfigure, enable HSE
WAITWHILE(!(RCC->CR & RCC_CR_HSERDY)); WAITWHILE(!(RCC->CR & RCC_CR_HSERDY));
// Enable Prefetch Buffer. Flash 4 wait states for 48..72MHz // Enable Prefetch Buffer. Flash 4 wait states for 48..72MHz
FLASH->ACR = (FLASH->ACR & ~(FLASH_ACR_LATENCY)) | FLASH->ACR = (FLASH->ACR & ~(FLASH_ACR_LATENCY)) |
FLASH_ACR_LATENCY_2 | FLASH_ACR_PRFTBE; FLASH_ACR_LATENCY_2 | FLASH_ACR_PRFTBE;
// HCLK = SYSCLK (AHB prescaler = 1), PCLK1 = HCLK (APB1 prescaler = 1), PCLK2 = HCLK (APB2 prescaler = 1) // HCLK = SYSCLK (AHB prescaler = 1), PCLK1 = HCLK/2 (APB1 prescaler = 2, max freq = 36MHz),
// PLLCLK = HSE * 9 = 72MHz // PCLK2 = HCLK (APB2 prescaler = 1), PLLCLK = HSE * 9 = 72MHz
RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_HPRE | RCC_CFGR_PPRE1 | RCC_CFGR_PPRE2 | RCC->CFGR = RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR_PLLMUL9 | RCC_CFGR_PPRE1_DIV2;
RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMUL | RCC_CFGR_USBPRE)
) | RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR_PLLMUL9 | RCC_CFGR_USBPRE_DIV1_5;
RCC->CR |= RCC_CR_PLLON; // Enable PLL RCC->CR |= RCC_CR_PLLON; // Enable PLL
// Wait till PLL is ready // Wait till PLL is ready
WAITWHILE(!(RCC->CR & RCC_CR_PLLRDY)); WAITWHILE(!(RCC->CR & RCC_CR_PLLRDY));
// Select PLL as system clock source // Select PLL as system clock source
RCC->CFGR = (RCC->CFGR & ~RCC_CFGR_SW) | RCC_CFGR_SW_PLL; RCC->CFGR = (RCC->CFGR & ~RCC_CFGR_SW) | RCC_CFGR_SW_PLL;
// Wait till PLL is used as system clock source // Wait till PLL is used as system clock source
WAITWHILE((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_1); WAITWHILE((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL);
#undef WAITWHILE SysFreq = 72000000;
return 1; return 1;
} }
#undef WAITWHILE
/******************* Bit definition for GPIO_MODER register *****************/ /******************* Bit definition for GPIO_MODER register *****************/
// _AI - analog inpt, _O - general output, _AF - alternate function // _AI - analog inpt, _O - general output, _AF - alternate function
@ -251,6 +248,20 @@ TRUE_INLINE int StartHSE(){ // system bus 72MHz from PLL
#define GPIO_OSPEEDR15_MED ((uint32_t)(1<<30)) #define GPIO_OSPEEDR15_MED ((uint32_t)(1<<30))
#define GPIO_OSPEEDR15_HIGH ((uint32_t)(3<<30)) #define GPIO_OSPEEDR15_HIGH ((uint32_t)(3<<30))
// clear MODER: ~GPIO_MODER_MODERXX_Msk, you should AND these
#define MODER_CLR(n) (~(3<<(n*2)))
// _AI - analog inpt, _O - general output, _AF - alternate function
// these should be OR'ed
#define MODER_I(n) (0)
#define MODER_O(n) (1<<(n*2))
#define MODER_AF(n) (2<<(n*2))
#define MODER_AI(n) (3<<(n*2))
// AFR field: afr - AFR number, pin - pin (0..15)
TRUE_INLINE uint32_t AFRf(uint8_t afr, uint8_t pin){
if(pin > 7) pin -= 8;
return (afr << (pin * 4));
}
/************************* ADC *************************/ /************************* ADC *************************/
/* inner termometer calibration values /* inner termometer calibration values

View File

@ -25,6 +25,8 @@
#ifndef WEAK #ifndef WEAK
#define WEAK __attribute__((weak)) #define WEAK __attribute__((weak))
#endif #endif
#include <stdint.h>
extern uint32_t SysFreq;
void WEAK reset_handler(void); void WEAK reset_handler(void);
void WEAK nmi_handler(void); void WEAK nmi_handler(void);

View File

@ -19,6 +19,8 @@
*/ */
#include "vector.h" #include "vector.h"
uint32_t SysFreq = 0;
typedef void (*vector_table_entry_t)(void); typedef void (*vector_table_entry_t)(void);
typedef void (*funcp_t) (void); typedef void (*funcp_t) (void);