Add canUART for STM32F103

This commit is contained in:
Edward Emelianov 2022-12-05 11:50:17 +03:00
parent d3ffc05128
commit cfff079dba
21 changed files with 1795 additions and 0 deletions

BIN
F1:F103/canUART/CANUART.bin Executable file

Binary file not shown.

162
F1:F103/canUART/Makefile Normal file
View File

@ -0,0 +1,162 @@
BINARY = CANUART
BOOTPORT ?= /dev/ttyUSB0
BOOTSPEED ?= 115200
# MCU FAMILY
FAMILY ?= F1
# MCU code
MCU ?= F103x6
# density (stm32f10x.h, lines 70-84)
DENSITY ?= LD
# change this linking script depending on particular MCU model,
LDSCRIPT ?= stm32f103x6.ld
# debug
DEFS = -DBLUEPILL
#DEFS += -DEBUG
# autoincremental version & build date
VERSION_FILE = version.inc
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)
INDEPENDENT_HEADERS=
FP_FLAGS ?= -msoft-float -mfloat-abi=soft
ASM_FLAGS ?= -mthumb -mcpu=cortex-m3 -mfix-cortex-m3-ldrd
ARCH_FLAGS = $(ASM_FLAGS) $(FP_FLAGS)
###############################################################################
# Executables
#PREFIX ?= arm-none-eabi
# gcc from arm web site
PREFIX ?= /opt/bin/arm-none-eabi
TOOLCHLIB ?= /opt/arm-none-eabi/lib
RM := rm -f
RMDIR := rmdir
CC := $(PREFIX)-gcc
# don't replace ld with gcc: the binary size would be much greater!!
LD := $(PREFIX)-gcc
AR := $(PREFIX)-ar
AS := $(PREFIX)-as
SIZE := $(PREFIX)-size
OBJCOPY := $(PREFIX)-objcopy
OBJDUMP := $(PREFIX)-objdump
GDB := $(PREFIX)-gdb
STFLASH := $(shell which st-flash)
STBOOT := $(shell which stm32flash)
DFUUTIL := $(shell which dfu-util)
###############################################################################
# Source files
OBJDIR := mk
SRC := $(wildcard *.c)
OBJS := $(addprefix $(OBJDIR)/, $(SRC:%.c=%.o))
STARTUP = $(OBJDIR)/startup.o
OBJS += $(STARTUP)
MAP = $(OBJDIR)/$(BINARY).map
# dependencies: we need them to recompile files if their headers-dependencies changed
DEPS := $(OBJS:.o=.d)
INC_DIR ?= ../inc
INCLUDE := -I$(INC_DIR)/Fx -I$(INC_DIR)/cm
LIB_DIR := $(INC_DIR)/ld
###############################################################################
# C flags
CFLAGS += -O2 -g -D__thumb2__=1 -MD -g -gdwarf-2
CFLAGS += -Wall -Werror -Wextra -Wshadow
CFLAGS += -fno-common -ffunction-sections -fdata-sections -fno-stack-protector -fshort-enums
CFLAGS += $(ARCH_FLAGS)
###############################################################################
# Linker flags
LDFLAGS += -nostartfiles --static -nostdlib -Wl,--gc-sections -Wl,--print-memory-usage -Wl,-Map=$(MAP)
LDFLAGS += -L$(LIB_DIR) -L$(TOOLCHLIB) -T$(LDSCRIPT)
###############################################################################
# Used libraries
LDLIBS += $(shell $(CC) $(CFLAGS) -print-libgcc-file-name) -Wl,--start-group -lc -lgcc -Wl,--end-group
DEFS += -DSTM32$(FAMILY) -DSTM32$(MCU) -DSTM32F10X_$(DENSITY)
ELF := $(OBJDIR)/$(BINARY).elf
LIST := $(OBJDIR)/$(BINARY).list
BIN := $(BINARY).bin
HEX := $(BINARY).hex
all: bin list size
elf: $(ELF)
bin: $(BIN)
hex: $(HEX)
list: $(LIST)
ifneq ($(MAKECMDGOALS),clean)
-include $(DEPS)
endif
$(OBJDIR):
mkdir $(OBJDIR)
$(STARTUP): $(INC_DIR)/startup/vector.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
@echo " CC $<"
$(CC) $(CFLAGS) $(DEFS) $(INCLUDE) -o $@ -c $<
$(BIN): $(ELF)
@echo " OBJCOPY $(BIN)"
$(OBJCOPY) -Obinary $(ELF) $(BIN)
$(HEX): $(ELF)
@echo " OBJCOPY $(HEX)"
$(OBJCOPY) -Oihex $(ELF) $(HEX)
$(LIST): $(ELF)
@echo " OBJDUMP $(LIST)"
$(OBJDUMP) -S $(ELF) > $(LIST)
$(ELF): $(OBJDIR) $(OBJS)
@echo " LD $(ELF)"
$(LD) $(LDFLAGS) $(OBJS) $(LDLIBS) -o $(ELF)
size: $(ELF)
$(SIZE) $(ELF)
clean:
@echo " CLEAN"
$(RM) $(OBJS) $(DEPS) $(ELF) $(HEX) $(LIST) $(MAP)
@rmdir $(OBJDIR) 2>/dev/null || true
flash: $(BIN)
@echo " FLASH $(BIN)"
$(STFLASH) write $(BIN) 0x8000000
boot: $(BIN)
@echo " LOAD $(BIN) through bootloader"
$(STBOOT) -b$(BOOTSPEED) $(BOOTPORT) -w $(BIN)
dfuboot: $(BIN)
@echo " LOAD $(BIN) THROUGH DFU"
$(DFUUTIL) -a0 -D $(BIN) -s 0x08000000
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

@ -0,0 +1,2 @@
CAN bus (PB8/PB9) <> UART1 (PA9/PA10)
The same thing as canusb for STM32F0x2

380
F1:F103/canUART/can.c Normal file
View File

