restructuring

This commit is contained in:
2022-03-10 11:04:14 +03:00
parent 29560b7c0c
commit 733dbd75d2
1758 changed files with 14 additions and 26855 deletions

View File

@@ -0,0 +1,150 @@
BINARY = pl2303
BOOTPORT ?= /dev/ttyUSB0
BOOTSPEED ?= 57600
# MCU FAMILY
FAMILY = F0
# MCU code
#MCU = F042x6
MCU = F072xB
# hardware definitions
#DEFS += -DCHECK_TMOUT
#DEFS += -DEBUG
# change this linking script depending on particular MCU model
#LDSCRIPT = stm32f042k.ld
LDSCRIPT = stm32f0728.ld
INDEPENDENT_HEADERS=
FP_FLAGS ?= -msoft-float
ASM_FLAGS = -mthumb -mcpu=cortex-m0 -march=armv6-m -mtune=cortex-m0
ARCH_FLAGS = $(ASM_FLAGS) $(FP_FLAGS)
###############################################################################
# Executables
OPREFIX ?= /opt/bin/arm-none-eabi
PREFIX ?= $(OPREFIX)
RM := rm -f
RMDIR := rmdir
CC := $(PREFIX)-gcc
LD := $(PREFIX)-gcc
AR := $(PREFIX)-ar
AS := $(PREFIX)-as
SIZE := $(PREFIX)-size
OBJCOPY := $(OPREFIX)-objcopy
OBJDUMP := $(OPREFIX)-objdump
GDB := $(OPREFIX)-gdb
STFLASH := $(shell which st-flash)
STBOOT := $(shell which stm32flash)
DFUUTIL := $(shell which dfu-util)
###############################################################################
# Source files
OBJDIR = mk
LDSCRIPT ?= $(BINARY).ld
SRC := $(wildcard *.c)
OBJS := $(addprefix $(OBJDIR)/, $(SRC:%.c=%.o))
STARTUP = $(OBJDIR)/startup.o
OBJS += $(STARTUP)
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 -MD -D__thumb2__=1
CFLAGS += -Wall -Werror -Wextra -Wshadow -Wimplicit-function-declaration
CFLAGS += -Wredundant-decls $(INCLUDE)
# -Wmissing-prototypes -Wstrict-prototypes
CFLAGS += -fno-common -ffunction-sections -fdata-sections
#CGLAGS += -fno-stack-protector
###############################################################################
# Linker flags
LDFLAGS += --static -nostartfiles --specs=nano.specs
#LDFLAGS += -fno-stack-protector
LDFLAGS += -L$(LIB_DIR)
LDFLAGS += -T$(LDSCRIPT)
LDFLAGS += -Wl,-Map=$(OBJDIR)/$(BINARY).map
LDFLAGS += -Wl,--gc-sections
###############################################################################
# Used libraries
LDLIBS += -Wl,--start-group -lc -lgcc -Wl,--end-group
LDLIBS += $(shell $(CC) $(CFLAGS) -print-libgcc-file-name)
DEFS += -DSTM32$(FAMILY) -DSTM32$(MCU)
#.SUFFIXES: .elf .bin .hex .srec .list .map .images
#.SECONDEXPANSION:
#.SECONDARY:
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) $(ARCH_FLAGS) -o $@ -c $<
$(OBJDIR)/%.o: %.c
@echo " CC $<"
$(CC) $(CFLAGS) $(DEFS) $(INCLUDE) $(ARCH_FLAGS) -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) $(ARCH_FLAGS) $(OBJS) $(LDLIBS) -o $(ELF)
size: $(ELF)
$(SIZE) $(ELF)
clean:
@echo " CLEAN"
$(RM) $(OBJS) $(DEPS) $(ELF) $(HEX) $(LIST) $(OBJDIR)/*.map *.d
@rmdir $(OBJDIR) 2>/dev/null || true
dfuboot: $(BIN)
@echo " LOAD $(BIN) THROUGH DFU"
$(DFUUTIL) -a0 -D $(BIN) -s 0x08000000
flash: $(BIN)
@echo " FLASH $(BIN)"
$(STFLASH) write $(BIN) 0x8000000
boot: $(BIN)
@echo " LOAD $(BIN) through bootloader"
$(STBOOT) -b$(BOOTSPEED) $(BOOTPORT) -w $(BIN)
gentags:
CFLAGS="$(CFLAGS) $(DEFS)" geany -g $(BINARY).c.tags *[hc] 2>/dev/null
.PHONY: clean flash boot gentags

View File

@@ -0,0 +1,2 @@
Simple test for STM32F0x2, PWM for all 4 channels of TIM3, USB (PL2303 emulator); USART1/2/3, SPI1/2,
I2C1 tests, ADC1 IN0/1 connected to variable resistor.

View File

@@ -0,0 +1,84 @@
/*
* This file is part of the Chiller project.
* Copyright 2018 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 "adc.h"
/**
* @brief ADC_array - array for ADC channels with median filtering:
* 0 - Rvar
* 1 - Rvar/2
* 2 - AIN5/DAC_OUT1
* 3 - internal Tsens
* 4 - Vref
*/
#define CHTSENS (3)
#define CHVREF (4)
uint16_t ADC_array[NUMBER_OF_ADC_CHANNELS*9];
/**
* @brief getADCval - calculate median value for `nch` channel
* @param nch - number of channel
* @return
*/
uint16_t getADCval(int nch){
int i, addr = nch;
register uint16_t temp;
#define PIX_SORT(a,b) { if ((a)>(b)) PIX_SWAP((a),(b)); }
#define PIX_SWAP(a,b) { temp=(a);(a)=(b);(b)=temp; }
uint16_t p[9];
for(i = 0; i < 9; ++i, addr += NUMBER_OF_ADC_CHANNELS) // first we should prepare array for optmed
p[i] = ADC_array[addr];
PIX_SORT(p[1], p[2]) ; PIX_SORT(p[4], p[5]) ; PIX_SORT(p[7], p[8]) ;
PIX_SORT(p[0], p[1]) ; PIX_SORT(p[3], p[4]) ; PIX_SORT(p[6], p[7]) ;
PIX_SORT(p[1], p[2]) ; PIX_SORT(p[4], p[5]) ; PIX_SORT(p[7], p[8]) ;
PIX_SORT(p[0], p[3]) ; PIX_SORT(p[5], p[8]) ; PIX_SORT(p[4], p[7]) ;
PIX_SORT(p[3], p[6]) ; PIX_SORT(p[1], p[4]) ; PIX_SORT(p[2], p[5]) ;
PIX_SORT(p[4], p[7]) ; PIX_SORT(p[4], p[2]) ; PIX_SORT(p[6], p[4]) ;
PIX_SORT(p[4], p[2]) ;
return p[4];
#undef PIX_SORT
#undef PIX_SWAP
}
// get voltage @input nch (1/100V)
uint32_t getADCvoltage(int nch){
uint32_t v = getADCval(nch);
v *= getVdd();
v /= 0xfff; // 12bit ADC
return v;
}
// return MCU temperature (degrees of celsius * 10)
int32_t getMCUtemp(){
// getVdd();
// make correction on Vdd value
// int32_t temperature = (int32_t)ADC_array[4] * VddValue / 330;
int32_t ADval = getADCval(CHTSENS);
int32_t temperature = (int32_t) *TEMP30_CAL_ADDR - ADval;
temperature *= (int32_t)(1100 - 300);
temperature /= (int32_t)(*TEMP30_CAL_ADDR - *TEMP110_CAL_ADDR);
temperature += 300;
return(temperature);
}
// return Vdd (1/100V)
uint32_t getVdd(){
uint32_t vdd = ((uint32_t) *VREFINT_CAL_ADDR) * (uint32_t)330; // 3.3V
vdd /= getADCval(CHVREF);
return vdd;
}

View File

@@ -0,0 +1,31 @@
/*
* This file is part of the Chiller project.
* Copyright 2018 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/>.
*/
#ifndef ADC_H
#define ADC_H
#include "stm32f0.h"
#define NUMBER_OF_ADC_CHANNELS (5)
extern uint16_t ADC_array[];
int32_t getMCUtemp();
uint32_t getVdd();
uint16_t getADCval(int nch);
uint32_t getADCvoltage(int nch);
#endif // ADC_H

View File

