From cfff079dbaef4c081de449c04d7092f791da8fab Mon Sep 17 00:00:00 2001 From: Edward Emelianov Date: Mon, 5 Dec 2022 11:50:17 +0300 Subject: [PATCH] Add canUART for STM32F103 --- F1:F103/canUART/CANUART.bin | Bin 0 -> 7648 bytes F1:F103/canUART/Makefile | 162 ++++++++ F1:F103/canUART/Readme.md | 2 + F1:F103/canUART/can.c | 380 ++++++++++++++++++ F1:F103/canUART/can.h | 58 +++ F1:F103/canUART/canuart.cflags | 1 + F1:F103/canUART/canuart.config | 7 + F1:F103/canUART/canuart.creator | 1 + F1:F103/canUART/canuart.creator.user | 160 ++++++++ F1:F103/canUART/canuart.cxxflags | 1 + F1:F103/canUART/canuart.files | 9 + F1:F103/canUART/canuart.includes | 7 + F1:F103/canUART/hardware.c | 55 +++ F1:F103/canUART/hardware.h | 58 +++ F1:F103/canUART/main.c | 93 +++++ F1:F103/canUART/openocd.cfg | 6 + F1:F103/canUART/proto.c | 574 +++++++++++++++++++++++++++ F1:F103/canUART/proto.h | 45 +++ F1:F103/canUART/usart.c | 140 +++++++ F1:F103/canUART/usart.h | 34 ++ F1:F103/canUART/version.inc | 2 + 21 files changed, 1795 insertions(+) create mode 100755 F1:F103/canUART/CANUART.bin create mode 100644 F1:F103/canUART/Makefile create mode 100644 F1:F103/canUART/Readme.md create mode 100644 F1:F103/canUART/can.c create mode 100644 F1:F103/canUART/can.h create mode 100644 F1:F103/canUART/canuart.cflags create mode 100644 F1:F103/canUART/canuart.config create mode 100644 F1:F103/canUART/canuart.creator create mode 100644 F1:F103/canUART/canuart.creator.user create mode 100644 F1:F103/canUART/canuart.cxxflags create mode 100644 F1:F103/canUART/canuart.files create mode 100644 F1:F103/canUART/canuart.includes create mode 100644 F1:F103/canUART/hardware.c create mode 100644 F1:F103/canUART/hardware.h create mode 100644 F1:F103/canUART/main.c create mode 100644 F1:F103/canUART/openocd.cfg create mode 100644 F1:F103/canUART/proto.c create mode 100644 F1:F103/canUART/proto.h create mode 100644 F1:F103/canUART/usart.c create mode 100644 F1:F103/canUART/usart.h create mode 100644 F1:F103/canUART/version.inc diff --git a/F1:F103/canUART/CANUART.bin b/F1:F103/canUART/CANUART.bin new file mode 100755 index 0000000000000000000000000000000000000000..67ae6200fc59092df05961f44b4ee6077170f873 GIT binary patch literal 7648 zcmbU_4Omm>x!=jj9|1KGu>9$BNI=kl1gNdUc7y~@Ne&POcw6gSPk`V_3nV5%W7oR^ zZP&VXn-#aKU^lO>_inpw2Ua`X)up$#`)T#LL17oQo3y(S3+;ALltU!uzTXLGXSY4i zEaV+Nu0_61 zIp_sA2Czu`N88s^{{OQ7=v;U6+jx{v@Ck4GGV}aEhW{h_WBQNu*-wZwXFrji$r!ZF zbR~U>Nw6Op>L7_U+?=7X)NjI@LoGeQzI0-zMo(<~_Pi z+V_k=?C#qpgI03z8G#(QxGl}|)ovw7uXig08{B%%%u}SE)pPxdSBH>J&ngB^UE#m` z5<(PG62^oUWK;tTIFK1#xD20>1DnaS%PnC1CJusSK9m7Tj< zFD*bQ=h>Z=lhVox{LPl_%rU>~&z67FUok1Kpz${w`Rip;vxz4p2UwE&J-dl@pG;@n z522iV`m+%JhT!|h5X!y`?Zwc0I}7B)BK@Nf0=r19gh}FBHEEX` zGB+PtT7~_i)T5~$Bn=>~hE^X{22}1iYic0go$NngB8Q^cNSEN&xYZ{?2Zi-4t`VRBjs23YTmrb^9C!iUc(t@64W|gLTXqI zmk4r3z=C!)m&Z^%fz-Dp&nd#gM7C`PrPz2XQKGf+WCEffEAIi2uV79K$aGrBeCM=a zOgb$jYflSR_2&ho)x!KRrrqRBv6jzB%ggyHVv}8C=@F929w7x_Ie8D8!Y*eYVH4au zc*A((c*#CfULch&&RZWSrU=W^A)FHu@C#B)j0h1%lmL)DgK#X+M`#SkKxv7yz6g2M zr7_PS^NXy;iM^n)Yn(c| ze#HOtO$u;6dJym(H&+5a8P##8uSqn-2D$$Gfplv|RlT4?i2p-04Ms1)=q5$VaGxS! z_>w|CjC3kW$70Qh|5+djINp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0M=VN$3C~Su0^-!=Cxmu|9*p5(2(bxlcuQ5<-*RB<@T2-zEi{4qaDz^<2MEAgs zM2Qi*9WPa`3y=CbJsnhaWrdfr(X=Ypb{7q_x-rS^!F93V@Yoiq%B>SeaHbSOia_4r z9B|v4pK$oRREyK=ZnN)%txT0$j~N%Y@P%~B^%gc@@|~r|wn@Bc $(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 diff --git a/F1:F103/canUART/Readme.md b/F1:F103/canUART/Readme.md new file mode 100644 index 0000000..d20e982 --- /dev/null +++ b/F1:F103/canUART/Readme.md @@ -0,0 +1,2 @@ +CAN bus (PB8/PB9) <> UART1 (PA9/PA10) +The same thing as canusb for STM32F0x2 diff --git a/F1:F103/canUART/can.c b/F1:F103/canUART/can.c new file mode 100644 index 0000000..9d31b6f --- /dev/null +++ b/F1:F103/canUART/can.c @@ -0,0 +1,380 @@ +/* + * This file is part of the canuart project. + * Copyright 2022 Edward V. Emelianov . + * + * 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 . + */ + +#include "can.h" +#include "hardware.h" +#include "proto.h" +#include "usart.h" + +// REMAPPED to PB8/PB9!!! + +#include // 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; + } +} diff --git a/F1:F103/canUART/can.h b/F1:F103/canUART/can.h new file mode 100644 index 0000000..fa09374 --- /dev/null +++ b/F1:F103/canUART/can.h @@ -0,0 +1,58 @@ +/* + * This file is part of the canuart project. + * Copyright 2022 Edward V. Emelianov . + * + * 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 . + */ + +#pragma once + +#include + +// 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); diff --git a/F1:F103/canUART/canuart.cflags b/F1:F103/canUART/canuart.cflags new file mode 100644 index 0000000..68d5165 --- /dev/null +++ b/F1:F103/canUART/canuart.cflags @@ -0,0 +1 @@ +-std=c17 \ No newline at end of file diff --git a/F1:F103/canUART/canuart.config b/F1:F103/canUART/canuart.config new file mode 100644 index 0000000..46273ce --- /dev/null +++ b/F1:F103/canUART/canuart.config @@ -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 diff --git a/F1:F103/canUART/canuart.creator b/F1:F103/canUART/canuart.creator new file mode 100644 index 0000000..e94cbbd --- /dev/null +++ b/F1:F103/canUART/canuart.creator @@ -0,0 +1 @@ +[General] diff --git a/F1:F103/canUART/canuart.creator.user b/F1:F103/canUART/canuart.creator.user new file mode 100644 index 0000000..ebefce4 --- /dev/null +++ b/F1:F103/canUART/canuart.creator.user @@ -0,0 +1,160 @@ + + + + + + EnvironmentId + {cf63021e-ef53-49b0-b03b-2f2570cdf3b6} + + + ProjectExplorer.Project.ActiveTarget + 0 + + + ProjectExplorer.Project.EditorSettings + + true + false + true + + Cpp + + CppGlobal + + + + QmlJS + + QmlJSGlobal + + + 2 + KOI8-R + false + 4 + false + 80 + true + true + 1 + false + false + false + 1 + true + true + 0 + 8 + true + false + 2 + true + true + true + *.md, *.MD, Makefile + true + true + + + + ProjectExplorer.Project.PluginSettings + + + true + true + Builtin.DefaultTidyAndClazy + 4 + + + + true + + + + + ProjectExplorer.Project.Target.0 + + Desktop + Desktop + Desktop + {91347f2c-5221-46a7-80b1-0a054ca02f79} + 0 + 0 + 0 + + /home/eddy/Docs/SAO/ELECTRONICS/STM32/F1-srcs/usbcan + + + + all + + true + GenericProjectManager.GenericMakeStep + + 1 + Сборка + Сборка + ProjectExplorer.BuildSteps.Build + + + + + clean + + true + GenericProjectManager.GenericMakeStep + + 1 + Очистка + Очистка + ProjectExplorer.BuildSteps.Clean + + 2 + false + + false + + По умолчанию + GenericProjectManager.GenericBuildConfiguration + + 1 + + + 0 + Развёртывание + Развёртывание + ProjectExplorer.BuildSteps.Deploy + + 1 + + false + ProjectExplorer.DefaultDeployConfiguration + + 1 + + + 2 + + ProjectExplorer.CustomExecutableRunConfiguration + + false + true + false + true + + 1 + + + + ProjectExplorer.Project.TargetCount + 1 + + + ProjectExplorer.Project.Updater.FileVersion + 22 + + + Version + 22 + + diff --git a/F1:F103/canUART/canuart.cxxflags b/F1:F103/canUART/canuart.cxxflags new file mode 100644 index 0000000..6435dfc --- /dev/null +++ b/F1:F103/canUART/canuart.cxxflags @@ -0,0 +1 @@ +-std=c++17 \ No newline at end of file diff --git a/F1:F103/canUART/canuart.files b/F1:F103/canUART/canuart.files new file mode 100644 index 0000000..2545be1 --- /dev/null +++ b/F1:F103/canUART/canuart.files @@ -0,0 +1,9 @@ +can.c +can.h +hardware.c +hardware.h +main.c +proto.c +proto.h +usart.c +usart.h diff --git a/F1:F103/canUART/canuart.includes b/F1:F103/canUART/canuart.includes new file mode 100644 index 0000000..0dce01d --- /dev/null +++ b/F1:F103/canUART/canuart.includes @@ -0,0 +1,7 @@ +. +../inc +../inc/Fx +../inc/cm +../inc/ld +../inc/startup + diff --git a/F1:F103/canUART/hardware.c b/F1:F103/canUART/hardware.c new file mode 100644 index 0000000..e868663 --- /dev/null +++ b/F1:F103/canUART/hardware.c @@ -0,0 +1,55 @@ +/* + * This file is part of the canuart project. + * Copyright 2022 Edward V. Emelianov . + * + * 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 . + */ + +#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) */ +} diff --git a/F1:F103/canUART/hardware.h b/F1:F103/canUART/hardware.h new file mode 100644 index 0000000..9663f8c --- /dev/null +++ b/F1:F103/canUART/hardware.h @@ -0,0 +1,58 @@ +/* + * This file is part of the canuart project. + * Copyright 2022 Edward V. Emelianov . + * + * 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 . + */ + +#pragma once + +#include + +#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(); + diff --git a/F1:F103/canUART/main.c b/F1:F103/canUART/main.c new file mode 100644 index 0000000..833e4be --- /dev/null +++ b/F1:F103/canUART/main.c @@ -0,0 +1,93 @@ +/* + * This file is part of the canuart project. + * Copyright 2022 Edward V. Emelianov . + * + * 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 . + */ + +#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; +} + diff --git a/F1:F103/canUART/openocd.cfg b/F1:F103/canUART/openocd.cfg new file mode 100644 index 0000000..f8936b2 --- /dev/null +++ b/F1:F103/canUART/openocd.cfg @@ -0,0 +1,6 @@ +# STM32F103C8 "Blue Pill" + +set FLASH_SIZE 0x8000 + +source [find interface/stlink-v2-1.cfg] +source [find target/stm32f1x.cfg] diff --git a/F1:F103/canUART/proto.c b/F1:F103/canUART/proto.c new file mode 100644 index 0000000..aae7b3c --- /dev/null +++ b/F1:F103/canUART/proto.c @@ -0,0 +1,574 @@ +/* + * This file is part of the canuart project. + * Copyright 2022 Edward V. Emelianov . + * + * 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 . + */ + +#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<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<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; +} diff --git a/F1:F103/canUART/proto.h b/F1:F103/canUART/proto.h new file mode 100644 index 0000000..2689d93 --- /dev/null +++ b/F1:F103/canUART/proto.h @@ -0,0 +1,45 @@ +/* + * This file is part of the canuart project. + * Copyright 2022 Edward V. Emelianov . + * + * 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 . + */ + +#pragma once + +#include +#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); diff --git a/F1:F103/canUART/usart.c b/F1:F103/canUART/usart.c new file mode 100644 index 0000000..7927473 --- /dev/null +++ b/F1:F103/canUART/usart.c @@ -0,0 +1,140 @@ +/* + * This file is part of the canuart project. + * Copyright 2022 Edward V. Emelianov . + * + * 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 . + */ + +#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; + } +} diff --git a/F1:F103/canUART/usart.h b/F1:F103/canUART/usart.h new file mode 100644 index 0000000..3d20150 --- /dev/null +++ b/F1:F103/canUART/usart.h @@ -0,0 +1,34 @@ +/* + * This file is part of the canuart project. + * Copyright 2022 Edward V. Emelianov . + * + * 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 . + */ + +#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); diff --git a/F1:F103/canUART/version.inc b/F1:F103/canUART/version.inc new file mode 100644 index 0000000..fc513df --- /dev/null +++ b/F1:F103/canUART/version.inc @@ -0,0 +1,2 @@ +#define BUILD_NUMBER "64" +#define BUILD_DATE "2022-12-05"