@ -0,0 +1,380 @@
/*
* This file is part of the canuart project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "can.h"
#include "hardware.h"
#include "proto.h"
#include "usart.h"
// REMAPPED to PB8/PB9!!!
#include <string.h> // memcpy
// circular buffer for received messages
static CAN_message messages[CAN_INMESSAGE_SIZE];
static uint8_t first_free_idx = 0; // index of first empty cell
static int8_t first_nonfree_idx = -1; // index of first data cell
static uint16_t oldspeed = 100; // speed of last init
static uint32_t last_err_code = 0;
static CAN_status can_status = CAN_STOP;
static void can_process_fifo(uint8_t fifo_num);
static CAN_message loc_flood_msg;
static CAN_message *flood_msg = NULL; // == loc_flood_msg - to flood
CAN_status CAN_get_status(){
int st = can_status;
can_status = CAN_OK;
return st;
}
// push next message into buffer; return 1 if buffer overfull
static int CAN_messagebuf_push(CAN_message *msg){
//MSG("Try to push\n");
#ifdef EBUG
usart_send("push\n");
#endif
if(first_free_idx == first_nonfree_idx){
#ifdef EBUG
usart_send("INBUF OVERFULL\n");
#endif
return 1; // no free space
}
if(first_nonfree_idx < 0) first_nonfree_idx = 0; // first message in empty buffer
memcpy(&messages[first_free_idx++], msg, sizeof(CAN_message));
// need to roll?
if(first_free_idx == CAN_INMESSAGE_SIZE) first_free_idx = 0;
return 0;
}
// pop message from buffer
CAN_message *CAN_messagebuf_pop(){
if(first_nonfree_idx < 0) return NULL;
#ifdef EBUG
//MSG("read from idx "); printu(first_nonfree_idx); NL();
#endif
CAN_message *msg = &messages[first_nonfree_idx++];
if(first_nonfree_idx == CAN_INMESSAGE_SIZE) first_nonfree_idx = 0;
if(first_nonfree_idx == first_free_idx){ // buffer is empty - refresh it
first_nonfree_idx = -1;
first_free_idx = 0;
}
return msg;
}
void CAN_reinit(uint16_t speed){
CAN1->TSR |= CAN_TSR_ABRQ0 | CAN_TSR_ABRQ1 | CAN_TSR_ABRQ2;
RCC->APB1RSTR |= RCC_APB1RSTR_CAN1RST;
RCC->APB1RSTR &= ~RCC_APB1RSTR_CAN1RST;
CAN_setup(speed);
}
/*
Can filtering: FSCx=0 (CAN1->FS1R) -> 16-bit identifiers
MASK: FBMx=0 (CAN1->FM1R), two filters (n in FR1 and n+1 in FR2)
ID: CAN1->sFilterRegister[x].FRn[0..15]
MASK: CAN1->sFilterRegister[x].FRn[16..31]
FR bits: STID[10:0] RTR IDE EXID[17:15]
LIST: FBMx=1, four filters (n&n+1 in FR1, n+2&n+3 in FR2)
IDn: CAN1->sFilterRegister[x].FRn[0..15]
IDn+1: CAN1->sFilterRegister[x].FRn[16..31]
*/
/*
Can timing: main freq - APB (PLL=48MHz)
segment = 1sync + TBS1 + TBS2, sample point is between TBS1 and TBS2,
so if TBS1=4 and TBS2=3, sum=8, bit sampling freq is 48/8 = 6MHz
-> to get 100kbps we need prescaler=60
250kbps - 24
500kbps - 12
1MBps - 6
*/
// speed - in kbps
void CAN_setup(uint16_t speed){
LED_off(LED1);
if(speed == 0) speed = oldspeed;
else if(speed < 50) speed = 50;
else if(speed > 3000) speed = 3000;
oldspeed = speed;
uint32_t tmout = 16000000;
// Configure GPIO: PB8 - CAN_Rx, PB9 - CAN_Tx
/* (1) Select AF mode (10) on PB8 and PB9 */
/* (2) AF4 for CAN signals */
RCC->APB2ENR |= RCC_APB2ENR_AFIOEN | RCC_APB2ENR_IOPBEN;
AFIO->MAPR |= AFIO_MAPR_CAN_REMAP_REMAP2;
GPIOB->CRH = 0;
//pin_set(GPIOB, 1<<8);
GPIOB->CRH = (GPIOB->CRH & ~(CRH(8,0xf)|CRH(9,0xf))) |
CRH(8, CNF_FLINPUT | MODE_INPUT) | CRH(9, CNF_AFPP | MODE_NORMAL);
/* Enable the peripheral clock CAN */
RCC->APB1ENR |= RCC_APB1ENR_CAN1EN;
/* Configure CAN */
/* (1) Enter CAN init mode to write the configuration */
/* (2) Wait the init mode entering */
/* (3) Exit sleep mode */
/* (4) Normal mode, set timing to 100kb/s: TBS1 = 4, TBS2 = 3, prescaler = 60 */
/* (5) Leave init mode */
/* (6) Wait the init mode leaving */
/* (7) Enter filter init mode, (16-bit + mask, bank 0 for FIFO 0) */
/* (8) Acivate filter 0 for two IDs */
/* (9) Identifier list mode */
/* (10) Set the Id list */
/* (12) Leave filter init */
/* (13) Set error interrupts enable (& bus off) */
CAN1->MCR |= CAN_MCR_INRQ; /* (1) */
while((CAN1->MSR & CAN_MSR_INAK) != CAN_MSR_INAK) /* (2) */
if(--tmout == 0) break;
CAN1->MCR &=~ CAN_MCR_SLEEP; /* (3) */
CAN1->MCR |= CAN_MCR_ABOM; /* allow automatically bus-off */
CAN1->BTR = 2 << 20 | 3 << 16 | (4500/speed - 1); //| CAN_BTR_SILM | CAN_BTR_LBKM; /* (4) */
CAN1->MCR &= ~CAN_MCR_INRQ; /* (5) */
tmout = 16000000;
while((CAN1->MSR & CAN_MSR_INAK) == CAN_MSR_INAK) /* (6) */
if(--tmout == 0) break;
// accept ALL
CAN1->FMR = CAN_FMR_FINIT; /* (7) */
CAN1->FA1R = CAN_FA1R_FACT0 | CAN_FA1R_FACT1; /* (8) */
// set to 1 all needed bits of CAN1->FFA1R to switch given filters to FIFO1
CAN1->sFilterRegister[0].FR1 = (1<<21)|(1<<5); // all odd IDs
CAN1->FFA1R = 2; // filter 1 for FIFO1, filter 0 - for FIFO0
CAN1->sFilterRegister[1].FR1 = (1<<21); // all even IDs
CAN1->FMR &= ~CAN_FMR_FINIT; /* (12) */
CAN1->IER |= CAN_IER_ERRIE | CAN_IER_FOVIE0 | CAN_IER_FOVIE1 | CAN_IER_BOFIE; /* (13) */
/* Configure IT */
NVIC_SetPriority(USB_LP_CAN1_RX0_IRQn, 0); // RX FIFO0 IRQ
NVIC_SetPriority(CAN1_RX1_IRQn, 0); // RX FIFO1 IRQ
NVIC_SetPriority(CAN1_SCE_IRQn, 0); // RX status changed IRQ
NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
NVIC_EnableIRQ(CAN1_RX1_IRQn);
NVIC_EnableIRQ(CAN1_SCE_IRQn);
CAN1->MSR = 0; // clear SLAKI, WKUI, ERRI
can_status = CAN_READY;
}
void printCANerr(){
if(!last_err_code) last_err_code = CAN1->ESR;
if(!last_err_code){
usart_send("No errors\n");
return;
}
usart_send("Receive error counter: ");
printu((last_err_code & CAN_ESR_REC)>>24);
usart_send("\nTransmit error counter: ");
printu((last_err_code & CAN_ESR_TEC)>>16);
usart_send("\nLast error code: ");
int lec = (last_err_code & CAN_ESR_LEC) >> 4;
const char *errmsg = "No";
switch(lec){
case 1: errmsg = "Stuff"; break;
case 2: errmsg = "Form"; break;
case 3: errmsg = "Ack"; break;
case 4: errmsg = "Bit recessive"; break;
case 5: errmsg = "Bit dominant"; break;
case 6: errmsg = "CRC"; break;
case 7: errmsg = "(set by software)"; break;
}
usart_send(errmsg); usart_send(" error\n");
if(last_err_code & CAN_ESR_BOFF) usart_send("Bus off ");
if(last_err_code & CAN_ESR_EPVF) usart_send("Passive error limit ");
if(last_err_code & CAN_ESR_EWGF) usart_send("Error counter limit");
last_err_code = 0;
usart_putchar('\n');
}
void can_proc(){
#ifdef EBUG
if(last_err_code){
usart_send("Error, ESR=");
printu(last_err_code);
usart_putchar('\n');
last_err_code = 0;
}
#endif
// check for messages in FIFO0 & FIFO1
if(CAN1->RF0R & CAN_RF0R_FMP0){
can_process_fifo(0);
}
if(CAN1->RF1R & CAN_RF1R_FMP1){
can_process_fifo(1);
}
IWDG->KR = IWDG_REFRESH;
if(CAN1->ESR & (CAN_ESR_BOFF | CAN_ESR_EPVF | CAN_ESR_EWGF)){ // much errors - restart CAN BUS
usart_send("\nToo much errors, restarting CAN!\n");
printCANerr();
// request abort for all mailboxes
CAN1->TSR |= CAN_TSR_ABRQ0 | CAN_TSR_ABRQ1 | CAN_TSR_ABRQ2;
// reset CAN bus
RCC->APB1RSTR |= RCC_APB1RSTR_CAN1RST;
RCC->APB1RSTR &= ~RCC_APB1RSTR_CAN1RST;
CAN_setup(0);
}
static uint32_t lastFloodTime = 0;
if(flood_msg && (Tms - lastFloodTime) > (FLOOD_PERIOD_MS-1)){ // flood every ~5ms
lastFloodTime = Tms;
can_send(flood_msg->data, flood_msg->length, flood_msg->ID);
}
}
CAN_status can_send(uint8_t *msg, uint8_t len, uint16_t target_id){
uint8_t mailbox = 0;
// check first free mailbox
if(CAN1->TSR & (CAN_TSR_TME)){
mailbox = (CAN1->TSR & CAN_TSR_CODE) >> 24;
}else{ // no free mailboxes
#ifdef EBUG
usart_send("No free mailboxes\n");
#endif
return CAN_BUSY;
}
#ifdef EBUG
usart_send("Send data. Len="); printu(len);
usart_send(", tagid="); printuhex(target_id);
usart_send(", data=");
for(int i = 0; i < len; ++i){
usart_send(" "); printuhex(msg[i]);
}
usart_putchar('\n');
#endif
CAN_TxMailBox_TypeDef *box = &CAN1->sTxMailBox[mailbox];
uint32_t lb = 0, hb = 0;
switch(len){
case 8:
hb |= (uint32_t)msg[7] << 24;
__attribute__((fallthrough));
case 7:
hb |= (uint32_t)msg[6] << 16;
__attribute__((fallthrough));
case 6:
hb |= (uint32_t)msg[5] << 8;
__attribute__((fallthrough));
case 5:
hb |= (uint32_t)msg[4];
__attribute__((fallthrough));
case 4:
lb |= (uint32_t)msg[3] << 24;
__attribute__((fallthrough));
case 3:
lb |= (uint32_t)msg[2] << 16;
__attribute__((fallthrough));
case 2:
lb |= (uint32_t)msg[1] << 8;
__attribute__((fallthrough));
default:
lb |= (uint32_t)msg[0];
}
box->TDLR = lb;
box->TDHR = hb;
box->TDTR = len;
box->TIR = (target_id & 0x7FF) << 21 | CAN_TI0R_TXRQ;
return CAN_OK;
}
void set_flood(CAN_message *msg){
if(!msg) flood_msg = NULL;
else{
memcpy(&loc_flood_msg, msg, sizeof(CAN_message));
flood_msg = &loc_flood_msg;
}
}
static void can_process_fifo(uint8_t fifo_num){
if(fifo_num > 1) return;
LED_on(LED1); // Turn on LED1 - message received
CAN_FIFOMailBox_TypeDef *box = &CAN1->sFIFOMailBox[fifo_num];
volatile uint32_t *RFxR = (fifo_num) ? &CAN1->RF1R : &CAN1->RF0R;
#ifdef EBUG
printu(*RFxR & CAN_RF0R_FMP0); usart_send(" messages in FIFO\n");
#endif
// read all
while(*RFxR & CAN_RF0R_FMP0){ // amount of messages pending
// CAN_RDTxR: (16-31) - timestamp, (8-15) - filter match index, (0-3) - data length
/* TODO: check filter match index if more than one ID can receive */
CAN_message msg;
uint8_t *dat = msg.data;
uint8_t len = box->RDTR & 0x0f;
msg.length = len;
msg.ID = box->RIR >> 21;
//msg.filterNo = (box->RDTR >> 8) & 0xff;
//msg.fifoNum = fifo_num;
if(len){ // message can be without data
uint32_t hb = box->RDHR, lb = box->RDLR;
switch(len){
case 8:
dat[7] = hb>>24;
__attribute__((fallthrough));
case 7:
dat[6] = (hb>>16) & 0xff;
__attribute__((fallthrough));
case 6:
dat[5] = (hb>>8) & 0xff;
__attribute__((fallthrough));
case 5:
dat[4] = hb & 0xff;
__attribute__((fallthrough));
case 4:
dat[3] = lb>>24;
__attribute__((fallthrough));
case 3:
dat[2] = (lb>>16) & 0xff;
__attribute__((fallthrough));
case 2:
dat[1] = (lb>>8) & 0xff;
__attribute__((fallthrough));
case 1:
dat[0] = lb & 0xff;
}
}
if(CAN_messagebuf_push(&msg)) return; // error: buffer is full, try later
*RFxR |= CAN_RF0R_RFOM0; // release fifo for access to next message
}
//if(*RFxR & CAN_RF0R_FULL0) *RFxR &= ~CAN_RF0R_FULL0;
*RFxR = 0; // clear FOVR & FULL
}
void usb_lp_can_rx0_isr(){ // Rx FIFO0 (overrun)
if(CAN1->RF0R & CAN_RF0R_FOVR0){ // FIFO overrun
CAN1->RF0R &= ~CAN_RF0R_FOVR0;
can_status = CAN_FIFO_OVERRUN;
}
}
void can_rx1_isr(){ // Rx FIFO1 (overrun)
if(CAN1->RF1R & CAN_RF1R_FOVR1){
CAN1->RF1R &= ~CAN_RF1R_FOVR1;
can_status = CAN_FIFO_OVERRUN;
}
}
void can_sce_isr(){ // status changed
if(CAN1->MSR & CAN_MSR_ERRI){ // Error
#ifdef EBUG
last_err_code = CAN1->ESR;
#endif
CAN1->MSR &= ~CAN_MSR_ERRI;
// request abort for problem mailbox
if(CAN1->TSR & CAN_TSR_TERR0) CAN1->TSR |= CAN_TSR_ABRQ0;
if(CAN1->TSR & CAN_TSR_TERR1) CAN1->TSR |= CAN_TSR_ABRQ1;
if(CAN1->TSR & CAN_TSR_TERR2) CAN1->TSR |= CAN_TSR_ABRQ2;
can_status = CAN_ERR;
}
}