@@ -0,0 +1,219 @@
/*
* geany_encoding=koi8-r
* hardware.c - hardware-dependent macros & functions
*
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#include "adc.h"
#include "hardware.h"
#include "proto.h"
#include "spi.h"
#include "usart.h"
#include "usb.h"
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) */
}
static inline void gpio_setup(){
// here we turn on clocking for all periph.
RCC->AHBENR |= RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN | RCC_AHBENR_DMAEN;
// Set LEDS (PA6-8, PB0/1) as Out & AF (PWM); PA0,1,5 - AIN, PA4 - DAC
GPIOA->MODER = GPIO_MODER_MODER0_AI | GPIO_MODER_MODER1_AI | GPIO_MODER_MODER4_AI |
GPIO_MODER_MODER5_AI | GPIO_MODER_MODER6_AF | GPIO_MODER_MODER7_AF | GPIO_MODER_MODER8_AF;
GPIOB->MODER = GPIO_MODER_MODER0_AF | GPIO_MODER_MODER1_AF;
// alternate functions: PA6-8: TIM3CH1,2 and TIM1_CH1 (AF1, AF1, AF2)
// PB0-1: TIM3CH3,4 (AF1, AF1),
GPIOA->AFR[0] = (1 << (6 * 4)) | (1 << (7 * 4));
GPIOA->AFR[1] = (2 << (0 * 4));
GPIOB->AFR[0] = (1 << (0 * 4)) | (1 << (1 * 4));
}
// Setup ADC and DAC
static inline void adc_setup(){
uint16_t ctr = 0; // 0xfff0 - more than 1.3ms
// Enable clocking
/* (1) Enable the peripheral clock of the ADC */
/* (2) Start HSI14 RC oscillator */
/* (3) Wait HSI14 is ready */
RCC->APB2ENR |= RCC_APB2ENR_ADC1EN; /* (1) */
RCC->CR2 |= RCC_CR2_HSI14ON; /* (2) */
while ((RCC->CR2 & RCC_CR2_HSI14RDY) == 0 && ++ctr < 0xfff0){}; /* (3) */
// calibration
/* (1) Ensure that ADEN = 0 */
/* (2) Clear ADEN */
/* (3) Launch the calibration by setting ADCAL */
/* (4) Wait until ADCAL=0 */
if ((ADC1->CR & ADC_CR_ADEN) != 0){ /* (1) */
ADC1->CR &= (uint32_t)(~ADC_CR_ADEN); /* (2) */
}
ADC1->CR |= ADC_CR_ADCAL; /* (3) */
ctr = 0; // ADC calibration time is 5.9us
while ((ADC1->CR & ADC_CR_ADCAL) != 0 && ++ctr < 0xfff0){}; /* (4) */
// enable ADC
ctr = 0;
do{
ADC1->CR |= ADC_CR_ADEN;
}while ((ADC1->ISR & ADC_ISR_ADRDY) == 0 && ++ctr < 0xfff0);
// configure ADC to generate a triangle wave on DAC1_OUT synchronized by TIM6 HW trigger
/* (1) Select HSI14 by writing 00 in CKMODE (reset value) */
/* (2) Select the continuous mode */
/* (3) Select CHSEL0,1,5 - ADC inputs, 16,17 - t. sensor and vref */
/* (4) Select a sampling mode of 111 i.e. 239.5 ADC clk to be greater than 17.1us */
/* (5) Wake-up the VREFINT and Temperature sensor (only for VBAT, Temp sensor and VRefInt) */
// ADC1->CFGR2 &= ~ADC_CFGR2_CKMODE; /* (1) */
ADC1->CFGR1 |= ADC_CFGR1_CONT; /* (2)*/
ADC1->CHSELR = ADC_CHSELR_CHSEL0 | ADC_CHSELR_CHSEL1 | ADC_CHSELR_CHSEL5 | ADC_CHSELR_CHSEL16 | ADC_CHSELR_CHSEL17; /* (3)*/
ADC1->SMPR |= ADC_SMPR_SMP_0 | ADC_SMPR_SMP_1 | ADC_SMPR_SMP_2; /* (4) */
ADC->CCR |= ADC_CCR_TSEN | ADC_CCR_VREFEN; /* (5) */
// configure DMA for ADC
// DMA for AIN
/* (1) Enable the peripheral clock on DMA */
/* (2) Enable DMA transfer on ADC and circular mode */
/* (3) Configure the peripheral data register address */
/* (4) Configure the memory address */
/* (5) Configure the number of DMA tranfer to be performs on DMA channel 1 */
/* (6) Configure increment, size, interrupts and circular mode */
/* (7) Enable DMA Channel 1 */
RCC->AHBENR |= RCC_AHBENR_DMA1EN; /* (1) */
ADC1->CFGR1 |= ADC_CFGR1_DMAEN | ADC_CFGR1_DMACFG; /* (2) */
DMA1_Channel1->CPAR = (uint32_t) (&(ADC1->DR)); /* (3) */
DMA1_Channel1->CMAR = (uint32_t)(ADC_array); /* (4) */
DMA1_Channel1->CNDTR = NUMBER_OF_ADC_CHANNELS * 9; /* (5) */
DMA1_Channel1->CCR |= DMA_CCR_MINC | DMA_CCR_MSIZE_0 | DMA_CCR_PSIZE_0 | DMA_CCR_CIRC; /* (6) */
DMA1_Channel1->CCR |= DMA_CCR_EN; /* (7) */
ADC1->CR |= ADC_CR_ADSTART; /* start the ADC conversions */
// DAC
/* (1) Enable the peripheral clock of the DAC */
/* (2) Configure WAVEx at 10,
Configure mask amplitude for ch1 (MAMP1) at 1011 for a 4095-bits amplitude
enable the DAC ch1, disable buffer on ch1,
and select TIM6 as trigger by keeping 000 in TSEL1 */
RCC->APB1ENR |= RCC_APB1ENR_DACEN; /* (1) */
DAC->CR |= DAC_CR_WAVE1_1
| DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0
| DAC_CR_BOFF1 | DAC_CR_TEN1 | DAC_CR_EN1; /* (2) */
// configure the Timer 6 to generate an external trigger on TRGO each microsecond
/* (1) Enable the peripheral clock of the TIM6 */
/* (2) Configure MMS=010 to output a rising edge at each update event */
/* (3) Select PCLK/2 i.e. 48MHz/2=24MHz */
/* (4) Set one update event each 1 microsecond */
/* (5) Enable TIM6 */
RCC->APB1ENR |= RCC_APB1ENR_TIM6EN; /* (1) */
TIM6->CR2 |= TIM_CR2_MMS_1; /* (2) */
TIM6->PSC = 1; /* (3) */
TIM6->ARR = (uint16_t)24; /* (4) */
TIM6->CR1 |= TIM_CR1_CEN; /* (5) */
}
static inline void pwm_setup(){
// enable clocking for tim1 & tim3
RCC->APB1ENR |= RCC_APB1ENR_TIM3EN;
RCC->APB2ENR |= RCC_APB2ENR_TIM1EN;
// PWM mode 2
TIM1->CCMR1 = TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_0;
TIM3->CCMR1 = TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_0 |
TIM_CCMR1_OC2M_2 | TIM_CCMR1_OC2M_1 | TIM_CCMR1_OC2M_0;
TIM3->CCMR2 = TIM_CCMR2_OC3M_2 | TIM_CCMR2_OC3M_1 | TIM_CCMR2_OC3M_0 |
TIM_CCMR2_OC4M_2 | TIM_CCMR2_OC4M_1 | TIM_CCMR2_OC4M_0;
// frequency - 8MHz for 31kHz PWM
TIM1->PSC = 5;
TIM3->PSC = 5;
// ARR for 8-bit PWM
TIM1->ARR = 254;
TIM3->ARR = 254;
TIM1->CCR1 = 127;
TIM3->CCR1 = 63; TIM3->CCR2 = 127; TIM3->CCR3 = 191; TIM3->CCR4 = 250;
// enable main output
TIM1->BDTR |= TIM_BDTR_MOE;
TIM3->BDTR |= TIM_BDTR_MOE;
// enable PWM outputs
TIM1->CCER = TIM_CCER_CC1E;
TIM3->CCER = TIM_CCER_CC1E | TIM_CCER_CC2E | TIM_CCER_CC3E | TIM_CCER_CC4E;
// start timers
TIM1->CR1 |= TIM_CR1_CEN;
TIM3->CR1 |= TIM_CR1_CEN;
}
void hw_setup(){
gpio_setup();
adc_setup();
pwm_setup();
}
// USART & SPI both use common DMA interrupts, so put them together here
// SPI Rx use the same DMA channels as USART Tx, so they can't work together!
// USART1 Tx (channel 2) & SPI1 Tx (channel 3)
void dma1_channel2_3_isr(){
if(DMA1->ISR & DMA_ISR_TCIF2){ // Tx
DMA1->IFCR |= DMA_IFCR_CTCIF2; // clear TC flag
txrdy[0] = 1;
}
if(DMA1->ISR & DMA_ISR_TCIF3){ // transfer done
DMA1->IFCR |= DMA_IFCR_CTCIF3;
SPI_status[0] = SPI_READY;
USND("SPI1 tx done\n");
}
if(DMA1->ISR & DMA_ISR_TEIF2){ // receiver overflow
DMA1->IFCR |= DMA_IFCR_CTEIF2;
SPIoverfl[0] = 1;
}
}
// USART2 + USART3 Tx (channels 4 and 7) & SPI2 Tx (channel 5)
void dma1_channel4_5_isr(){
if(DMA1->ISR & DMA_ISR_TCIF4){ // Tx
DMA1->IFCR |= DMA_IFCR_CTCIF4; // clear TC flag
txrdy[1] = 1;
}
if(DMA1->ISR & DMA_ISR_TEIF4){
DMA1->IFCR |= DMA_IFCR_CTEIF4;
SPIoverfl[1] = 1;
}
if(DMA1->ISR & DMA_ISR_TCIF5){
DMA1->IFCR |= DMA_IFCR_CTCIF5;
SPI_status[1] = SPI_READY;
USND("SPI2 tx done\n");
}
#ifdef USART3
if(DMA1->ISR & DMA_ISR_TCIF7){ // Tx
DMA1->IFCR |= DMA_IFCR_CTCIF7; // clear TC flag
txrdy[2] = 1;
}
#endif
}

View File

@@ -0,0 +1,46 @@
/*
* geany_encoding=koi8-r
* hardware.h
*
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#pragma once
#ifndef __HARDWARE_H__
#define __HARDWARE_H__
#include "stm32f0.h"
#define CONCAT(a,b) a ## b
#define STR_HELPER(s) #s
#define STR(s) STR_HELPER(s)
// PWM LEDS
#define SET_LED_PWM3(ch, N) do{TIM3->CCR ## ch = (uint32_t)N;}while(0)
#define GET_LED_PWM3(ch) (uint8_t)(TIM3->CCR ## ch)
#define SET_LED_PWM1(N) do{TIM1->CCR1 = (uint32_t)N;}while(0)
#define GET_LED_PWM1() (uint8_t)(TIM1->CCR1)
// USB pullup (not used in STM32F0x2!) - PA15
#define USBPU_port GPIOA
#define USBPU_pin (1<<15)
void iwdg_setup();
void hw_setup();
#endif // __HARDWARE_H__

View File

@@ -0,0 +1,194 @@
/*
* geany_encoding=koi8-r
* i2c.c
*
* Copyright 2017 Edward V. Emelianov <eddy@sao.ru, 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#include "hardware.h"
#include "i2c.h"
#include "proto.h"
#include "usb.h"
I2C_SPEED curI2Cspeed = LOW_SPEED;
extern volatile uint32_t Tms;
static uint32_t cntr;
volatile uint8_t I2C_scan_mode = 0; // == 1 when I2C is in scan mode
static uint8_t i2caddr = I2C_ADDREND; // not active
void i2c_setup(I2C_SPEED speed){
if(speed >= CURRENT_SPEED){
speed = curI2Cspeed;
}else{
curI2Cspeed = speed;
}
I2C1->CR1 = 0;
/*
* GPIO Resources: I2C1_SCL - PB6, I2C1_SDA - PB7 (AF1)
*/
GPIOB->AFR[0] = (GPIOB->AFR[0] & ~(GPIO_AFRL_AFRL6 | GPIO_AFRL_AFRL7)) |
1 << (6 * 4) | 1 << (7 * 4);
GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODER6 | GPIO_MODER_MODER7)) |
GPIO_MODER_MODER6_AF | GPIO_MODER_MODER7_AF;
GPIOB->OTYPER |= GPIO_OTYPER_OT_6 | GPIO_OTYPER_OT_7; // both open-drain outputs
// I2C
RCC->APB1ENR |= RCC_APB1ENR_I2C1EN; // timing
RCC->CFGR3 |= RCC_CFGR3_I2C1SW; // use sysclock for timing
if(speed == LOW_SPEED){ // 10kHz
// PRESC=B, SCLDEL=4, SDADEL=2, SCLH=0xC3, SCLL=0xB0
I2C1->TIMINGR = (0xB<<28) | (4<<20) | (2<<16) | (0xC3<<8) | (0xB0);
}else if(speed == HIGH_SPEED){ // 100kHz
I2C1->TIMINGR = (0xB<<28) | (4<<20) | (2<<16) | (0x12<<8) | (0x11);
}else{ // VERYLOW_SPEED - the lowest speed by STM register: 5.8kHz (presc = 16-1 = 15; )
I2C1->TIMINGR = (0xf<<28) | (4<<20) | (2<<16) | (0xff<<8) | (0xff);
}
I2C1->CR1 = I2C_CR1_PE;
}
/**
* write command byte to I2C
* @param addr - device address (TSYS01_ADDR0 or TSYS01_ADDR1)
* @param data - bytes to write
* @param nbytes - amount of bytes to write
* @param stop - to set STOP
* @return 0 if error
*/
static uint8_t write_i2cs(uint8_t addr, uint8_t *data, uint8_t nbytes, uint8_t stop){
cntr = Tms;
I2C1->CR1 = 0; // clear busy flag
I2C1->ICR = 0x3f38; // clear all errors
I2C1->CR1 = I2C_CR1_PE;
while(I2C1->ISR & I2C_ISR_BUSY){
IWDG->KR = IWDG_REFRESH;
if(Tms - cntr > I2C_TIMEOUT){
USND("Line busy\n");
return 0; // check busy
}}
cntr = Tms;
while(I2C1->CR2 & I2C_CR2_START){
IWDG->KR = IWDG_REFRESH;
if(Tms - cntr > I2C_TIMEOUT){
return 0; // check start
}}
//I2C1->ICR = 0x3f38; // clear all errors
I2C1->CR2 = nbytes << 16 | addr;
if(stop) I2C1->CR2 |= I2C_CR2_AUTOEND; // autoend
// now start transfer
I2C1->CR2 |= I2C_CR2_START;
for(int i = 0; i < nbytes; ++i){
cntr = Tms;
while(!(I2C1->ISR & I2C_ISR_TXIS)){ // ready to transmit
IWDG->KR = IWDG_REFRESH;
if(I2C1->ISR & I2C_ISR_NACKF){
I2C1->ICR |= I2C_ICR_NACKCF;
USND("NAK\n");
return 0;
}
if(Tms - cntr > I2C_TIMEOUT){
USND("Timeout\n");
return 0;
}
}
I2C1->TXDR = data[i]; // send data
}
// wait for data gone
while(I2C1->ISR & I2C_ISR_BUSY){
IWDG->KR = IWDG_REFRESH;
if(Tms - cntr > I2C_TIMEOUT){break;}
}
return 1;
}
uint8_t write_i2c(uint8_t addr, uint8_t *data, uint8_t nbytes){
return write_i2cs(addr, data, nbytes, 1);
}
/**
* read nbytes of data from I2C line
* `data` should be an array with at least `nbytes` length
* @return 1 if all OK, 0 if NACK or no device found
*/
static uint8_t read_i2cb(uint8_t addr, uint8_t *data, uint8_t nbytes, uint8_t busychk){
if(busychk){
cntr = Tms;
while(I2C1->ISR & I2C_ISR_BUSY){
IWDG->KR = IWDG_REFRESH;
if(Tms - cntr > I2C_TIMEOUT){
USND("Line busy\n");
return 0; // check busy
}}
}
cntr = Tms;
while(I2C1->CR2 & I2C_CR2_START){
IWDG->KR = IWDG_REFRESH;
if(Tms - cntr > I2C_TIMEOUT){
USND("No start\n");
return 0; // check start
}}
// read N bytes
I2C1->CR2 = (nbytes<<16) | addr | 1 | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN;
I2C1->CR2 |= I2C_CR2_START;
uint8_t i;
for(i = 0; i < nbytes; ++i){
cntr = Tms;
while(!(I2C1->ISR & I2C_ISR_RXNE)){ // wait for data
IWDG->KR = IWDG_REFRESH;
if(I2C1->ISR & I2C_ISR_NACKF){
I2C1->ICR |= I2C_ICR_NACKCF;
USND("NAK\n");
return 0;
}
if(Tms - cntr > I2C_TIMEOUT){
USND("Timeout\n");
return 0;
}
}
*data++ = I2C1->RXDR;
}
return 1;
}
uint8_t read_i2c(uint8_t addr, uint8_t *data, uint8_t nbytes){
return read_i2cb(addr, data, nbytes, 1);
}
// read register reg
uint8_t read_i2c_reg(uint8_t addr, uint8_t reg, uint8_t *data, uint8_t nbytes){
if(!write_i2cs(addr, &reg, 1, 0)) return 0;
return read_i2cb(addr, data, nbytes, 0);
}
void i2c_init_scan_mode(){
i2caddr = 0;
I2C_scan_mode = 1;
}
// return 1 if next addr is active & return in as `addr`
// if addresses are over, return 1 and set addr to I2C_NOADDR
// if scan mode inactive, return 0 and set addr to I2C_NOADDR
int i2c_scan_next_addr(uint8_t *addr){
*addr = i2caddr;
if(i2caddr == I2C_ADDREND){
*addr = I2C_ADDREND;
I2C_scan_mode = 0;
return 0;
}
if(!read_i2c_reg((i2caddr++)<<1, 0, NULL, 0)) return 0;
return 1;
}