58
F1:F103/canUART/can.h Normal file
View File

@ -0,0 +1,58 @@
/*
* This file is part of the canuart project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stdint.h>
// amount of filter banks in STM32F0
#define STM32F0FBANKNO 28
// flood period in milliseconds
#define FLOOD_PERIOD_MS 5
// incoming message buffer size
#define CAN_INMESSAGE_SIZE (8)
// CAN message
typedef struct{
uint8_t data[8]; // up to 8 bytes of data
uint8_t length; // data length
uint16_t ID; // ID of receiver
} CAN_message;
typedef enum{
CAN_STOP,
CAN_READY,
CAN_BUSY,
CAN_OK,
CAN_ERR,
CAN_FIFO_OVERRUN
} CAN_status;
CAN_status CAN_get_status();
void CAN_reinit(uint16_t speed);
void CAN_setup(uint16_t speed);
CAN_status can_send(uint8_t *msg, uint8_t len, uint16_t target_id);
void can_proc();
void printCANerr();
CAN_message *CAN_messagebuf_pop();
void set_flood(CAN_message *msg);

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 BLUEPILL
#define STM32F1
#define STM32F103x6
#define STM32F10X_LD

View File

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

View File

@ -0,0 +1,160 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 8.0.2, 2022-11-29T16:57:02. -->
<qtcreator>
<data>
<variable>EnvironmentId</variable>
<value type="QByteArray">{cf63021e-ef53-49b0-b03b-2f2570cdf3b6}</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">false</value>
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">1</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">2</value>
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
<value type="bool" key="EditorConfiguration.cleanIndentation">true</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">true</value>
<value type="bool" key="EditorConfiguration.skipTrailingWhitespace">true</value>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.PluginSettings</variable>
<valuemap type="QVariantMap">
<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">4</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">{91347f2c-5221-46a7-80b1-0a054ca02f79}</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">/home/eddy/Docs/SAO/ELECTRONICS/STM32/F1-srcs/usbcan</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">По умолчанию</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,9 @@
can.c
can.h
hardware.c
hardware.h
main.c
proto.c
proto.h
usart.c
usart.h

View File

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

View File

@ -0,0 +1,55 @@
/*
* This file is part of the canuart project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hardware.h"
uint8_t ledsON = 0;
void gpio_setup(void){
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPBEN | RCC_APB2ENR_IOPCEN | RCC_APB2ENR_AFIOEN;
LED_off(LED0);
LED_off(LED1);
// Set leds (PA0/PA4) as opendrain output
GPIOA->CRL = CRL(0, CNF_ODOUTPUT|MODE_SLOW) | CRL(4, CNF_ODOUTPUT|MODE_SLOW);
#ifdef BLUEPILL
GPIOC->CRH = CRH(13, CNF_PPOUTPUT|MODE_SLOW);
#endif
}
void iwdg_setup(){
uint32_t tmout = 16000000;
/* Enable the peripheral clock RTC */
/* (1) Enable the LSI (40kHz) */
/* (2) Wait while it is not ready */
RCC->CSR |= RCC_CSR_LSION; /* (1) */
while((RCC->CSR & RCC_CSR_LSIRDY) != RCC_CSR_LSIRDY){if(--tmout == 0) break;} /* (2) */
/* Configure IWDG */
/* (1) Activate IWDG (not needed if done in option bytes) */
/* (2) Enable write access to IWDG registers */
/* (3) Set prescaler by 64 (1.6ms for each tick) */
/* (4) Set reload value to have a rollover each 2s */
/* (5) Check if flags are reset */
/* (6) Refresh counter */
IWDG->KR = IWDG_START; /* (1) */
IWDG->KR = IWDG_WRITE_ACCESS; /* (2) */
IWDG->PR = IWDG_PR_PR_1; /* (3) */
IWDG->RLR = 1250; /* (4) */
tmout = 16000000;
while(IWDG->SR){if(--tmout == 0) break;} /* (5) */
IWDG->KR = IWDG_REFRESH; /* (6) */
}