View File

@@ -0,0 +1,47 @@
/*
* This file is part of the F0testbrd project.
* Copyright 2021 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
#ifndef I2C_H__
#define I2C_H__
#include "stm32f0.h"
#define I2C_ADDREND (0x80)
typedef enum{
VERYLOW_SPEED,
LOW_SPEED,
HIGH_SPEED,
CURRENT_SPEED
} I2C_SPEED;
extern I2C_SPEED curI2Cspeed;
extern volatile uint8_t I2C_scan_mode;
// timeout of I2C bus in ms
#define I2C_TIMEOUT (100)
void i2c_setup(I2C_SPEED speed);
uint8_t read_i2c(uint8_t addr, uint8_t *data, uint8_t nbytes);
uint8_t read_i2c_reg(uint8_t addr, uint8_t reg, uint8_t *data, uint8_t nbytes);
uint8_t write_i2c(uint8_t addr, uint8_t *data, uint8_t nbytes);
void i2c_init_scan_mode();
int i2c_scan_next_addr(uint8_t *addr);
#endif // I2C_H__

View File

@@ -0,0 +1,109 @@
/*
* main.c
*
* Copyright 2017 Edward V. Emelianoff <eddy@sao.ru, 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "adc.h"
#include "hardware.h"
#include "i2c.h"
#include "proto.h"
#include "spi.h"
#include "usart.h"
#include "usb.h"
#include "usb_lib.h"
// ADC value threshold for meaning it is new
#define ADCthreshold (20)
volatile uint32_t Tms = 0;
/* Called when systick fires */
void sys_tick_handler(void){
++Tms;
}
volatile uint8_t ADCmon = 0; // ==1 to monitor ADC (change PWM of LEDS & show current value)
uint16_t oldADCval = 0;
int main(void){
uint32_t lastT = 0;
sysreset();
SysTick_Config(6000, 1);
hw_setup();
RCC->CSR |= RCC_CSR_RMVF; // remove reset flags
USB_setup();
iwdg_setup();
while (1){
IWDG->KR = IWDG_REFRESH; // refresh watchdog
if(lastT > Tms || Tms - lastT > 499){
if(ADCmon){
uint16_t v = getADCval(0);
int32_t d = v - oldADCval;
if(d < -ADCthreshold || d > ADCthreshold){
oldADCval = v;
printADCvals();
v >>= 2; // 10 bits
TIM3->CCR1 = TIM3->CCR2 = TIM3->CCR3 = 0xff; TIM3->CCR4 = 0;
if(v >= 0x300) TIM3->CCR4 = v - 0x300;
else if(v >= 0x200) TIM3->CCR3 = v - 0x200;
else if(v >= 0x100){ TIM3->CCR2 = v - 0x100; TIM3->CCR3 = 0; }
else{ TIM3->CCR1 = v; TIM3->CCR2 = TIM3->CCR3 = 0; }
}
}
lastT = Tms;
transmit_tbuf(); // non-blocking transmission of data from UART buffer every 0.5s
}
if(I2C_scan_mode){
uint8_t addr;
int ok = i2c_scan_next_addr(&addr);
if(addr == I2C_ADDREND) USND("Scan ends\n");
else if(ok){
USB_sendstr(uhex2str(addr));
USND(" ("); USB_sendstr(u2str(addr));
USND(") - found device\n");
}
}
usb_proc();
char *txt;
if((txt = get_USB())){
const char *ans = parse_cmd(txt);
if(ans){
uint16_t l = 0; const char *p = ans;
while(*p++) l++;
USB_send((uint8_t*)ans, l);
if(ans[l-1] != '\n') USND("\n");
}
}
for(int n = 1; n <= USARTNUM; ++n){
if(usartrx(n)){ // usart1 received data, store in in buffer
int r = usart_getline(n, &txt);
if(r){
txt[r] = 0;
USND("Got string over USART"); USB_sendstr(u2str(n));
USND(":\n"); USB_sendstr(txt);
}
}
}
}
return 0;
}

Binary file not shown.

View File

@@ -0,0 +1,548 @@
/*
* This file is part of the F0testbrd project.
* Copyright 2021 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 "adc.h"
#include "i2c.h"
#include "proto.h"
#include "spi.h"
#include "usart.h"
#include "usb.h"
#include "usb_lib.h"
#define LOCBUFFSZ (32)
// local buffer for I2C and SPI data to send
static uint8_t locBuffer[LOCBUFFSZ];
void USB_sendstr(const char *str){
uint16_t l = 0;
const char *b = str;
while(*b++) ++l;
USB_send((const uint8_t*)str, l);
}
static inline char *chPWM(volatile uint32_t *reg, char *buf){
char *lbuf = buf;
lbuf = omit_spaces(lbuf);
char cmd = *lbuf;
lbuf = omit_spaces(lbuf + 1);
uint32_t N;
if(getnum(lbuf, &N) == lbuf) N = 1;
uint32_t oldval = *reg;
if(cmd == '-'){ // decrement
if(oldval < N) return "Already at minimum";
else *reg -= N;
}else if(cmd == '+'){ // increment
if(oldval + N > 255) return "Already at maximum";
else *reg += N;
}else{
USND("Wrong command: ");
return buf;
}
return "OK";
}
static inline char *TIM3pwm(char *buf){
uint8_t channel = *buf - '1';
if(channel > 3) return "Wrong channel number";
volatile uint32_t *reg = &TIM3->CCR1;
return chPWM(&reg[channel], buf+1);
}
static inline char *getPWMvals(){
USND("TIM1CH1: "); USB_sendstr(u2str(TIM1->CCR1));
USND("\nTIM3CH1: "); USB_sendstr(u2str(TIM3->CCR1));
USND("\nTIM3CH2: "); USB_sendstr(u2str(TIM3->CCR2));
USND("\nTIM3CH3: "); USB_sendstr(u2str(TIM3->CCR3));
USND("\nTIM3CH4: "); USB_sendstr(u2str(TIM3->CCR4));
USND("\n");
return NULL;
}
static inline char *USARTsend(char *buf){
uint32_t N;
if(buf == getnum(buf, &N)) return "Point number of USART";
if(N < 1 || N > USARTNUM) return "Wrong USART number";
buf = omit_spaces(buf + 1);
usart_send(N, buf);
transmit_tbuf();
return "OK";
}
// read N numbers from buf, @return 0 if wrong or none
static uint16_t readNnumbers(char *buf){
uint32_t D;
char *nxt;
uint16_t N = 0;
while((nxt = getnum(buf, &D)) && nxt != buf && N < LOCBUFFSZ){
buf = nxt;
locBuffer[N++] = (uint8_t) D&0xff;
USND("add byte: "); USB_sendstr(uhex2str(D&0xff)); USND("\n");
}
USND("Send "); USB_sendstr(u2str(N)); USND(" bytes\n");
return N;
}
// dump memory buffer
static void hexdump(uint8_t *arr, uint16_t len){
char buf[52], *bptr = buf;
for(uint16_t l = 0; l < len; ++l, ++arr){
for(int16_t j = 1; j > -1; --j){
register uint8_t half = (*arr >> (4*j)) & 0x0f;
if(half < 10) *bptr++ = half + '0';
else *bptr++ = half - 10 + 'a';
}
if(l % 16 == 15){
*bptr++ = '\n';
*bptr = 0;
USB_sendstr(buf);
bptr = buf;
}else *bptr++ = ' ';
}
if(bptr != buf){
*bptr++ = '\n';
*bptr = 0;
USB_sendstr(buf);
}
}
static uint8_t i2cinited = 0;
static inline char *setupI2C(char *buf){
buf = omit_spaces(buf);
if(*buf < '0' || *buf > '2') return "Wrong speed";
i2c_setup(*buf - '0');
i2cinited = 1;
return "OK";
}
static uint8_t I2Caddress = 0;
static inline char *saI2C(char *buf){
uint32_t addr;
if(!getnum(buf, &addr) || addr > 0x7f) return "Wrong address";
I2Caddress = (uint8_t) addr << 1;
USND("I2Caddr="); USB_sendstr(uhex2str(addr)); USND("\n");
return "OK";
}
static inline void rdI2C(char *buf){
uint32_t N;
char *nxt = getnum(buf, &N);
if(!nxt || buf == nxt || N > 0xff){
USND("Bad register number\n");
return;
}
buf = nxt;
uint8_t reg = N;
nxt = getnum(buf, &N);
if(!nxt || buf == nxt || N > LOCBUFFSZ){
USND("Bad length\n");
return;
}
if(!read_i2c_reg(I2Caddress, reg, locBuffer, N)){
USND("Error reading I2C\n");
return;
}
if(N == 0){ USND("OK"); return; }
USND("Register "); USB_sendstr(uhex2str(reg)); USND(":\n");
hexdump(locBuffer, N);
/*for(uint32_t i = 0; i < N; ++i){
if(i < 10) USND(" ");
USB_sendstr(u2str(i)); USND(": "); USB_sendstr(uhex2str(locBuffer[i]));
USND("\n");
}*/
}
static inline char *wrI2C(char *buf){
uint16_t N = readNnumbers(buf);
if(!write_i2c(I2Caddress, locBuffer, N)) return "Error writing I2C";
return "OK";
}
static inline char *DAC_chval(char *buf){
uint32_t D;
char *nxt = getnum(buf, &D);
if(!nxt || nxt == buf || D > 4095) return "Wrong DAC amplitude\n";
DAC->DHR12R1 = D;
return "OK";
}
// write locBuffer to SPI
static inline void wrSPI(int SPIidx, char *buf){
uint16_t N = readNnumbers(buf);
if(N < 1){
*(uint8_t *)&(SPI1->DR) = 0xea;
USND("Enter at least 1 number (max: ");
USB_sendstr(u2str(LOCBUFFSZ)); USND(")\n");
return;
}
if(SPI_transmit(SPIidx, locBuffer, N)) USND("Error: busy?\n");
else USND("done");
}
static inline void rdSPI(int SPIidx){
if(SPI_isoverflow(SPIidx)) USND("SPI buffer overflow\n");
uint8_t len = LOCBUFFSZ;
if(SPI_getdata(SPIidx, locBuffer, &len)){
USND("Error getting data: busy?\n");
return;
}
if(len == 0){
USND("Nothing to read\n");
return;
}
if(len > LOCBUFFSZ) USND("Can't get full message: buffer too small\n");
USND("SPI data:\n");
hexdump(locBuffer, len);
}
static inline char *procSPI(char *buf){
int idx = 0;
if(*buf == 'p') idx = 1;
buf = omit_spaces(buf + 1);
if(*buf == 'w') wrSPI(idx, buf + 1);
else if(*buf == 'r') rdSPI(idx);
else return "Enter `w` and data to write, `r` - to read";
return NULL;
}
const char *helpstring =
"+/-[num] - increase/decrease TIM1ch1 PWM by 1 or `num`\n"
"1..4'+'/'-'[num] - increase/decrease TIM3chN PWM by 1 or `num`\n"
"A - get ADC values\n"
"dx - change DAC lowcal to x\n"
"g - get PWM values\n"
"i0..3 - setup I2C with lowest..highest speed (5.8, 10 and 100kHz)\n"
"Ia addr - set I2C address\n"
"Iw bytes - send bytes (hex/dec/oct/bin) to I2C\n"
"Ir reg n - read n bytes from I2C reg\n"
"Is - scan I2C bus\n"
"L - send long string over USB\n"
"m - monitor ADC on/off\n"
"Pw bytes - send bytes over SPI1\n"
"pw bytes - send bytes over SPI2\n"
"Pr - get data from SPI1\n"
"pr - get data from SPI2\n"
"R - software reset\n"
"S - send short string over USB\n"
"s - setup SPI (and turn off USARTs)\n"
"Ux str - send string to USARTx (1..3)\n"
"u - setup USARTs (and turn off SPI)\n"
"T - MCU temperature\n"
"V - Vdd\n"
"W - test watchdog\n"
;
void printADCvals(){
USND("AIN0: "); USB_sendstr(u2str(getADCval(0)));
USND(" ("); USB_sendstr(u2str(getADCvoltage(0)));
USND("/100 V)\nAIN1: "); USB_sendstr(u2str(getADCval(1)));
USND(" ("); USB_sendstr(u2str(getADCvoltage(1)));
USND("/100 V)\nAIN5: "); USB_sendstr(u2str(getADCval(2)));
USND(" ("); USB_sendstr(u2str(getADCvoltage(2)));
USND("/100 V)\n");
}
const char *parse_cmd(char *buf){
// "long" commands
switch(*buf){
case '+':
case '-':
return chPWM(&TIM1->CCR1, buf);
break;
case '1':
case '2':
case '3':
case '4':
return TIM3pwm(buf);
break;
case 'd':
return DAC_chval(buf + 1);
case 'i':
return setupI2C(buf + 1);
break;
case 'I':
if(!i2cinited) return "Init I2C first";
buf = omit_spaces(buf + 1);
if(*buf == 'a') return saI2C(buf + 1);
else if(*buf == 'r'){ rdI2C(buf + 1); return NULL; }
else if(*buf == 'w') return wrI2C(buf + 1);
else if(*buf == 's') i2c_init_scan_mode();
else return "Command should be 'Ia', 'Iw', 'Ir' or 'Is'\n";
break;
case 'p':
case 'P':
return procSPI(buf);
break;
case 'U':
return USARTsend(buf + 1);
break;
}
// "short" commands
if(buf[1] != '\n') return buf;
switch(*buf){
case 'g':
return getPWMvals();
break;
case 'A':
printADCvals();
break;
case 'L':
USND("Very long test string for USB (it's length is more than 64 bytes).\n"
"This is another part of the string! Can you see all of this?\n");
return "Long test sent";
break;
case 'm':
ADCmon = !ADCmon;
USND("Monitoring is ");
if(ADCmon) USND("on\n");
else USND("off\n");
break;
case 'R':
USND("Soft reset\n");
//SEND("Soft reset\n");
NVIC_SystemReset();
break;
case 'S':
USND("Test string for USB\n");
return "Short test sent";
break;
case 's':
USND("SPI are ON, USART are OFF\n");
usart_stop();
spi_setup();
break;
case 'T':
return u2str(getMCUtemp());
break;
case 'u':
USND("USART are ON, SPI are OFF\n");
spi_stop();
usart_setup();
break;
case 'V':
return u2str(getVdd());
break;
case 'W':
USND("Wait for reboot\n");
//SEND("Wait for reboot\n");
while(1){nop();};
break;
default: // help
return helpstring;
break;
}
return NULL;
}
// usb getline
char *get_USB(){
static char tmpbuf[129], *curptr = tmpbuf;
static int rest = 128;
int x = USB_receive((uint8_t*)curptr);
curptr[x] = 0;
if(!x) return NULL;
if(curptr[x-1] == '\n'){
curptr = tmpbuf;
rest = 128;
return tmpbuf;
}
curptr += x; rest -= x;
if(rest <= 0){ // buffer overflow
curptr = tmpbuf;
rest = 128;
}
return NULL;
}
static char *_2str(uint32_t val, uint8_t minus){
static char strbuf[12];
char *bufptr = &strbuf[11];
*bufptr = 0;
if(!val){
*(--bufptr) = '0';
}else{
while(val){
*(--bufptr) = val % 10 + '0';
val /= 10;
}
}
if(minus) *(--bufptr) = '-';
return bufptr;
}
// return string with number `val`
char *u2str(uint32_t val){
return _2str(val, 0);
}
char *i2str(int32_t i){
uint8_t minus = 0;
uint32_t val;
if(i < 0){
minus = 1;
val = -i;
}else val = i;
return _2str(val, minus);
}
// print 32bit unsigned int as hex
char *uhex2str(uint32_t val){
static char buf[12] = "0x";
int npos = 2;
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) buf[npos++] = half + '0';
else buf[npos++] = half - 10 + 'a';
}
}
buf[npos] = 0;
return buf;
}
char *omit_spaces(const char *buf){
while(*buf){
if(*buf > ' ') break;
++buf;
}
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 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;
}
// 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;
}

View File

@@ -0,0 +1,40 @@
/*
* This file is part of the F0testbrd project.
* Copyright 2021 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
#ifndef PROTO_H__
#define PROTO_H__
#include "stm32f0.h"
#define USND(str) do{USB_send((uint8_t*)str, sizeof(str)-1);}while(0)
extern volatile uint8_t ADCmon;
void USB_sendstr(const char *str);
char *get_USB();
const char *parse_cmd(char *buf);
void printADCvals();
char *u2str(uint32_t val);
char *i2str(int32_t i);
char *uhex2str(uint32_t val);
char *getnum(const char *txt, uint32_t *N);
char *omit_spaces(const char *buf);
#endif // PROTO_H__

View File

@@ -0,0 +1,178 @@
/*
* This file is part of the F0testbrd project.
* Copyright 2021 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"
#include "proto.h"
#include "spi.h"
#include "usb.h"
#include <string.h> // memcpy
// buffers for DMA rx/tx
static uint8_t inbuff[SPInumber][SPIBUFSZ], outbuf[SPInumber][SPIBUFSZ];
volatile uint8_t SPIoverfl[SPInumber] = {0, 0};
spiStatus SPI_status[SPInumber] = {SPI_NOTREADY, SPI_NOTREADY};
static DMA_Channel_TypeDef * const rxDMA[SPInumber] = {DMA1_Channel2, DMA1_Channel4};
static DMA_Channel_TypeDef * const txDMA[SPInumber] = {DMA1_Channel3, DMA1_Channel5};
static const uint32_t txDMAirqn[SPInumber] = {DMA1_Channel2_3_IRQn, DMA1_Channel4_5_6_7_IRQn};
static SPI_TypeDef * const SPI[SPInumber] = {SPI1, SPI2};
// setup SPI by data from arrays above,
// @param SPIidx - index in arrays
// @param master - == 0 for slave
static void spicommonsetup(uint8_t SPIidx, uint8_t master){
if(SPIidx >= SPInumber) return;
// Configure DMA SPI
/* SPI_RX DMA config */
/* (1) Peripheral address */
/* (2) Memory address */
/* (3) Data size */
/* (4) Memory increment */
/* Peripheral to memory */
/* 8-bit transfer */
/* Overflow IR */
rxDMA[SPIidx]->CCR &= ~DMA_CCR_EN;
rxDMA[SPIidx]->CPAR = (uint32_t)&(SPI[SPIidx]->DR); /* (1) */
rxDMA[SPIidx]->CMAR = (uint32_t)inbuff[SPIidx]; /* (2) */
rxDMA[SPIidx]->CNDTR = SPIBUFSZ; /* (3) */
rxDMA[SPIidx]->CCR |= DMA_CCR_MINC | DMA_CCR_TEIE | DMA_CCR_EN; /* (4) */
/* SPI_TX DMA config */
/* (5) Peripheral address */
/* (6) Memory address */
/* (7) Memory increment */
/* Memory to peripheral*/
/* 8-bit transfer */
/* Transfer complete IT */
txDMA[SPIidx]->CCR &= ~DMA_CCR_EN;
txDMA[SPIidx]->CPAR = (uint32_t)&(SPI[SPIidx]->DR); /* (5) */
txDMA[SPIidx]->CMAR = (uint32_t)outbuf[SPIidx]; /* (6) */
txDMA[SPIidx]->CCR |= DMA_CCR_MINC | DMA_CCR_TCIE | DMA_CCR_DIR; /* (7) */
/* Configure IT */
/* (8) Set priority */
/* (9) Enable DMA */
NVIC_SetPriority(txDMAirqn[SPIidx], 0);
NVIC_EnableIRQ(txDMAirqn[SPIidx]);
/* Configure SPI */
/* (1) Master selection, BR: Fpclk/256 CPOL and CPHA at zero (rising first edge) */
/* (1a) software slave management (SSI inactive) */
/* (2) TX and RX with DMA, 8-bit Rx fifo */
/* (3) Enable SPI */
if(master) SPI[SPIidx]->CR1 = SPI_CR1_MSTR | SPI_CR1_BR | SPI_CR1_SSM | SPI_CR1_SSI; /* (1) */
else SPI[SPIidx]->CR1 = SPI_CR1_SSM; // (1a)
SPI[SPIidx]->CR2 = SPI_CR2_TXDMAEN | SPI_CR2_RXDMAEN | SPI_CR2_FRXTH | SPI_CR2_DS_2 | SPI_CR2_DS_1 | SPI_CR2_DS_0; /* (2) */
SPI[SPIidx]->CR1 |= SPI_CR1_SPE; /* (3) */
SPI_status[SPIidx] = SPI_READY;
SPI_prep_receive(SPIidx);
}
// SPI1 (AF0): PB3 - SCK, PB4 - MISO, PB5 - MOSI; RxDMA - ch2, TxDMA - ch3
// SPI2 (AF0): PB13 - SCK, PB14 - MISO, PB15 - MOSI; RxDMA - ch4, TxDMA - ch5
void spi_setup(){
// RCC->AHBENR |= RCC_AHBENR_GPIOBEN; // uncomment in common case
/* (1) Select AF mode on pins */
/* (2) AF0 for SPI1 signals */
GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODER3 | GPIO_MODER_MODER4 | GPIO_MODER_MODER5|
GPIO_MODER_MODER13 | GPIO_MODER_MODER14 | GPIO_MODER_MODER15)) |
GPIO_MODER_MODER3_AF | GPIO_MODER_MODER4_AF | GPIO_MODER_MODER5_AF |
GPIO_MODER_MODER13_AF | GPIO_MODER_MODER14_AF | GPIO_MODER_MODER15_AF; /* (1) */
GPIOB->AFR[0] = (GPIOB->AFR[0] & ~(GPIO_AFRL_AFRL3 | GPIO_AFRL_AFRL4 | GPIO_AFRL_AFRL5)); /* (2) */
GPIOB->AFR[1] = (GPIOB->AFR[1] & ~(GPIO_AFRH_AFRH5 | GPIO_AFRH_AFRH6 | GPIO_AFRH_AFRH7)); /* (2) */
// enable clocking
RCC->AHBENR |= RCC_AHBENR_DMA1EN;
RCC->APB1ENR |= RCC_APB1ENR_SPI2EN;
RCC->APB2ENR |= RCC_APB2ENR_SPI1EN;
// SPI1 - master, SPI2 - slave
spicommonsetup(0, 1);
spicommonsetup(1, 0);
}
void spi_stop(){
RCC->APB1ENR &= ~RCC_APB1ENR_SPI2EN;
RCC->APB2ENR &= ~RCC_APB2ENR_SPI1EN;
}
/**
* @brief SPI_transmit - transmit data over SPI DMA
* @param N - SPI number (0 - SPI1, 1 - SPI2)
* @param buf - data to transmit
* @param len - its length
* @return 0 if all OK
*/
uint8_t SPI_transmit(uint8_t N, const uint8_t *buf, uint8_t len){
if(!buf || !len || len > SPIBUFSZ || N >= SPInumber) return 1; // bad data format
if(SPI_status[N] != SPI_READY) return 2; // spi not ready to transmit data
int ctr = 0;
while(SPI[N]->SR & SPI_SR_FTLVL && ++ctr < 99999); // wait for transmission buffer empty
ctr = 0;
while(SPI[N]->SR & SPI_SR_BSY && ++ctr < 99999); // wait while busy
USND("SPI->SR="); USB_sendstr(uhex2str(SPI[N]->SR)); USND("\n");
txDMA[N]->CCR &=~ DMA_CCR_EN;
memcpy(outbuf[N], buf, len);
txDMA[N]->CNDTR = len;
//txDMA[N]->CMAR = (uint32_t)outbuf[N];
SPI_prep_receive(N);
SPI_status[N] = SPI_BUSY;
txDMA[N]->CCR |= DMA_CCR_EN;
return 0;
}
// prepare channel N to receive data, return 0 if all OK
uint8_t SPI_prep_receive(uint8_t N){
if(N >= SPInumber) return 1;
if(SPI_status[N] != SPI_READY) return 2; // still transmitting data
SPIoverfl[N] = 0;
rxDMA[N]->CCR &= ~DMA_CCR_EN;
(void)SPI[N]->DR; // read DR and SR to clear OVR flag
(void)SPI[N]->SR;
rxDMA[N]->CNDTR = SPIBUFSZ;
//rxDMA[N]->CMAR = (uint32_t)inbuff[N];
rxDMA[N]->CCR |= DMA_CCR_EN;
return 0;
}
/**
* @brief SPI_getdata - get data received by DMA & reload receiver
* @param N - number of channel (0/1)
* @param buf - buffer for data (with length maxlen) or NULL
* @param maxlen - (I) - amount of received bytes (or 0 if buffer is empty),
* (O) - amount of real bytes amount in buffer (could be > maxlen if maxlen < SPIBUFSZ)
* @return 0 if all OK or error code
*/
uint8_t SPI_getdata(uint8_t N, uint8_t *buf, uint8_t *maxlen){
if(N >= SPInumber) return 1;
if(SPI_status[N] != SPI_READY) return 2; // still transmitting data
rxDMA[N]->CCR &= ~DMA_CCR_EN;
SPIoverfl[N] = 0;
uint8_t remain = rxDMA[N]->CNDTR;
if(maxlen){
if(buf && *maxlen) memcpy(buf, inbuff[N], *maxlen);
*maxlen = SPIBUFSZ - remain; // bytes received
}
rxDMA[N]->CNDTR = SPIBUFSZ;
rxDMA[N]->CCR |= DMA_CCR_EN;
return 0;
}
// return 1 if given channel overflowed & clear overflow flag
// should be called BEFORE SPI_prep_receive() or SPI_getdata()
uint8_t SPI_isoverflow(uint8_t N){
if(N >= SPInumber) return 1;
register uint8_t o = SPIoverfl[N];
SPIoverfl[N] = 0;
return o;
}