View File

@ -0,0 +1,58 @@
/*
* This file is part of the canuart project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stm32f1.h>
#define CONCAT(a,b) a ## b
#define STR_HELPER(s) #s
#define STR(s) STR_HELPER(s)
#define FORMUSART(X) CONCAT(USART, X)
#define USARTX FORMUSART(USARTNUM)
// LEDS: 0 - PA0, 1 - PA4
// LED0
#define LED0_port GPIOA
#define LED0_pin (1<<0)
// LED1
#define LED1_port GPIOA
#define LED1_pin (1<<4)
#ifdef BLUEPILL
#define LEDB_port GPIOC
#define LEDB_pin (1<<13)
#endif
#define LED_blink(x) do{if(ledsON) pin_toggle(x ## _port, x ## _pin);}while(0)
#define LED_on(x) do{if(ledsON) pin_clear(x ## _port, x ## _pin);}while(0)
#define LED_off(x) do{pin_set(x ## _port, x ## _pin);}while(0)
// CAN address - PB14(0), PB15(1), PA8(2)
#define READ_CAN_INV_ADDR() (((GPIOA->IDR & (1<<8))>>6)|((GPIOB->IDR & (3<<14))>>14))
extern volatile uint32_t Tms;
extern uint8_t ledsON;
void gpio_setup(void);
void iwdg_setup();

93
F1:F103/canUART/main.c Normal file
View File

@ -0,0 +1,93 @@
/*
* This file is part of the canuart project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "can.h"
#include "hardware.h"
#include "proto.h"
#include "usart.h"
volatile uint32_t Tms = 0;
/* Called when systick fires */
void sys_tick_handler(void){
++Tms;
}
int main(void){
uint32_t lastT = 0;
#ifdef BLUEPILL
uint32_t bplastT = 0;
#endif
CAN_message *can_mesg;
StartHSE();
SysTick_Config(72000);
gpio_setup();
usart_setup();
CAN_setup(100);
RCC->CSR |= RCC_CSR_RMVF; // remove reset flags
#ifndef EBUG
iwdg_setup();
#endif
while (1){
IWDG->KR = IWDG_REFRESH; // refresh watchdog
if(lastT && (Tms - lastT > 199)){
LED_off(LED0);
lastT = 0;
}
#ifdef BLUEPILL
if(Tms - bplastT > 499){
pin_toggle(LEDB_port, LEDB_pin);
bplastT = Tms;
}
#endif
can_proc();
CAN_status st = CAN_get_status();
if(st == CAN_FIFO_OVERRUN){
usart_send("CAN bus fifo overrun occured!\n");
}else if(st == CAN_ERR){
usart_send("Some CAN error occured\n");
}
while((can_mesg = CAN_messagebuf_pop())){
if(can_mesg && isgood(can_mesg->ID)){
LED_on(LED0);
lastT = Tms;
if(!lastT) lastT = 1;
if(ShowMsgs){ // new data in buff
IWDG->KR = IWDG_REFRESH;
uint8_t len = can_mesg->length;
printu(Tms);
usart_send(" #");
printuhex(can_mesg->ID);
for(uint8_t ctr = 0; ctr < len; ++ctr){
usart_putchar(' ');
printuhex(can_mesg->data[ctr]);
}
usart_putchar('\n');
}
}
}
char *str;
int g = usart_getline(&str);
if(g < 0) usart_send("USART buffer overflow!\n");
else if(g > 0) cmd_parser(str);
usart_transmit();
}
return 0;
}