View File

@@ -0,0 +1,45 @@
/*
* This file is part of the F0testbrd project.
* Copyright 2021 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
#ifndef SPI_H__
#define SPI_H__
#include "stm32f0.h"
#define SPInumber (2)
#define SPIBUFSZ (8)
typedef enum{
SPI_NOTREADY,
SPI_READY,
SPI_BUSY
} spiStatus;
extern spiStatus SPI_status[];
extern volatile uint8_t SPIoverfl[];
void spi_setup();
void spi_stop();
uint8_t SPI_transmit(uint8_t N, const uint8_t *buf, uint8_t len);
uint8_t SPI_prep_receive(uint8_t N);
uint8_t SPI_getdata(uint8_t N, uint8_t *buf, uint8_t *maxlen);
uint8_t SPI_isoverflow(uint8_t N);
#endif // SPI_H__

View File

@@ -0,0 +1,239 @@
/*
* usart.c
*
* Copyright 2017 Edward V. Emelianoff <eddy@sao.ru, 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "stm32f0.h"
#include "hardware.h"
#include "proto.h"
#include "usart.h"
#include "usb.h"
#include <string.h>
extern volatile uint32_t Tms;
// USART tx DMA 1: DMA1_Channel2, 2: DMA1_Channel4, 3: DMA1_Channel7
static DMA_Channel_TypeDef *USARTDMA[USARTNUM] = {
DMA1_Channel2, DMA1_Channel4
#ifdef USART3
,DMA1_Channel7
#endif
};
static USART_TypeDef *USARTs[USARTNUM] = {
USART1, USART2
#ifdef USART3
,USART3
#endif
};
static volatile int idatalen[USARTNUM][2] = {0}; // received data line length (including '\n')
static volatile int odatalen[USARTNUM][2] = {0};
volatile int linerdy[USARTNUM] = {0}, // received data ready
dlen[USARTNUM] = {0}, // length of data (including '\n') in current buffer
bufovr[USARTNUM] = {0}, // input buffer overfull
txrdy[USARTNUM] = {1,1 // transmission done
#ifdef USART3
,1
#endif
}
;
int rbufno[USARTNUM] = {0}, tbufno[USARTNUM] = {0}; // current rbuf/tbuf numbers
static char rbuf[USARTNUM][2][UARTBUFSZI], tbuf[USARTNUM][2][UARTBUFSZO]; // receive & transmit buffers
static char *recvdata[USARTNUM] = {0};
/**
* return length of received data (without trailing zero
* usartno: 1, 2 or 3
*/
int usart_getline(int usartno, char **line){
--usartno;
if(bufovr[usartno]){
bufovr[usartno] = 0;
linerdy[usartno] = 0;
return 0;
}
*line = recvdata[usartno];
linerdy[usartno] = 0;
return dlen[usartno];
}
// transmit current tbuf for all USARTs and swap buffers
void transmit_tbuf(){
for(int usartno = 0; usartno < USARTNUM; ++usartno){
uint32_t p = 1000000;
while(!txrdy[usartno] && --p);
if(!txrdy[usartno]) continue;
register int l = odatalen[usartno][tbufno[usartno]];
if(!l) continue;
txrdy[usartno] = 0;
odatalen[usartno][tbufno[usartno]] = 0;
USARTDMA[usartno]->CCR &= ~DMA_CCR_EN;
USARTDMA[usartno]->CMAR = (uint32_t) tbuf[usartno][tbufno[usartno]]; // mem
USARTDMA[usartno]->CNDTR = l;
USARTDMA[usartno]->CCR |= DMA_CCR_EN;
tbufno[usartno] = !tbufno[usartno];
}
}
void usart_putchar(int usartno, const char ch){
--usartno;
if(odatalen[usartno][tbufno[usartno]] == UARTBUFSZO) transmit_tbuf();
tbuf[usartno][tbufno[usartno]][odatalen[usartno][tbufno[usartno]]++] = ch;
}
void usart_send(int usartno, const char *str){
--usartno;
while(*str){
if(odatalen[usartno][tbufno[usartno]] == UARTBUFSZO) transmit_tbuf();
tbuf[usartno][tbufno[usartno]][odatalen[usartno][tbufno[usartno]]++] = *str++;
}
}
void usart_sendn(int usartno, const char *str, uint32_t L){
--usartno;
for(uint32_t i = 0; i < L; ++i){
if(odatalen[usartno][tbufno[usartno]] == UARTBUFSZO) transmit_tbuf();
tbuf[usartno][tbufno[usartno]][odatalen[usartno][tbufno[usartno]]++] = *str++;
}
}
void newline(int usartno){
usart_putchar(usartno, '\n');
transmit_tbuf();
}
void usart_setup(){
// USART1: Rx - PA10, Tx - PA9 (AF1)
// USART2: Rx - PA3, Tx - PA2 (AF1)
// USART3: Rx - PB11, Tx - PB10 (AF4)
// setup pins:
GPIOA->MODER = (GPIOA->MODER & ~(GPIO_MODER_MODER2|GPIO_MODER_MODER3|GPIO_MODER_MODER9 | GPIO_MODER_MODER10)) |
GPIO_MODER_MODER2_AF | GPIO_MODER_MODER3_AF | GPIO_MODER_MODER9_AF | GPIO_MODER_MODER10_AF;
GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(GPIO_AFRL_AFRL2 | GPIO_AFRL_AFRL3)) |
1 << (2 * 4) | 1 << (3 * 4); // PA2,3
GPIOA->AFR[1] = (GPIOA->AFR[1] & ~(GPIO_AFRH_AFRH1 | GPIO_AFRH_AFRH2)) |
1 << (1 * 4) | 1 << (2 * 4); // PA9, PA10
// clock
RCC->APB2ENR |= RCC_APB2ENR_USART1EN;
RCC->APB1ENR |= RCC_APB1ENR_USART2EN;
RCC->AHBENR |= RCC_AHBENR_DMA1EN;
#ifdef USART3
GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODER10 | GPIO_MODER_MODER11)) |
GPIO_MODER_MODER10_AF | GPIO_MODER_MODER11_AF;
GPIOB->AFR[1] = (GPIOB->AFR[1] & ~(GPIO_AFRH_AFRH2 | GPIO_AFRH_AFRH3)) |
4 << (2 * 4) | 4 << (3 * 4); // PB10, PB11
RCC->APB1ENR |= RCC_APB1ENR_USART3EN;
#endif
for(int i = 0; i < USARTNUM; ++i){
USARTs[i]->ICR = 0xffffffff; // clear all flags
// USARTX Tx DMA
USARTDMA[i]->CCR &= ~DMA_CCR_EN;
USARTDMA[i]->CPAR = (uint32_t) &USARTs[i]->TDR; // periph
USARTDMA[i]->CCR |= DMA_CCR_MINC | DMA_CCR_DIR | DMA_CCR_TCIE; // 8bit, mem++, mem->per, transcompl irq
// setup usarts
USARTs[i]->BRR = 480000 / 1152;
USARTs[i]->CR3 = USART_CR3_DMAT; // enable DMA Tx
USARTs[i]->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_UE | USART_CR1_RXNEIE; // 1start,8data,nstop; enable Rx,Tx,USART
uint32_t tmout = 16000000;
while(!(USARTs[i]->ISR & USART_ISR_TC)){if(--tmout == 0) break;} // polling idle frame Transmission
USARTs[i]->ICR = 0xffffffff; // clear all flags again
}
NVIC_SetPriority(DMA1_Channel2_3_IRQn, 3);
NVIC_EnableIRQ(DMA1_Channel2_3_IRQn);
NVIC_SetPriority(USART1_IRQn, 0);
NVIC_EnableIRQ(USART1_IRQn);
NVIC_SetPriority(DMA1_Channel4_5_6_7_IRQn, 3);
NVIC_EnableIRQ(DMA1_Channel4_5_6_7_IRQn);
NVIC_SetPriority(USART2_IRQn, 0);
NVIC_EnableIRQ(USART2_IRQn);
#ifdef USART3
NVIC_SetPriority(USART3_4_IRQn, 0);
NVIC_EnableIRQ(USART3_4_IRQn);
#endif
}
void usart_stop(){
RCC->APB2ENR &= ~RCC_APB2ENR_USART1EN;
RCC->APB1ENR &= ~RCC_APB1ENR_USART2EN;
#ifdef USART3
RCC->APB1ENR &= ~RCC_APB1ENR_USART3EN;
#endif
}
static void usart_IRQ(int usartno){
USART_TypeDef *USARTX = USARTs[usartno];
//USND("USART"); USB_sendstr(u2str(usartno+1)); USND(" IRQ, ISR=");
//USB_sendstr(uhex2str(USARTX->ISR)); USND("\n");
#ifdef CHECK_TMOUT
static uint32_t tmout[USARTNUM] = {0};
#endif
if(USARTX->ISR & USART_ISR_RXNE){ // RX not emty - receive next char
#ifdef CHECK_TMOUT
if(tmout[usartno] && Tms >= tmout[usartno]){ // set overflow flag
bufovr[usartno] = 1;
idatalen[usartno][rbufno[usartno]] = 0;
}
tmout[usartno] = Tms + TIMEOUT_MS;
if(!tmout[usartno]) tmout[usartno] = 1; // prevent 0
#endif
// read RDR clears flag
uint8_t rb = USARTX->RDR;
//USND("RB="); USB_sendstr(uhex2str(rb)); USND("\n");
if(idatalen[usartno][rbufno[usartno]] < UARTBUFSZI){ // put next char into buf
rbuf[usartno][rbufno[usartno]][idatalen[usartno][rbufno[usartno]]++] = rb;
if(rb == '\n'){ // got newline - line ready
//USND("Newline\n");
linerdy[usartno] = 1;
dlen[usartno] = idatalen[usartno][rbufno[usartno]];
recvdata[usartno] = rbuf[usartno][rbufno[usartno]];
// prepare other buffer
rbufno[usartno] = !rbufno[usartno];
idatalen[usartno][rbufno[usartno]] = 0;
#ifdef CHECK_TMOUT
// clear timeout at line end
tmout[usartno] = 0;
#endif
}
}else{ // buffer overrun
bufovr[usartno] = 1;
idatalen[usartno][rbufno[usartno]] = 0;
#ifdef CHECK_TMOUT
tmout[usartno] = 0;
#endif
}
}
}
void usart1_isr(){
usart_IRQ(0);
}
void usart2_isr(){
usart_IRQ(1);
}
// work with USART3 only @ boards that have it
#ifdef USART3
void usart3_4_isr(){
usart_IRQ(2);
}
#endif