View File

@ -0,0 +1,6 @@
# STM32F103C8 "Blue Pill"
set FLASH_SIZE 0x8000
source [find interface/stlink-v2-1.cfg]
source [find target/stm32f1x.cfg]

574
F1:F103/canUART/proto.c Normal file
View File

@ -0,0 +1,574 @@
/*
* This file is part of the canuart project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "can.h"
#include "hardware.h"
#include "proto.h"
#include "usart.h"
#include "version.inc"
extern volatile uint8_t canerror;
uint8_t ShowMsgs = 07;
uint16_t Ignore_IDs[IGN_SIZE];
uint8_t IgnSz = 0;
char *omit_spaces(const char *buf){
while(*buf){
if(*buf > ' ') break;
++buf;
}
return (char*)buf;
}
// read hexadecimal number (without 0x prefix!)
static char *gethex(const char *buf, uint32_t *N){
char *start = (char*)buf;
uint32_t num = 0;
while(*buf){
char c = *buf;
uint8_t M = 0;
if(c >= '0' && c <= '9'){
M = '0';
}else if(c >= 'A' && c <= 'F'){
M = 'A' - 10;
}else if(c >= 'a' && c <= 'f'){
M = 'a' - 10;
}
if(M){
if(num & 0xf0000000){ // overflow
*N = 0xffffff;
return start;
}
num <<= 4;
num += c - M;
}else{
break;
}
++buf;
}
*N = num;
return (char*)buf;
}
// In case of overflow return `buf` and N==0xffffffff
// read decimal number & return pointer to next non-number symbol
static char *getdec(const char *buf, uint32_t *N){
char *start = (char*)buf;
uint32_t num = 0;
while(*buf){
char c = *buf;
if(c < '0' || c > '9'){
break;
}
if(num > 429496729 || (num == 429496729 && c > '5')){ // overflow
*N = 0xffffff;
return start;
}
num *= 10;
num += c - '0';
++buf;
}
*N = num;
return (char*)buf;
}
// read octal number (without 0 prefix!)
static char *getoct(const char *buf, uint32_t *N){
char *start = (char*)buf;
uint32_t num = 0;
while(*buf){
char c = *buf;
if(c < '0' || c > '7'){
break;
}
if(num & 0xe0000000){ // overflow
*N = 0xffffff;
return start;
}
num <<= 3;
num += c - '0';
++buf;
}
*N = num;
return (char*)buf;
}
// read binary number (without b prefix!)
static char *getbin(const char *buf, uint32_t *N){
char *start = (char*)buf;
uint32_t num = 0;
while(*buf){
char c = *buf;
if(c < '0' || c > '1'){
break;
}
if(num & 0x80000000){ // overflow
*N = 0xffffff;
return start;
}
num <<= 1;
if(c == '1') num |= 1;
++buf;
}
*N = num;
return (char*)buf;
}
/**
* @brief getnum - read uint32_t from string (dec, hex or bin: 127, 0x7f, 0b1111111)
* @param buf - buffer with number and so on
* @param N - the number read
* @return pointer to first non-number symbol in buf
* (if it is == buf, there's no number or if *N==0xffffffff there was overflow)
*/
char *getnum(const char *txt, uint32_t *N){
char *nxt = NULL;
char *s = omit_spaces(txt);
if(*s == '0'){ // hex, oct or 0
if(s[1] == 'x' || s[1] == 'X'){ // hex
nxt = gethex(s+2, N);
if(nxt == s+2) nxt = (char*)txt;
}else if(s[1] > '0'-1 && s[1] < '8'){ // oct
nxt = getoct(s+1, N);
if(nxt == s+1) nxt = (char*)txt;
}else{ // 0
nxt = s+1;
*N = 0;
}
}else if(*s == 'b' || *s == 'B'){
nxt = getbin(s+1, N);
if(nxt == s+1) nxt = (char*)txt;
}else{
nxt = getdec(s, N);
if(nxt == s) nxt = (char*)txt;
}
return nxt;
}
// parse `txt` to CAN_message
static CAN_message *parseCANmsg(char *txt){
static CAN_message canmsg;
uint32_t N;
char *n;
int ctr = -1;
canmsg.ID = 0xffff;
do{
txt = omit_spaces(txt);
n = getnum(txt, &N);
if(txt == n) break;
txt = n;
if(ctr == -1){
if(N > 0x7ff){
usart_send("ID should be 11-bit number!\n");
return NULL;
}
canmsg.ID = (uint16_t)(N&0x7ff);
ctr = 0;
continue;
}
if(ctr > 7){
usart_send("ONLY 8 data bytes allowed!\n");
return NULL;
}
if(N > 0xff){
usart_send("Every data portion is a byte!\n");
return NULL;
}
canmsg.data[ctr++] = (uint8_t)(N&0xff);
}while(1);
if(canmsg.ID == 0xffff){
usart_send("NO ID given, send nothing!\n");
return NULL;
}
usart_send("Message parsed OK\n");
canmsg.length = (uint8_t) ctr;
return &canmsg;
}
// usart_send command, format: ID (hex/bin/dec) data bytes (up to 8 bytes, space-delimeted)
TRUE_INLINE void usart_sendCANcommand(char *txt){
if(CAN1->MSR & CAN_MSR_INAK){
usart_send("CAN bus is off, try to restart it\n");
return;
}
CAN_message *msg = parseCANmsg(txt);
if(!msg) return;
uint32_t N = 3;
while(CAN_BUSY == can_send(msg->data, msg->length, msg->ID)){
if(--N == 0) break;
}
}
TRUE_INLINE void CANini(char *txt){
txt = omit_spaces(txt);
uint32_t N;
char *n = getnum(txt, &N);
if(txt == n){
usart_send("No speed given");
return;
}
if(N < 50){
usart_send("Lowest speed is 50kbps");
return;
}else if(N > 3000){
usart_send("Highest speed is 3000kbps");
return;
}
CAN_reinit((uint16_t)N);
usart_send("Reinit CAN bus with speed ");
printu(N); usart_send("kbps");
}
TRUE_INLINE void addIGN(char *txt){
if(IgnSz == IGN_SIZE){
usart_send("Ignore buffer is full");
return;
}
txt = omit_spaces(txt);
uint32_t N;
char *n = getnum(txt, &N);
if(txt == n){
usart_send("No ID given");
return;
}
if(N > 0x7ff){
usart_send("ID should be 11-bit number!");
return;
}
Ignore_IDs[IgnSz++] = (uint16_t)(N & 0x7ff);
usart_send("Added ID "); printu(N);
usart_send("\nIgn buffer size: "); printu(IgnSz);
}
TRUE_INLINE void print_ign_buf(){
if(IgnSz == 0){
usart_send("Ignore buffer is empty");
return;
}
usart_send("Ignored IDs:\n");
for(int i = 0; i < IgnSz; ++i){
printu(i);
usart_send(": ");
printuhex(Ignore_IDs[i]);
usart_putchar('\n');
}
}
// print ID/mask of CAN1->sFilterRegister[x] half
static void printID(uint16_t FRn){
if(FRn & 0x1f) return; // trash
printuhex(FRn >> 5);
}
/*
Can filtering: FSCx=0 (CAN1->FS1R) -> 16-bit identifiers
CAN1->FMR = (sb)<<8 | FINIT - init filter in starting bank sb
CAN1->FFA1R FFAx = 1 -> FIFO1, 0 -> FIFO0
CAN1->FA1R FACTx=1 - filter active
MASK: FBMx=0 (CAN1->FM1R), two filters (n in FR1 and n+1 in FR2)
ID: CAN1->sFilterRegister[x].FRn[0..15]
MASK: CAN1->sFilterRegister[x].FRn[16..31]
FR bits: STID[10:0] RTR IDE EXID[17:15]
LIST: FBMx=1, four filters (n&n+1 in FR1, n+2&n+3 in FR2)
IDn: CAN1->sFilterRegister[x].FRn[0..15]
IDn+1: CAN1->sFilterRegister[x].FRn[16..31]
*/
TRUE_INLINE void list_filters(){
uint32_t fa = CAN1->FA1R, ctr = 0, mask = 1;
while(fa){
if(fa & 1){
usart_send("Filter "); printu(ctr); usart_send(", FIFO");
if(CAN1->FFA1R & mask) usart_send("1");
else usart_send("0");
usart_send(" in ");
if(CAN1->FM1R & mask){ // up to 4 filters in LIST mode
usart_send("LIST mode, IDs: ");
printID(CAN1->sFilterRegister[ctr].FR1 & 0xffff);
usart_send(" ");
printID(CAN1->sFilterRegister[ctr].FR1 >> 16);
usart_send(" ");
printID(CAN1->sFilterRegister[ctr].FR2 & 0xffff);
usart_send(" ");
printID(CAN1->sFilterRegister[ctr].FR2 >> 16);
}else{ // up to 2 filters in MASK mode
usart_send("MASK mode: ");
if(!(CAN1->sFilterRegister[ctr].FR1&0x1f)){
usart_send("ID="); printID(CAN1->sFilterRegister[ctr].FR1 & 0xffff);
usart_send(", MASK="); printID(CAN1->sFilterRegister[ctr].FR1 >> 16);
usart_send(" ");
}
if(!(CAN1->sFilterRegister[ctr].FR2&0x1f)){
usart_send("ID="); printID(CAN1->sFilterRegister[ctr].FR2 & 0xffff);
usart_send(", MASK="); printID(CAN1->sFilterRegister[ctr].FR2 >> 16);
}
}
usart_putchar('\n');
}
fa >>= 1;
++ctr;
mask <<= 1;
}
}
/**
* @brief add_filter - add/modify filter
* @param str - string in format "bank# FIFO# mode num0 .. num3"
* where bank# - 0..27
* if there's nothing after bank# - delete filter
* FIFO# - 0,1
* mode - 'I' for ID, 'M' for mask
* num0..num3 - IDs in ID mode, ID/MASK for mask mode
*/
static void add_filter(char *str){
uint32_t N;
str = omit_spaces(str);
char *n = getnum(str, &N);
if(n == str){
usart_send("No bank# given");
return;
}
if(N > STM32F0FBANKNO-1){
usart_send("bank# > 27");
return;
}
uint8_t bankno = (uint8_t)N;
str = omit_spaces(n);
if(!*str){ // deactivate filter
usart_send("Deactivate filters in bank ");
printu(bankno);
CAN1->FMR = CAN_FMR_FINIT;
CAN1->FA1R &= ~(1<<bankno);
CAN1->FMR &=~ CAN_FMR_FINIT;
return;
}
uint8_t fifono = 0;
if(*str == '1') fifono = 1;
else if(*str != '0'){
usart_send("FIFO# is 0 or 1");
return;
}
str = omit_spaces(str + 1);
char c = *str;
uint8_t mode = 0; // ID
if(c == 'M' || c == 'm') mode = 1;
else if(c != 'I' && c != 'i'){
usart_send("mode is 'M/m' for MASK and 'I/i' for IDLIST");
return;
}
str = omit_spaces(str + 1);
uint32_t filters[4];
uint32_t nfilt;
for(nfilt = 0; nfilt < 4; ++nfilt){
n = getnum(str, &N);
if(n == str) break;
filters[nfilt] = N;
str = omit_spaces(n);
}
if(nfilt == 0){
usart_send("You should add at least one filter!");
return;
}
if(mode && (nfilt&1)){
usart_send("In MASK mode you should point pairs of ID/MASK");
return;
}
CAN1->FMR = CAN_FMR_FINIT;
uint32_t mask = 1<<bankno;
CAN1->FA1R |= mask; // activate given filter
if(fifono) CAN1->FFA1R |= mask; // set FIFO number
else CAN1->FFA1R &= ~mask;
if(mode) CAN1->FM1R &= ~mask; // MASK
else CAN1->FM1R |= mask; // LIST
uint32_t F1 = (0x8f<<16);
uint32_t F2 = (0x8f<<16);
// reset filter registers to wrong value
CAN1->sFilterRegister[bankno].FR1 = (0x8f<<16) | 0x8f;
CAN1->sFilterRegister[bankno].FR2 = (0x8f<<16) | 0x8f;
switch(nfilt){
case 4:
F2 = filters[3] << 21;
// fallthrough
case 3:
CAN1->sFilterRegister[bankno].FR2 = (F2 & 0xffff0000) | (filters[2] << 5);
// fallthrough
case 2:
F1 = filters[1] << 21;
// fallthrough
case 1:
CAN1->sFilterRegister[bankno].FR1 = (F1 & 0xffff0000) | (filters[0] << 5);
}
CAN1->FMR &=~ CAN_FMR_FINIT;
usart_send("Added filter with ");
printu(nfilt); usart_send(" parameters");
}
const char *helpmsg =
"https://github.com/eddyem/stm32samples/tree/master/F1:F103/canUART build#" BUILD_NUMBER " @ " BUILD_DATE "\n"
"'a' - add ID to ignore list (max 10 IDs)\n"
"'b' - reinit CAN with given baudrate\n"
"'c' - get CAN status\n"
"'d' - delete ignore list\n"
"'e' - get CAN errcodes\n"
"'f' - add/delete filter, format: bank# FIFO# mode(M/I) num0 [num1 [num2 [num3]]]\n"
"'F' - usart_send/clear flood message: F ID byte0 ... byteN\n"
"'I' - reinit CAN\n"
"'l' - list all active filters\n"
"'o' - turn LEDs OFF\n"
"'O' - turn LEDs ON\n"
"'p' - print ignore buffer\n"
"'P' - pause/resume in packets displaying\n"
"'R' - software reset\n"
"'s/S' - usart_send data over CAN: s ID byte0 .. byteN\n"
"'T' - get time from start (ms)\n"
;
TRUE_INLINE void getcanstat(){
usart_send("CAN_MSR=");
printuhex(CAN1->MSR);
usart_send("\nCAN_TSR=");
printuhex(CAN1->TSR);
usart_send("\nCAN_RF0R=");
printuhex(CAN1->RF0R);
usart_send("\nCAN_RF1R=");
printuhex(CAN1->RF1R);
}
/**
* @brief cmd_parser - command parsing
* @param txt - buffer with commands & data
*/
void cmd_parser(char *txt){
char _1st = txt[0];
/*
* parse long commands here
*/
switch(_1st){
case 'a':
addIGN(txt + 1);
goto eof;
break;
case 'b':
CANini(txt + 1);
goto eof;
break;
case 'f':
add_filter(txt + 1);
goto eof;
break;
case 'F':
set_flood(parseCANmsg(txt + 1));
goto eof;
break;
case 's':
case 'S':
usart_sendCANcommand(txt + 1);
goto eof;
break;
}
if(txt[1] != '\n') *txt = '?'; // help for wrong message length
switch(_1st){
case 'c':
getcanstat();
break;
case 'd':
IgnSz = 0;
break;
case 'e':
printCANerr();
break;
case 'I':
CAN_reinit(0);
break;
case 'l':
list_filters();
break;
case 'o':
ledsON = 0;
LED_off(LED0);
LED_off(LED1);
break;
case 'O':
ledsON = 1;
break;
case 'p':
print_ign_buf();
break;
case 'P':
ShowMsgs = !ShowMsgs;
if(ShowMsgs) usart_send("Resume\n");
else usart_send("Pause\n");
break;
case 'R':
usart_send("Soft reset\n");
usart_transmit();
// wait until DMA & USART done
while(!usart_txrdy);
while(!(USART1->SR & USART_SR_TXE));
USART1->CR1 = 0; // stop USART
NVIC_SystemReset();
break;
case 'T':
usart_send("Time (ms): ");
printu(Tms);
usart_putchar('\n');
break;
default: // help
usart_send(helpmsg);
break;
}
eof:
usart_putchar('\n');
}
// print 32bit unsigned int
void printu(uint32_t val){
char buf[11], *bufptr = &buf[10];
*bufptr = 0;
if(!val){
*(--bufptr) = '0';
}else{
while(val){
*(--bufptr) = val % 10 + '0';
val /= 10;
}
}
usart_send(bufptr);
}
// print 32bit unsigned int as hex
void printuhex(uint32_t val){
usart_send("0x");
uint8_t *ptr = (uint8_t*)&val + 3;
int8_t i, j, z=1;
for(i = 0; i < 4; ++i, --ptr){
if(*ptr == 0){ // omit leading zeros
if(i == 3) z = 0;
if(z) continue;
}
else z = 0;
for(j = 1; j > -1; --j){
uint8_t half = (*ptr >> (4*j)) & 0x0f;
if(half < 10) usart_putchar(half + '0');
else usart_putchar(half - 10 + 'a');
}
}
}
// check Ignore_IDs & return 1 if ID isn't in list
uint8_t isgood(uint16_t ID){
for(int i = 0; i < IgnSz; ++i)
if(Ignore_IDs[i] == ID) return 0;
return 1;
}