View File

@@ -0,0 +1,59 @@
/*
* usart.h
*
* Copyright 2017 Edward V. Emelianoff <eddy@sao.ru, 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#pragma once
#ifndef __USART_H__
#define __USART_H__
#include "hardware.h"
#ifdef USART3
#define USARTNUM (3)
#else
#define USARTNUM (2)
#endif
// input and output buffers size
#define UARTBUFSZI (32)
#define UARTBUFSZO (512)
// timeout between data bytes
#ifndef TIMEOUT_MS
#define TIMEOUT_MS (1500)
#endif
// macro for static strings
#define SEND(n, str) usart_send(n, str)
#define usartrx(n) (linerdy[n-1])
#define usartovr(n) (bufovr[n-1])
extern volatile int linerdy[], bufovr[], txrdy[];
void transmit_tbuf();
void usart_setup();
int usart_getline(int usartno, char **line);
void usart_send(int usartno, const char *str);
void usart_sendn(int usartno, const char *str, uint32_t L);
void newline(int usartno);
void usart_putchar(int usartno, const char ch);
void usart_stop();
#endif // __USART_H__

View File

@@ -0,0 +1,170 @@
/*
* geany_encoding=koi8-r
* usb.c - base functions for different USB types
*
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#include "usb.h"
#include "usb_lib.h"
static volatile uint8_t tx_succesfull = 1;
static volatile uint8_t rxNE = 0;
// interrupt IN handler (never used?)
static void EP1_Handler(){
uint16_t epstatus = KEEP_DTOG(USB->EPnR[1]);
if(RX_FLAG(epstatus)) epstatus = (epstatus & ~USB_EPnR_STAT_TX) ^ USB_EPnR_STAT_RX; // set valid RX
else epstatus = epstatus & ~(USB_EPnR_STAT_TX|USB_EPnR_STAT_RX);
// clear CTR
epstatus = (epstatus & ~(USB_EPnR_CTR_RX|USB_EPnR_CTR_TX));
USB->EPnR[1] = epstatus;
}
// data IN/OUT handlers
static void transmit_Handler(){ // EP3IN
tx_succesfull = 1;
uint16_t epstatus = KEEP_DTOG_STAT(USB->EPnR[3]);
// clear CTR keep DTOGs & STATs
USB->EPnR[3] = (epstatus & ~(USB_EPnR_CTR_TX)); // clear TX ctr
}
static void receive_Handler(){ // EP2OUT
rxNE = 1;
uint16_t epstatus = KEEP_DTOG_STAT(USB->EPnR[2]);
USB->EPnR[2] = (epstatus & ~(USB_EPnR_CTR_RX)); // clear RX ctr
}
void USB_setup(){
RCC->APB1ENR |= RCC_APB1ENR_CRSEN | RCC_APB1ENR_USBEN; // enable CRS (hsi48 sync) & USB
RCC->CFGR3 &= ~RCC_CFGR3_USBSW; // reset USB
RCC->CR2 |= RCC_CR2_HSI48ON; // turn ON HSI48
uint32_t tmout = 16000000;
while(!(RCC->CR2 & RCC_CR2_HSI48RDY)){if(--tmout == 0) break;}
FLASH->ACR = FLASH_ACR_PRFTBE | FLASH_ACR_LATENCY;
CRS->CFGR &= ~CRS_CFGR_SYNCSRC;
CRS->CFGR |= CRS_CFGR_SYNCSRC_1; // USB SOF selected as sync source
CRS->CR |= CRS_CR_AUTOTRIMEN; // enable auto trim
CRS->CR |= CRS_CR_CEN; // enable freq counter & block CRS->CFGR as read-only
RCC->CFGR |= RCC_CFGR_SW;
// allow RESET and CTRM interrupts
USB->CNTR = USB_CNTR_RESETM | USB_CNTR_CTRM;
// clear flags
USB->ISTR = 0;
// and activate pullup
USB->BCDR |= USB_BCDR_DPPU;
NVIC_EnableIRQ(USB_IRQn);
}
static int usbwr(const uint8_t *buf, uint16_t l){
uint32_t ctra = 1000000;
while(--ctra && tx_succesfull == 0){
IWDG->KR = IWDG_REFRESH;
}
tx_succesfull = 0;
EP_Write(3, buf, l);
ctra = 1000000;
while(--ctra && tx_succesfull == 0){
IWDG->KR = IWDG_REFRESH;
}
if(tx_succesfull == 0){usbON = 0; return 1;} // usb is OFF?
return 0;
}
static uint8_t usbbuff[USB_TXBUFSZ-1]; // temporary buffer (63 - to prevent need of ZLP)
static uint8_t buflen = 0; // amount of symbols in usbbuff
// send next up to 63 bytes of data in usbbuff
static void send_next(){
if(!buflen || !tx_succesfull) return;
tx_succesfull = 0;
EP_Write(3, usbbuff, buflen);
buflen = 0;
}
// unblocking sending - just fill a buffer
void USB_send(const uint8_t *buf, uint16_t len){
if(!usbON || !len) return;
if(len > USB_TXBUFSZ-1 - buflen){
usbwr(usbbuff, buflen);
buflen = 0;
}
if(len > USB_TXBUFSZ-1){
USB_send_blk(buf, len);
return;
}
while(len--) usbbuff[buflen++] = *buf++;
}
// blocking sending
void USB_send_blk(const uint8_t *buf, uint16_t len){
if(!usbON || !len) return; // USB disconnected
if(buflen){
usbwr(usbbuff, buflen);
buflen = 0;
}
int needzlp = 0;
while(len){
if(len == USB_TXBUFSZ) needzlp = 1;
uint16_t s = (len > USB_TXBUFSZ) ? USB_TXBUFSZ : len;
if(usbwr(buf, s)) return;
len -= s;
buf += s;
}
if(needzlp){
usbwr(NULL, 0);
}
}
void usb_proc(){
switch(USB_Dev.USB_Status){
case USB_STATE_CONFIGURED:
// make new BULK endpoint
// Buffer have 1024 bytes, but last 256 we use for CAN bus (30.2 of RM: USB main features)
EP_Init(1, EP_TYPE_INTERRUPT, USB_EP1BUFSZ, 0, EP1_Handler); // IN1 - transmit
EP_Init(2, EP_TYPE_BULK, 0, USB_RXBUFSZ, receive_Handler); // OUT2 - receive data
EP_Init(3, EP_TYPE_BULK, USB_TXBUFSZ, 0, transmit_Handler); // IN3 - transmit data
USB_Dev.USB_Status = USB_STATE_CONNECTED;
break;
case USB_STATE_DEFAULT:
case USB_STATE_ADDRESSED:
if(usbON){
usbON = 0;
}
break;
default: // USB_STATE_CONNECTED - send next data portion
if(!usbON) return;
send_next();
}
}
/**
* @brief USB_receive
* @param buf (i) - buffer[64] for received data
* @return amount of received bytes
*/
uint8_t USB_receive(uint8_t *buf){
if(!usbON || !rxNE) return 0;
uint8_t sz = EP_Read(2, buf);
uint16_t epstatus = KEEP_DTOG(USB->EPnR[2]);
// keep stat_tx & set ACK rx
USB->EPnR[2] = (epstatus & ~(USB_EPnR_STAT_TX)) ^ USB_EPnR_STAT_RX;
rxNE = 0;
return sz;
}

View File

@@ -0,0 +1,37 @@
/*
* geany_encoding=koi8-r
* usb.h
*
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#pragma once
#ifndef __USB_H__
#define __USB_H__
#include "hardware.h"
#define BUFFSIZE (64)
void USB_setup();
void usb_proc();
void USB_send(const uint8_t *buf, uint16_t len);
void USB_send_blk(const uint8_t *buf, uint16_t len);
uint8_t USB_receive(uint8_t *buf);
#endif // __USB_H__

View File

@@ -0,0 +1,103 @@
/*
* geany_encoding=koi8-r
* usb_defs.h
*
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#pragma once
#ifndef __USB_DEFS_H__
#define __USB_DEFS_H__
#include <stm32f0.h>
// max endpoints number
#define STM32ENDPOINTS 8
#define USB_EP1BUFSZ 8
/**
* Buffers size definition
**/
// !!! when working with CAN bus change USB_BTABLE_SIZE to 768 !!!
#define USB_BTABLE_SIZE 1024
// first 64 bytes of USB_BTABLE are registers!
#define USB_EP0_BASEADDR 64
// for USB FS EP0 buffers are from 8 to 64 bytes long (64 for PL2303)
#define USB_EP0_BUFSZ 64
// USB transmit buffer size (64 for PL2303)
#define USB_TXBUFSZ 64
// USB receive buffer size (64 for PL2303)
#define USB_RXBUFSZ 64
#define USB_BTABLE_BASE 0x40006000
#undef USB_BTABLE
#define USB_BTABLE ((USB_BtableDef *)(USB_BTABLE_BASE))
#define USB_ISTR_EPID 0x0000000F
#define USB_FNR_LSOF_0 0x00000800
#define USB_FNR_lSOF_1 0x00001000
#define USB_LPMCSR_BESL_0 0x00000010
#define USB_LPMCSR_BESL_1 0x00000020
#define USB_LPMCSR_BESL_2 0x00000040
#define USB_LPMCSR_BESL_3 0x00000080
#define USB_EPnR_CTR_RX 0x00008000
#define USB_EPnR_DTOG_RX 0x00004000
#define USB_EPnR_STAT_RX 0x00003000
#define USB_EPnR_STAT_RX_0 0x00001000
#define USB_EPnR_STAT_RX_1 0x00002000
#define USB_EPnR_SETUP 0x00000800
#define USB_EPnR_EP_TYPE 0x00000600
#define USB_EPnR_EP_TYPE_0 0x00000200
#define USB_EPnR_EP_TYPE_1 0x00000400
#define USB_EPnR_EP_KIND 0x00000100
#define USB_EPnR_CTR_TX 0x00000080
#define USB_EPnR_DTOG_TX 0x00000040
#define USB_EPnR_STAT_TX 0x00000030
#define USB_EPnR_STAT_TX_0 0x00000010
#define USB_EPnR_STAT_TX_1 0x00000020
#define USB_EPnR_EA 0x0000000F
#define USB_COUNTn_RX_BLSIZE 0x00008000
#define USB_COUNTn_NUM_BLOCK 0x00007C00
#define USB_COUNTn_RX 0x0000003F
#define USB_TypeDef USB_TypeDef_custom
typedef struct{
__IO uint32_t EPnR[STM32ENDPOINTS];
__IO uint32_t RESERVED[STM32ENDPOINTS];
__IO uint32_t CNTR;
__IO uint32_t ISTR;
__IO uint32_t FNR;
__IO uint32_t DADDR;
__IO uint32_t BTABLE;
__IO uint32_t LPMCSR;
__IO uint32_t BCDR;
} USB_TypeDef;
typedef struct{
__IO uint16_t USB_ADDR_TX;
__IO uint16_t USB_COUNT_TX;
__IO uint16_t USB_ADDR_RX;
__IO uint16_t USB_COUNT_RX;
} USB_EPDATA_TypeDef;
typedef struct{
__IO USB_EPDATA_TypeDef EP[STM32ENDPOINTS];
} USB_BtableDef;
#endif // __USB_DEFS_H__