45
F1:F103/canUART/proto.h Normal file
View File

@ -0,0 +1,45 @@
/*
* This file is part of the canuart project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stm32f1.h>
#include "hardware.h"
#define BUFSZ (64)
#ifdef EBUG
#define DBG(str) do{usart_send(__FILE__ " (L" STR(__LINE__) "): " str); \
usart_putchar('\n'); usart_transmit(); }while(0)
#else
#define DBG(str)
#endif
#define IGN_SIZE 10
extern uint16_t Ignore_IDs[IGN_SIZE];
extern uint8_t IgnSz;
extern uint8_t ShowMsgs;
void cmd_parser(char *buf);
void printu(uint32_t val);
void printuhex(uint32_t val);
char *omit_spaces(const char *buf);
char *getnum(const char *buf, uint32_t *N);
uint8_t isgood(uint16_t ID);

140
F1:F103/canUART/usart.c Normal file
View File

@ -0,0 +1,140 @@
/*
* This file is part of the canuart project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "stm32f1.h"
#include "usart.h"
extern volatile uint32_t Tms;
static volatile int idatalen[2] = {0,0}; // received data line length (including '\n')
static volatile int odatalen[2] = {0,0};
volatile int usart_txrdy = 1; // transmission done
static volatile int usart_linerdy = 0 // received data ready
,dlen = 0 // length of data (including '\n') in current buffer
,usart_bufovr = 0 // input buffer overfull
;
int rbufno = 0, tbufno = 0; // current rbuf/tbuf numbers
static char rbuf[2][UARTBUFSZI], tbuf[2][UARTBUFSZO]; // receive & transmit buffers
static char *recvdata = NULL;
/**
* return length of received data (without trailing zero)
*/
int usart_getline(char **line){
if(usart_bufovr){
usart_bufovr = 0;
usart_linerdy = 0;
return -1;
}
if(!usart_linerdy) return 0;
*line = recvdata;
usart_linerdy = 0;
int x = dlen;
dlen = 0;
return x;
}
// transmit current tbuf and swap buffers
void usart_transmit(){
register int l = odatalen[tbufno];
if(!l) return;
uint32_t tmout = 16000000;
while(!usart_txrdy){if(--tmout == 0) return;}; // wait for previos buffer transmission
usart_txrdy = 0;
odatalen[tbufno] = 0;
DMA1_Channel4->CCR &= ~DMA_CCR_EN;
DMA1_Channel4->CMAR = (uint32_t) tbuf[tbufno]; // mem
DMA1_Channel4->CNDTR = l;
DMA1_Channel4->CCR |= DMA_CCR_EN;
tbufno = !tbufno;
}
void usart_putchar(const char ch){
if(odatalen[tbufno] == UARTBUFSZO) usart_transmit();
tbuf[tbufno][odatalen[tbufno]++] = ch;
}
void usart_send(const char *str){
while(*str){
if(odatalen[tbufno] == UARTBUFSZO) usart_transmit();
tbuf[tbufno][odatalen[tbufno]++] = *str++;
}
}
/*
* USART speed: baudrate = Fck/(USARTDIV)
* USARTDIV stored in USART->BRR
*
* for 72MHz USARTDIV=72000/f(kboud); so for 115200 USARTDIV=72000/115.2=625 -> BRR=0x271
* 9600: BRR = 7500 (0x1D4C)
*/
void usart_setup(){
uint32_t tmout = 16000000;
// PA9 - Tx, PA10 - Rx
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_USART1EN | RCC_APB2ENR_AFIOEN;
RCC->AHBENR |= RCC_AHBENR_DMA1EN;
GPIOA->CRH = CRH(9, CNF_AFPP|MODE_NORMAL) | CRH(10, CNF_FLINPUT|MODE_INPUT);
// USART1 Tx DMA - Channel4 (Rx - channel 5)
DMA1_Channel4->CPAR = (uint32_t) &USART1->DR; // periph
DMA1_Channel4->CCR |= DMA_CCR_MINC | DMA_CCR_DIR | DMA_CCR_TCIE; // 8bit, mem++, mem->per, transcompl irq
// Tx CNDTR set @ each transmission due to data size
NVIC_SetPriority(DMA1_Channel4_IRQn, 3);
NVIC_EnableIRQ(DMA1_Channel4_IRQn);
NVIC_SetPriority(USART1_IRQn, 0);
// setup usart1
USART1->BRR = 72000000 / 115200;
USART1->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_UE; // 1start,8data,nstop; enable Rx,Tx,USART
while(!(USART1->SR & USART_SR_TC)){if(--tmout == 0) break;} // polling idle frame Transmission
USART1->SR = 0; // clear flags
USART1->CR1 |= USART_CR1_RXNEIE; // allow Rx IRQ
USART1->CR3 = USART_CR3_DMAT; // enable DMA Tx
NVIC_EnableIRQ(USART1_IRQn);
}
void usart1_isr(){
if(USART1->SR & USART_SR_RXNE){ // RX not emty - receive next char
uint8_t rb = USART1->DR;
if(idatalen[rbufno] < UARTBUFSZI){ // put next char into buf
rbuf[rbufno][idatalen[rbufno]++] = rb;
if(rb == '\n'){ // got newline - line ready
usart_linerdy = 1;
dlen = idatalen[rbufno];
recvdata = rbuf[rbufno];
// prepare other buffer
rbufno = !rbufno;
idatalen[rbufno] = 0;
}
}else{ // buffer overrun
usart_bufovr = 1;
idatalen[rbufno] = 0;
}
}
}
void dma1_channel4_isr(){
if(DMA1->ISR & DMA_ISR_TCIF4){ // Tx
DMA1->IFCR = DMA_IFCR_CTCIF4; // clear TC flag
usart_txrdy = 1;
}
}

34
F1:F103/canUART/usart.h Normal file
View File

@ -0,0 +1,34 @@
/*
* This file is part of the canuart project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
// input and output buffers size
#define UARTBUFSZI (128)
#define UARTBUFSZO (128)
#define usartrx() (usart_linerdy)
#define usartovr() (usart_bufovr)
extern volatile int usart_txrdy;
void usart_transmit();
void usart_setup();
int usart_getline(char **line);
void usart_send(const char *str);
void usart_putchar(const char ch);

View File

@ -0,0 +1,2 @@
#define BUILD_NUMBER "64"
#define BUILD_DATE "2022-12-05"