View File

@@ -0,0 +1,470 @@
/*
* geany_encoding=koi8-r
* usb_lib.c
*
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#include <stdint.h>
#include "usb_lib.h"
ep_t endpoints[STM32ENDPOINTS];
usb_dev_t USB_Dev;
uint8_t usbON = 0; // device disconnected from terminal
static usb_LineCoding lineCoding = {115200, 0, 0, 8};
static config_pack_t setup_packet;
static uint8_t ep0databuf[EP0DATABUF_SIZE];
static uint8_t ep0dbuflen = 0;
usb_LineCoding getLineCoding(){return lineCoding;}
// definition of parts common for USB_DeviceDescriptor & USB_DeviceQualifierDescriptor
#define bcdUSB_L 0x10
#define bcdUSB_H 0x01
#define bDeviceClass 0
#define bDeviceSubClass 0
#define bDeviceProtocol 0
#define bNumConfigurations 1
static const uint8_t USB_DeviceDescriptor[] = {
18, // bLength
0x01, // bDescriptorType - Device descriptor
bcdUSB_L, // bcdUSB_L - 1.10
bcdUSB_H, // bcdUSB_H
bDeviceClass, // bDeviceClass - USB_COMM
bDeviceSubClass, // bDeviceSubClass
bDeviceProtocol, // bDeviceProtocol
USB_EP0_BUFSZ, // bMaxPacketSize
0x7b, // idVendor_L PL2303: VID=0x067b, PID=0x2303
0x06, // idVendor_H
0x03, // idProduct_L
0x23, // idProduct_H
0x00, // bcdDevice_Ver_L
0x03, // bcdDevice_Ver_H
0x01, // iManufacturer
0x02, // iProduct
0x00, // iSerialNumber
bNumConfigurations // bNumConfigurations
};
static const uint8_t USB_DeviceQualifierDescriptor[] = {
10, //bLength
0x06, // bDescriptorType - Device qualifier
bcdUSB_L, // bcdUSB_L
bcdUSB_H, // bcdUSB_H
bDeviceClass, // bDeviceClass
bDeviceSubClass, // bDeviceSubClass
bDeviceProtocol, // bDeviceProtocol
USB_EP0_BUFSZ, // bMaxPacketSize0
bNumConfigurations, // bNumConfigurations
0x00 // Reserved
};
static const uint8_t USB_ConfigDescriptor[] = {
/*Configuration Descriptor*/
0x09, /* bLength: Configuration Descriptor size */
0x02, /* bDescriptorType: Configuration */
39, /* wTotalLength:no of returned bytes */
0x00,
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor describing the configuration */
0xa0, /* bmAttributes - Bus powered, Remote wakeup */
0x32, /* MaxPower 100 mA */
/*---------------------------------------------------------------------------*/
/*Interface Descriptor */
0x09, /* bLength: Interface Descriptor size */
0x04, /* bDescriptorType: Interface */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x03, /* bNumEndpoints: 3 endpoints used */
0xff, /* bInterfaceClass */
0x00, /* bInterfaceSubClass */
0x00, /* bInterfaceProtocol */
0x00, /* iInterface: */
///////////////////////////////////////////////////
/*Endpoint 1 Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
0x05, /* bDescriptorType: Endpoint */
0x81, /* bEndpointAddress IN1 */
0x03, /* bmAttributes: Interrupt */
0x0a, /* wMaxPacketSize LO: */
0x00, /* wMaxPacketSize HI: */
0x01, /* bInterval: */
/*Endpoint OUT2 Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
0x05, /* bDescriptorType: Endpoint */
0x02, /* bEndpointAddress: OUT2 */
0x02, /* bmAttributes: Bulk */
(USB_RXBUFSZ & 0xff), /* wMaxPacketSize: 64 */
(USB_RXBUFSZ >> 8),
0x00, /* bInterval: ignore for Bulk transfer */
/*Endpoint IN3 Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
0x05, /* bDescriptorType: Endpoint */
0x83, /* bEndpointAddress IN3 */
0x02, /* bmAttributes: Bulk */
(USB_TXBUFSZ & 0xff), /* wMaxPacketSize: 64 */
(USB_TXBUFSZ >> 8),
0x00, /* bInterval: ignore for Bulk transfer */
};
_USB_LANG_ID_(USB_StringLangDescriptor, LANG_US);
// these descriptors are not used in PL2303 emulator!
_USB_STRING_(USB_StringSerialDescriptor, u"0");
_USB_STRING_(USB_StringManufacturingDescriptor, u"Prolific Technology Inc.");
_USB_STRING_(USB_StringProdDescriptor, u"USB-Serial Controller");
/*
* default handlers
*/
// SET_LINE_CODING
void WEAK linecoding_handler(usb_LineCoding __attribute__((unused)) *lc){
}
// SET_CONTROL_LINE_STATE
void WEAK clstate_handler(uint16_t __attribute__((unused)) val){
}
// SEND_BREAK
void WEAK break_handler(){
}
// handler of vendor requests
void WEAK vendor_handler(config_pack_t *packet){
if(packet->bmRequestType & 0x80){ // read
uint8_t c;
switch(packet->wValue){
case 0x8484:
c = 2;
break;
case 0x0080:
c = 1;
break;
case 0x8686:
c = 0xaa;
break;
default:
c = 0;
}
EP_WriteIRQ(0, &c, 1);
}else{ // write ZLP
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
}
static void wr0(const uint8_t *buf, uint16_t size){
if(setup_packet.wLength < size) size = setup_packet.wLength; // shortened request
if(size < endpoints[0].txbufsz){
EP_WriteIRQ(0, buf, size);
return;
}
while(size){
uint16_t l = size;
if(l > endpoints[0].txbufsz) l = endpoints[0].txbufsz;
EP_WriteIRQ(0, buf, l);
buf += l;
size -= l;
uint8_t needzlp = (l == endpoints[0].txbufsz) ? 1 : 0;
if(size || needzlp){ // send last data buffer
uint16_t status = KEEP_DTOG(USB->EPnR[0]);
// keep DTOGs, clear CTR_RX,TX, set TX VALID, leave stat_Rx
USB->EPnR[0] = (status & ~(USB_EPnR_CTR_RX|USB_EPnR_CTR_TX|USB_EPnR_STAT_RX))
^ USB_EPnR_STAT_TX;
uint32_t ctr = 1000000;
while(--ctr && (USB->ISTR & USB_ISTR_CTR) == 0){IWDG->KR = IWDG_REFRESH;};
if((USB->ISTR & USB_ISTR_CTR) == 0){
return;
}
if(needzlp) EP_WriteIRQ(0, (uint8_t*)0, 0);
}
}
}
static inline void get_descriptor(){
switch(setup_packet.wValue){
case DEVICE_DESCRIPTOR:
wr0(USB_DeviceDescriptor, sizeof(USB_DeviceDescriptor));
break;
case CONFIGURATION_DESCRIPTOR:
wr0(USB_ConfigDescriptor, sizeof(USB_ConfigDescriptor));
break;
case STRING_LANG_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringLangDescriptor, STRING_LANG_DESCRIPTOR_SIZE_BYTE);
break;
case STRING_MAN_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringManufacturingDescriptor, USB_StringManufacturingDescriptor.bLength);
break;
case STRING_PROD_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringProdDescriptor, USB_StringProdDescriptor.bLength);
break;
case STRING_SN_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringSerialDescriptor, USB_StringSerialDescriptor.bLength);
break;
case DEVICE_QUALIFIER_DESCRIPTOR:
wr0(USB_DeviceQualifierDescriptor, USB_DeviceQualifierDescriptor[0]);
break;
default:
break;
}
}
static uint8_t configuration = 0; // reply for GET_CONFIGURATION (==1 if configured)
static inline void std_d2h_req(){
uint16_t status = 0; // bus powered
switch(setup_packet.bRequest){
case GET_DESCRIPTOR:
get_descriptor();
break;
case GET_STATUS:
EP_WriteIRQ(0, (uint8_t *)&status, 2); // send status: Bus Powered
break;
case GET_CONFIGURATION:
EP_WriteIRQ(0, &configuration, 1);
break;
default:
break;
}
}
static inline void std_h2d_req(){
switch(setup_packet.bRequest){
case SET_ADDRESS:
// new address will be assigned later - after acknowlegement or request to host
USB_Dev.USB_Addr = setup_packet.wValue;
break;
case SET_CONFIGURATION:
// Now device configured
USB_Dev.USB_Status = USB_STATE_CONFIGURED;
configuration = setup_packet.wValue;
break;
default:
break;
}
}
/*
bmRequestType: 76543210
7 direction: 0 - host->device, 1 - device->host
65 type: 0 - standard, 1 - class, 2 - vendor
4..0 getter: 0 - device, 1 - interface, 2 - endpoint, 3 - other
*/
/**
* Endpoint0 (control) handler
*/
static void EP0_Handler(){
uint16_t epstatus = USB->EPnR[0]; // EP0R on input -> return this value after modifications
uint8_t reqtype = setup_packet.bmRequestType & 0x7f;
uint8_t dev2host = (setup_packet.bmRequestType & 0x80) ? 1 : 0;
int rxflag = RX_FLAG(epstatus);
if(rxflag && SETUP_FLAG(epstatus)){
switch(reqtype){
case STANDARD_DEVICE_REQUEST_TYPE: // standard device request
if(dev2host){
std_d2h_req();
}else{
std_h2d_req();
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
break;
case STANDARD_ENDPOINT_REQUEST_TYPE: // standard endpoint request
if(setup_packet.bRequest == CLEAR_FEATURE){
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
break;
case VENDOR_REQUEST_TYPE:
vendor_handler(&setup_packet);
break;
case CONTROL_REQUEST_TYPE:
switch(setup_packet.bRequest){
case GET_LINE_CODING:
EP_WriteIRQ(0, (uint8_t*)&lineCoding, sizeof(lineCoding));
break;
case SET_LINE_CODING: // omit this for next stage, when data will come
break;
case SET_CONTROL_LINE_STATE:
usbON = 1;
clstate_handler(setup_packet.wValue);
break;
case SEND_BREAK:
usbON = 0;
break_handler();
break;
default:
break;
}
if(setup_packet.bRequest != GET_LINE_CODING) EP_WriteIRQ(0, (uint8_t *)0, 0); // write acknowledgement
break;
default:
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
}else if(rxflag){ // got data over EP0 or host acknowlegement
if(endpoints[0].rx_cnt){
if(setup_packet.bRequest == SET_LINE_CODING){
linecoding_handler((usb_LineCoding*)ep0databuf);
}
}
} else if(TX_FLAG(epstatus)){ // package transmitted
// now we can change address after enumeration
if ((USB->DADDR & USB_DADDR_ADD) != USB_Dev.USB_Addr){
USB->DADDR = USB_DADDR_EF | USB_Dev.USB_Addr;
// change state to ADRESSED
USB_Dev.USB_Status = USB_STATE_ADDRESSED;
}
}
epstatus = KEEP_DTOG(USB->EPnR[0]);
if(rxflag) epstatus ^= USB_EPnR_STAT_TX; // start ZLP/data transmission
else epstatus &= ~USB_EPnR_STAT_TX; // or leave unchanged
// keep DTOGs, clear CTR_RX,TX, set RX VALID
USB->EPnR[0] = (epstatus & ~(USB_EPnR_CTR_RX|USB_EPnR_CTR_TX)) ^ USB_EPnR_STAT_RX;
}
static uint16_t lastaddr = USB_EP0_BASEADDR;
/**
* Endpoint initialisation
* !!! when working with CAN bus change USB_BTABLE_SIZE to 768 !!!
* @param number - EP num (0...7)
* @param type - EP type (EP_TYPE_BULK, EP_TYPE_CONTROL, EP_TYPE_ISO, EP_TYPE_INTERRUPT)
* @param txsz - transmission buffer size @ USB/CAN buffer
* @param rxsz - reception buffer size @ USB/CAN buffer
* @param uint16_t (*func)(ep_t *ep) - EP handler function
* @return 0 if all OK
*/
int EP_Init(uint8_t number, uint8_t type, uint16_t txsz, uint16_t rxsz, void (*func)()){
if(number >= STM32ENDPOINTS) return 4; // out of configured amount
if(txsz > USB_BTABLE_SIZE || rxsz > USB_BTABLE_SIZE) return 1; // buffer too large
if(lastaddr + txsz + rxsz >= USB_BTABLE_SIZE) return 2; // out of btable
USB->EPnR[number] = (type << 9) | (number & USB_EPnR_EA);
USB->EPnR[number] ^= USB_EPnR_STAT_RX | USB_EPnR_STAT_TX_1;
if(rxsz & 1 || rxsz > 992) return 3; // wrong rx buffer size
uint16_t countrx = 0;
if(rxsz < 64) countrx = rxsz / 2;
else{
if(rxsz & 0x1f) return 3; // should be multiple of 32
countrx = 31 + rxsz / 32;
}
USB_BTABLE->EP[number].USB_ADDR_TX = lastaddr;
endpoints[number].tx_buf = (uint16_t *)(USB_BTABLE_BASE + lastaddr);
endpoints[number].txbufsz = txsz;
lastaddr += txsz;
USB_BTABLE->EP[number].USB_COUNT_TX = 0;
USB_BTABLE->EP[number].USB_ADDR_RX = lastaddr;
endpoints[number].rx_buf = (uint8_t *)(USB_BTABLE_BASE + lastaddr);
lastaddr += rxsz;
// buffer size: Table127 of RM
USB_BTABLE->EP[number].USB_COUNT_RX = countrx << 10;
endpoints[number].func = func;
return 0;
}
// standard IRQ handler
void usb_isr(){
if (USB->ISTR & USB_ISTR_RESET){
usbON = 0;
// Reinit registers
USB->CNTR = USB_CNTR_RESETM | USB_CNTR_CTRM;
USB->ISTR = 0;
// Endpoint 0 - CONTROL
// ON USB LS size of EP0 may be 8 bytes, but on FS it should be 64 bytes!
lastaddr = LASTADDR_DEFAULT; // roll back to beginning of buffer
EP_Init(0, EP_TYPE_CONTROL, USB_EP0_BUFSZ, USB_EP0_BUFSZ, EP0_Handler);
// clear address, leave only enable bit
USB->DADDR = USB_DADDR_EF;
// state is default - wait for enumeration
USB_Dev.USB_Status = USB_STATE_DEFAULT;
}
if(USB->ISTR & USB_ISTR_CTR){
// EP number
uint8_t n = USB->ISTR & USB_ISTR_EPID;
// copy status register
uint16_t epstatus = USB->EPnR[n];
// copy received bytes amount
endpoints[n].rx_cnt = USB_BTABLE->EP[n].USB_COUNT_RX & 0x3FF; // low 10 bits is counter
// check direction
if(USB->ISTR & USB_ISTR_DIR){ // OUT interrupt - receive data, CTR_RX==1 (if CTR_TX == 1 - two pending transactions: receive following by transmit)
if(n == 0){ // control endpoint
if(epstatus & USB_EPnR_SETUP){ // setup packet -> copy data to conf_pack
EP_Read(0, (uint8_t*)&setup_packet);
ep0dbuflen = 0;
// interrupt handler will be called later
}else if(epstatus & USB_EPnR_CTR_RX){ // data packet -> push received data to ep0databuf
ep0dbuflen = endpoints[0].rx_cnt;
EP_Read(0, (uint8_t*)&ep0databuf);
}
}
}else{ // IN interrupt - transmit data, only CTR_TX == 1
// enumeration end could be here (if EP0)
}
// call EP handler
if(endpoints[n].func) endpoints[n].func(endpoints[n]);
}
}
/**
* Write data to EP buffer (called from IRQ handler)
* @param number - EP number
* @param *buf - array with data
* @param size - its size
*/
void EP_WriteIRQ(uint8_t number, const uint8_t *buf, uint16_t size){
uint8_t i;
if(size > endpoints[number].txbufsz) size = endpoints[number].txbufsz;
uint16_t N2 = (size + 1) >> 1;
// the buffer is 16-bit, so we should copy data as it would be uint16_t
uint16_t *buf16 = (uint16_t *)buf;
for (i = 0; i < N2; i++){
endpoints[number].tx_buf[i] = buf16[i];
}
USB_BTABLE->EP[number].USB_COUNT_TX = size;
}
/**
* Write data to EP buffer (called outside IRQ handler)
* @param number - EP number
* @param *buf - array with data
* @param size - its size
*/
void EP_Write(uint8_t number, const uint8_t *buf, uint16_t size){
EP_WriteIRQ(number, buf, size);
uint16_t status = KEEP_DTOG(USB->EPnR[number]);
// keep DTOGs, clear CTR_TX & set TX VALID to start transmission
USB->EPnR[number] = (status & ~(USB_EPnR_CTR_TX)) ^ USB_EPnR_STAT_TX;
}
/*
* Copy data from EP buffer into user buffer area
* @param *buf - user array for data
* @return amount of data read
*/
int EP_Read(uint8_t number, uint8_t *buf){
int n = endpoints[number].rx_cnt;
endpoints[number].rx_cnt = 0;
if(n){
for(int i = 0; i < n; ++i)
buf[i] = endpoints[number].rx_buf[i];
}
return n;
}

View File

@@ -0,0 +1,191 @@
/*
* geany_encoding=koi8-r
* usb_lib.h
*
* Copyright 2018 Edward V. Emelianov <eddy@sao.ru, 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 2 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#pragma once
#ifndef __USB_LIB_H__
#define __USB_LIB_H__
#include <wchar.h>
#include "usb_defs.h"
#define EP0DATABUF_SIZE (64)
#define LASTADDR_DEFAULT (STM32ENDPOINTS * 8)
// Max EP amount (EP0 + other used)
#define ENDPOINTS_NUM 4
// bmRequestType & 0x7f
#define STANDARD_DEVICE_REQUEST_TYPE 0
#define STANDARD_ENDPOINT_REQUEST_TYPE 2
#define VENDOR_REQUEST_TYPE 0x40
#define CONTROL_REQUEST_TYPE 0x21
// bRequest, standard; for bmRequestType == 0x80
#define GET_STATUS 0x00
#define GET_DESCRIPTOR 0x06
#define GET_CONFIGURATION 0x08
// for bmRequestType == 0
#define CLEAR_FEATURE 0x01
#define SET_FEATURE 0x03 // unused
#define SET_ADDRESS 0x05
#define SET_DESCRIPTOR 0x07 // unused
#define SET_CONFIGURATION 0x09
// for bmRequestType == 0x81, 1 or 0xB2
#define GET_INTERFACE 0x0A // unused
#define SET_INTERFACE 0x0B // unused
#define SYNC_FRAME 0x0C // unused
#define VENDOR_REQUEST 0x01 // unused
// Class-Specific Control Requests
#define SEND_ENCAPSULATED_COMMAND 0x00 // unused
#define GET_ENCAPSULATED_RESPONSE 0x01 // unused
#define SET_COMM_FEATURE 0x02 // unused
#define GET_COMM_FEATURE 0x03 // unused
#define CLEAR_COMM_FEATURE 0x04 // unused
#define SET_LINE_CODING 0x20
#define GET_LINE_CODING 0x21
#define SET_CONTROL_LINE_STATE 0x22
#define SEND_BREAK 0x23
// control line states
#define CONTROL_DTR 0x01
#define CONTROL_RTS 0x02
// wValue
#define DEVICE_DESCRIPTOR 0x100
#define CONFIGURATION_DESCRIPTOR 0x200
#define STRING_LANG_DESCRIPTOR 0x300
#define STRING_MAN_DESCRIPTOR 0x301
#define STRING_PROD_DESCRIPTOR 0x302
#define STRING_SN_DESCRIPTOR 0x303
#define DEVICE_QUALIFIER_DESCRIPTOR 0x600
#define RX_FLAG(epstat) (epstat & USB_EPnR_CTR_RX)
#define TX_FLAG(epstat) (epstat & USB_EPnR_CTR_TX)
#define SETUP_FLAG(epstat) (epstat & USB_EPnR_SETUP)
// EPnR bits manipulation
#define KEEP_DTOG_STAT(EPnR) (EPnR & ~(USB_EPnR_STAT_RX|USB_EPnR_STAT_TX|USB_EPnR_DTOG_RX|USB_EPnR_DTOG_TX))
#define KEEP_DTOG(EPnR) (EPnR & ~(USB_EPnR_DTOG_RX|USB_EPnR_DTOG_TX))
// USB state: uninitialized, addressed, ready for use, connected
typedef enum{
USB_STATE_DEFAULT,
USB_STATE_ADDRESSED,
USB_STATE_CONFIGURED,
USB_STATE_CONNECTED
} USB_state;
// EP types
#define EP_TYPE_BULK 0x00
#define EP_TYPE_CONTROL 0x01
#define EP_TYPE_ISO 0x02
#define EP_TYPE_INTERRUPT 0x03
#define LANG_US (uint16_t)0x0409
#define _USB_STRING_(name, str) \
static const struct name \
{ \
uint8_t bLength; \
uint8_t bDescriptorType; \
uint16_t bString[(sizeof(str) - 2) / 2]; \
\
} \
name = {sizeof(name), 0x03, str}
#define _USB_LANG_ID_(name, lng_id) \
\
static const struct name \
{ \
uint8_t bLength; \
uint8_t bDescriptorType; \
uint16_t bString; \
\
} \
name = {0x04, 0x03, lng_id}
#define STRING_LANG_DESCRIPTOR_SIZE_BYTE (4)
// EP0 configuration packet
typedef struct {
uint8_t bmRequestType;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} config_pack_t;
// endpoints state
typedef struct{
uint16_t *tx_buf; // transmission buffer address
uint16_t txbufsz; // transmission buffer size
uint8_t *rx_buf; // reception buffer address
void (*func)(); // endpoint action function
unsigned rx_cnt : 10; // received data counter
} ep_t;
// USB status & its address
typedef struct {
uint8_t USB_Status;
uint16_t USB_Addr;
}usb_dev_t;
typedef struct {
uint32_t dwDTERate;
uint8_t bCharFormat;
#define USB_CDC_1_STOP_BITS 0
#define USB_CDC_1_5_STOP_BITS 1
#define USB_CDC_2_STOP_BITS 2
uint8_t bParityType;
#define USB_CDC_NO_PARITY 0
#define USB_CDC_ODD_PARITY 1
#define USB_CDC_EVEN_PARITY 2
#define USB_CDC_MARK_PARITY 3
#define USB_CDC_SPACE_PARITY 4
uint8_t bDataBits;
} __attribute__ ((packed)) usb_LineCoding;
typedef struct {
uint8_t bmRequestType;
uint8_t bNotificationType;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} __attribute__ ((packed)) usb_cdc_notification;
extern ep_t endpoints[];
extern usb_dev_t USB_Dev;
extern uint8_t usbON;
void USB_Init();
int EP_Init(uint8_t number, uint8_t type, uint16_t txsz, uint16_t rxsz, void (*func)());
void EP_WriteIRQ(uint8_t number, const uint8_t *buf, uint16_t size);
void EP_Write(uint8_t number, const uint8_t *buf, uint16_t size);
int EP_Read(uint8_t number, uint8_t *buf);
usb_LineCoding getLineCoding();
void linecoding_handler(usb_LineCoding *lc);
void clstate_handler(uint16_t val);
void break_handler();
void vendor_handler(config_pack_t *packet);
#endif // __USB_LIB_H__