From 3b3c150474a0325d2732bb7b4e3a44ebbd6394aa Mon Sep 17 00:00:00 2001 From: eddyem Date: Mon, 23 Jan 2023 17:35:44 +0300 Subject: [PATCH] add ADC (don't working DAC, don't workint Tsens) --- F0:F030,F042,F072/F0_testbrd/proto.c | 1 + F3:F303/ADC/Makefile | 9 + F3:F303/ADC/Readme | 1 + F3:F303/ADC/adc.bin | Bin 0 -> 7036 bytes F3:F303/ADC/adc.c | 172 ++++++++++++ F3:F303/ADC/adc.cflags | 1 + F3:F303/ADC/adc.config | 7 + F3:F303/ADC/adc.creator | 1 + F3:F303/ADC/adc.creator.user | 171 ++++++++++++ F3:F303/ADC/adc.cxxflags | 1 + F3:F303/ADC/adc.files | 17 ++ F3:F303/ADC/adc.h | 40 +++ F3:F303/ADC/adc.includes | 6 + F3:F303/ADC/hardware.c | 33 +++ F3:F303/ADC/hardware.h | 26 ++ F3:F303/ADC/main.c | 66 +++++ F3:F303/ADC/openocd.cfg | 110 ++++++++ F3:F303/ADC/proto.c | 115 ++++++++ F3:F303/ADC/proto.h | 25 ++ F3:F303/ADC/ringbuffer.c | 124 +++++++++ F3:F303/ADC/ringbuffer.h | 35 +++ F3:F303/ADC/strfunc.c | 343 +++++++++++++++++++++++ F3:F303/ADC/strfunc.h | 32 +++ F3:F303/ADC/usb.c | 176 ++++++++++++ F3:F303/ADC/usb.h | 35 +++ F3:F303/ADC/usb_lib.c | 389 +++++++++++++++++++++++++++ F3:F303/ADC/usb_lib.h | 182 +++++++++++++ F3:F303/ADC/usbhw.c | 137 ++++++++++ F3:F303/ADC/usbhw.h | 103 +++++++ F3:F303/ADC/version.inc | 2 + F3:F303/PL2303/openocd.cfg | 119 ++++++++ F3:F303/USB_template/openocd.cfg | 119 ++++++++ 32 files changed, 2598 insertions(+) create mode 100644 F3:F303/ADC/Makefile create mode 100644 F3:F303/ADC/Readme create mode 100755 F3:F303/ADC/adc.bin create mode 100644 F3:F303/ADC/adc.c create mode 100644 F3:F303/ADC/adc.cflags create mode 100644 F3:F303/ADC/adc.config create mode 100644 F3:F303/ADC/adc.creator create mode 100644 F3:F303/ADC/adc.creator.user create mode 100644 F3:F303/ADC/adc.cxxflags create mode 100644 F3:F303/ADC/adc.files create mode 100644 F3:F303/ADC/adc.h create mode 100644 F3:F303/ADC/adc.includes create mode 100644 F3:F303/ADC/hardware.c create mode 100644 F3:F303/ADC/hardware.h create mode 100644 F3:F303/ADC/main.c create mode 100644 F3:F303/ADC/openocd.cfg create mode 100644 F3:F303/ADC/proto.c create mode 100644 F3:F303/ADC/proto.h create mode 100644 F3:F303/ADC/ringbuffer.c create mode 100644 F3:F303/ADC/ringbuffer.h create mode 100644 F3:F303/ADC/strfunc.c create mode 100644 F3:F303/ADC/strfunc.h create mode 100644 F3:F303/ADC/usb.c create mode 100644 F3:F303/ADC/usb.h create mode 100644 F3:F303/ADC/usb_lib.c create mode 100644 F3:F303/ADC/usb_lib.h create mode 100644 F3:F303/ADC/usbhw.c create mode 100644 F3:F303/ADC/usbhw.h create mode 100644 F3:F303/ADC/version.inc create mode 100644 F3:F303/PL2303/openocd.cfg create mode 100644 F3:F303/USB_template/openocd.cfg diff --git a/F0:F030,F042,F072/F0_testbrd/proto.c b/F0:F030,F042,F072/F0_testbrd/proto.c index 9c7ff48..a9d3819 100644 --- a/F0:F030,F042,F072/F0_testbrd/proto.c +++ b/F0:F030,F042,F072/F0_testbrd/proto.c @@ -23,6 +23,7 @@ #include "usart.h" #include "usb.h" #include "usb_lib.h" +#include #define LOCBUFFSZ (32) // local buffer for I2C and SPI data to send diff --git a/F3:F303/ADC/Makefile b/F3:F303/ADC/Makefile new file mode 100644 index 0000000..9e20e3f --- /dev/null +++ b/F3:F303/ADC/Makefile @@ -0,0 +1,9 @@ +BINARY := adc +PREFIX=/opt/ARM10/bin/arm-none-eabi +# MCU code +MCU := F303xb +# change this linking script depending on particular MCU model, +LDSCRIPT := stm32f303xB.ld + +include ../makefile.f3 +include ../../makefile.stm32 diff --git a/F3:F303/ADC/Readme b/F3:F303/ADC/Readme new file mode 100644 index 0000000..31702a2 --- /dev/null +++ b/F3:F303/ADC/Readme @@ -0,0 +1 @@ +ADC and DAC on STM32D303 diff --git a/F3:F303/ADC/adc.bin b/F3:F303/ADC/adc.bin new file mode 100755 index 0000000000000000000000000000000000000000..4f9f286d9fa404fc5bf35cd24d765003e91863b7 GIT binary patch literal 7036 zcmeG=4SQ2nn(zHc^U=_zEl8VIxNZ0-q)2E~u%NxYNpJH}8l->>jKd9WA=N@-TeLE> zPb1)1fzdjhXCI`jqByLh&e{(;3u-4F9Y-jpHzc~47hw?gN-%8b+Uuc~!@`d4>*o@)C}E%Ex+XWmum$G? znWFbf8l(v*JGw_tZ*WY?{d=ivoCiI@e;~8MJ}E6B_d62H>}bRPBJWf}9?|K3#{

zY(*=J=ajqmxtAGKRh4d^A*0GuTjUhJW>{Wkz~eqCEwv3wOUrZIbMn@^&q{|p_c*N4 zW7UUnWR)rQkYqEd4NJd|xc3zq*tjsuEula}bk0+!vd!dk!(l;$z}Vh+$1{;)+bsC@K)rNLz5uByJJ+ zAf$sP1JEFK%#x-&Mi<μ&+Jr==rqSi zK6>Ptkst4zKQa#+XjFYL7N2c4SE6fu_o;emT(vHq>NtNz_egi_xT!n#K8GBUtF9{Bl8GHKj8^*SWxw9P&bW+=*AE}Me(uu37v>8 zTSt7z?<37KBff9xp|U$_g=l}C@U^bd;U@cfJjgl~xl~@3w80%88zcNlj<8^(9T^_V zoI$e2--iBJbV)Azg|>wbV>yd;ZrC7m3+&%>FDTy?GXUf&^Iml8(RUBV&&Lk?=DOxq zfPCcET#rkht~Pi!X7`NVXweSL_583_&z`f;QNEBt&t+KNbsva}VH^yC2c#L`- zR^kruma%>iRYJicK!^(ZqwC^iGM9 z3#>5~1@lnS&6|17Ob^J*QO@X1BID%Ee39ui^;vVMUl32Mx~}WlBX9w#qi58&Dd*Ho z$4pzhbR`rY+Z4|iFJV7(;zpIq`R)R+pOq6^yvQ^4Ds zB+mH4>Nz5$omJpDq6o7oMr%qW{=kP3ilv4dOBI3P%#0ZI+5Xa4(Ax)wgF^ZjCUOpk zX)R;bM&c{_BUB1CTveJBNC`85w2Su&W5J6dmmD{F`x5_U-d=^+?|I8}Sa{d}s3$uc zvimca^*rin6OM#g=5@bLY!_blXNbG;pAnNptl=JmmG7dEe-4o!*2bu>jtJL-Z31<+ zQ_!4y)ANXjvA!w2>1h{egbwQ8ki2~hJ(gJ}eX><&O^;F8OpKbn3)c`@^KDu-L2D8T zwMj&a{N7$xyhFTGjE^BNU)tkYZeI_AXhPo6xQpvt zVRD9g@ys0w-c#_`Gxc(dC0UX%3REFkryiamORlRyTwQz=SDU+ttS`Hj1x)zEB>BuP zVVd+&kkGd`(}iGM5g@D5h81@miMZJrXA}ijh8~(TL-x8zR(%#^!ipJ$7a0GP&{|z^ zBvO(T8ZyoKYiQ}5%c0H2SJ1AtIUjW8i;$-ohJ~)n0^M_NiIJ>Q`N@qkJD~$rAfI_! z&`A9O^tu6UE+hYvcp?P;7hila>(~gdiHzuO_#%JtoxjqwvvZ_>=P^8Y2@bCA_VteR zC+6j25b^t9?)fWqI3G&j_^a>uz~I9ZnK4h{#y+1~(eTCC2>gxq(bF$q`N2+t;YO4i zy*NdGB*HMGgJ9(4eZF-L$ZrgcqXumL8t2-Id_T+09BFfq+XWN$F<$K3uYktoBoK~v zK7nUDFOXY@B*$SK?+7|8t|&TslgY^vU6(&+OiP&XZtW}Katd=NYnKoS-esVQ7%vpq zFy=>ZvKhJJ=PEY52PU(OpUkrRB15ofMUX^Se$QKWw?l_Flb>E>0E~ssV}8B3AtzJH zdW_^N%+Gf$L{7}~Eb)TsgRo`#2jM-eX$cj!Qqx5u6^vg6XLc5|-3R&m zg4fU&CiES#mskk}zY3CFfU}F<4-o1}*?&0uKKh87|7oZTV@1uqKQ!gxma#2wf7{14 z+*QS+&bK#&)DE>XLwXxy9FMoO0PM6L#l5me4=S=>yx4oN9Y9<~Nd+W3H+uBlc~PH` zC-XFUrzp=U9T~jBQFg86v1GmyvnEeAF}tIDWk>hb5PTo_=bw+qO}%N(4$ljnhN#bC zka?z7q`5=gAipxMlj90yQ0PYxu zf#;54^Y*5#G&VC`-aegOXXEqYV-MV7MgBxeh1tX7y#(?oL!o5!di!>DEA0%PSND!9 zojJIdX^|2MeAhVP$s(`!Sl}|TKTZQT-4XQIuBA45dz1O}l>^eGj5K>%LWVXWBlRE1 zP$gur7`o9f)%nce)8m=Zd= zrj<`yNevsDD^E~)(;`ZWRCWC=$R7<*c-EWx^1bn~^>H~wv>@;#FT#iL^LD9F!;M`G zsp7_>F32T4wFDO4!27}>KT?zt+2s677H44OG`aDy-;J}grUlX~W_)2L*3r%rbFJoP zMT{!Q=mJBvVD@rYXF+lt{=E2h`pz6a`n+hsom)yHxWkD+)X0_Tdlk}@mXem3(UoM&V6xIP> z2{n4WBt=T~JQL*~dPe4ysnU5R)qVG1vC(wqk4dKBCiU#4YHE_Qzhw4}{nxY-8-X=U zI7#ce471*)@!Wzm7dy(YsfMx`$1B4=HYozDUiGC!d;&e%FTg0jsthAxlm1!yc?|mh zRT_{K9Tz0IZ<8tzVmP^v#+Fawh5F8O;>~!o>DULcR?dIb^}PRT{quB!6J5yJ+VK@k zG3{=~W05(Akt*>^Mq3H4uv(&Eu5|BrC*v!{VlhN{d?h@MXP5I4L$t+UiEcMIHxJYv z9-YG@B{Sfr=A<~;>dE(z)}gj#R1;1aHLmF4wFA}2vAPm5V3|?9M>4&)&rRM$@F%=u z1I6=r$0mDOnXl{B4t1kXl|w!F|B}cIksEA$%<88&T_1~0?ky^>s#~wv-6;+(b#ACj zW9Og#e%-w*Svi%>qljf#lPN{`DT?^2GB(E>@NB3{-g_!Zx~gW9ceyU_Nn%guoLH_X z8(hZTKX|uQfmQb}p1ECyT4?{-#Z-8`ESKf&--CI#u?)U>@37yo5;#{hM^JfrLtgcCyV2*%`*U>$=A6o_7b)Ba!xNByF^DUx zs;XZOO>-{XJI$`g+y~ik<3uRgPDZnCU|sTd->z>Yh9vJuJV`$O(+p63iSTRKE@C6! zUrx1R^>Do)^u*YQSFXvZ_IzT^bcab|2c8? zjprsJrJvyVYf%%Sv?s4tFo(pAT~tTTY%pxd`Oj`sEW>1tvBk$q&EmD8SHdamYu%s5 z*u!4yoDmP4!7w*8j zk&l^tb7<^)TU8!vVZNWrdobrWS1Ty0i;+Q`M%uY%^z0)>OSJKMJEzCZF4V1_}iZTSN8E>OA`?hzyOh>onT5-d6yPn?_8sF5c@>hcbF-V{x#mnL?=gZ)^p(llUQn&Slg>MDsJJMS<((9qB)}GOlmU*Xo zM){VR1NBk9A;U@=3x>{LWboUa77Jnl?yx5&q|hu|A&wd*HiquBu{hc`u`Yyf(3Z3S zsVXheRc~k7<|E!c;Xr(UeM_|L?ddjhPOYCP31!&Qaa1|6B9xX`T`{rr_Fg3WZz}J| z{!8Q>_GEt+;Qq|a#=VL6BP;d?uph+Mk8K#+OsAu6Y*J?(SD24zCn60#&OPT#f=#}$%~R0XCi0x z)Luw+kQ0Os`{?eNuK(m!H5}-wzpB=@dtOBtkUwj7U9Qv8_c7u9T62so$i=UathtK3 zc5&|zJ`-p!8K>ac;ibvR0sg78Lt{&Jv%tx z6wGxCGzc$Az?0*9rp9Y3$p}ERZgr`MLzffap$6o^SxYROdz-hewrNLo4RQonS--uu zsXigCwvhv<->!lBEn5BnaU@YHo?. + * + * 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 "adc.h" + +/** + * @brief ADCx_array - arrays for ADC channels with median filtering: + * ADC1: + * 0 - Rvar - ADC1_IN1 + * 1 - Rvar/2 - ADC1_IN2 + * 2 - internal Tsens - ADC1_IN16 + * 3 - Vref - ADC1_IN18 + * ADC2: + * 4 - AIN5/DAC_OUT1 - PA4 - DAC1_OUT1, PA5 - ADC2_IN2 + */ +static uint16_t ADC_array[NUMBER_OF_ADC_CHANNELS*9]; + +TRUE_INLINE void calADC(ADC_TypeDef *chnl){ + // calibration + // enable voltage regulator + chnl->CR = 0; + chnl->CR = ADC_CR_ADVREGEN_0; + // wait for 10us + uint16_t ctr = 0; + while(++ctr < 1000){nop();} + // ADCALDIF=0 (single channels) + if((chnl->CR & ADC_CR_ADEN)){ + chnl->CR |= ADC_CR_ADSTP; + chnl->CR |= ADC_CR_ADDIS; + } + chnl->CR |= ADC_CR_ADCAL; + while((chnl->CR & ADC_CR_ADCAL) != 0 && ++ctr < 0xfff0){}; + chnl->CR = ADC_CR_ADVREGEN_0; + // enable ADC + ctr = 0; + do{ + chnl->CR |= ADC_CR_ADEN; + }while((chnl->ISR & ADC_ISR_ADRDY) == 0 && ++ctr < 0xfff0); +} + +TRUE_INLINE void enADC(ADC_TypeDef *chnl){ + // ADEN->1, wait ADRDY + chnl->CR |= ADC_CR_ADEN; + uint16_t ctr = 0; + while(!(chnl->ISR & ADC_ISR_ADRDY) && ++ctr < 0xffff){} + chnl->CR |= ADC_CR_ADSTART; /* start the ADC conversions */ +} + +/** + * ADC1 - DMA1_ch1 + * ADC2 - DMA2_ch1 + */ +// Setup ADC and DAC +void adc_setup(){ + RCC->AHBENR |= RCC_AHBENR_ADC12EN; // Enable clocking + ADC12_COMMON->CCR = ADC_CCR_TSEN | ADC_CCR_VREFEN | ADC_CCR_CKMODE; // enable Tsens and Vref, HCLK/4 + calADC(ADC1); + calADC(ADC2); + // ADC1: channels 1,2,16,18; ADC2: channel 2 + ADC1->SMPR1 = ADC_SMPR1_SMP0 | ADC_SMPR1_SMP1; + ADC1->SMPR2 = ADC_SMPR2_SMP15 | ADC_SMPR2_SMP17; + // 4 conversions in group: 1->2->16->18 + ADC1->SQR1 = (1<<6) | (2<<12) | (16<<18) | (18<<24) | (4-1); + ADC2->SMPR1 = ADC_SMPR1_SMP1; + ADC2->SQR1 = (2<<6) | (1-1); + // configure DMA for ADC + RCC->AHBENR |= RCC_AHBENR_DMA1EN | RCC_AHBENR_DMA2EN; + ADC1->CFGR = ADC_CFGR_CONT | ADC_CFGR_DMAEN | ADC_CFGR_DMACFG; + ADC2->CFGR = ADC_CFGR_CONT | ADC_CFGR_DMAEN | ADC_CFGR_DMACFG; + DMA1_Channel1->CPAR = (uint32_t) (&(ADC1->DR)); + DMA1_Channel1->CMAR = (uint32_t)(ADC_array); + DMA1_Channel1->CNDTR = NUMBER_OF_ADC1_CHANNELS * 9; + DMA1_Channel1->CCR |= DMA_CCR_MINC | DMA_CCR_MSIZE_0 | DMA_CCR_PSIZE_0 | DMA_CCR_CIRC; + DMA1_Channel1->CCR |= DMA_CCR_EN; + + DMA2_Channel1->CPAR = (uint32_t) (&(ADC2->DR)); + DMA2_Channel1->CMAR = (uint32_t)(&ADC_array[ADC2START]); + DMA2_Channel1->CNDTR = NUMBER_OF_ADC2_CHANNELS * 9; + DMA2_Channel1->CCR |= DMA_CCR_MINC | DMA_CCR_MSIZE_0 | DMA_CCR_PSIZE_0 | DMA_CCR_CIRC; + DMA2_Channel1->CCR |= DMA_CCR_EN; + + enADC(ADC1); + enADC(ADC2); + // configure DAC to generate a triangle wave on DAC1_OUT synchronized by TIM6 HW trigger + /* (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_DAC1EN; /* (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) */ +} + +/** + * @brief getADCval - calculate median value for `nch` channel + * @param nch - number of channel + * @return + */ +uint16_t getADCval(int nch){ + int 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]; + int adval = (nch >= NUMBER_OF_ADC1_CHANNELS) ? NUMBER_OF_ADC2_CHANNELS : NUMBER_OF_ADC1_CHANNELS; + for(int i = 0; i < 9; ++i, addr += adval) // 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 (V) +float getADCvoltage(int nch){ + float v = getADCval(nch); + v *= getVdd(); + v /= 4096.f; // 12bit ADC + return v; +} + +// return MCU temperature (degrees of celsius) +float getMCUtemp(){ + // make correction on Vdd value + int32_t ADval = getADCval(ADC_TS); + float temperature = (float) *TEMP30_CAL_ADDR - ADval; + temperature *= (110.f - 30.f); + temperature /= (float)(*TEMP30_CAL_ADDR - *TEMP110_CAL_ADDR); + temperature += 30.f; + return(temperature); +} + +// return Vdd (V) +float getVdd(){ + float vdd = ((float) *VREFINT_CAL_ADDR) * 3.3f; // 3.3V + vdd /= getADCval(ADC_VREF); + return vdd; +} diff --git a/F3:F303/ADC/adc.cflags b/F3:F303/ADC/adc.cflags new file mode 100644 index 0000000..68d5165 --- /dev/null +++ b/F3:F303/ADC/adc.cflags @@ -0,0 +1 @@ +-std=c17 \ No newline at end of file diff --git a/F3:F303/ADC/adc.config b/F3:F303/ADC/adc.config new file mode 100644 index 0000000..1cf1964 --- /dev/null +++ b/F3:F303/ADC/adc.config @@ -0,0 +1,7 @@ +// Add predefined macros for your project here. For example: +// #define THE_ANSWER 42 +#define EBUG +#define STM32F3 +#define STM32F303xb +#define __thumb2__ 1 +#define __ARM_ARCH_7M__ diff --git a/F3:F303/ADC/adc.creator b/F3:F303/ADC/adc.creator new file mode 100644 index 0000000..e94cbbd --- /dev/null +++ b/F3:F303/ADC/adc.creator @@ -0,0 +1 @@ +[General] diff --git a/F3:F303/ADC/adc.creator.user b/F3:F303/ADC/adc.creator.user new file mode 100644 index 0000000..aa79e75 --- /dev/null +++ b/F3:F303/ADC/adc.creator.user @@ -0,0 +1,171 @@ + + + + + + EnvironmentId + {7bd84e39-ca37-46d3-be9d-99ebea85bc0d} + + + 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 + true + false + 0 + true + true + 0 + 8 + true + false + 1 + true + false + true + *.md, *.MD, Makefile + false + true + + + + ProjectExplorer.Project.PluginSettings + + + true + false + true + true + true + true + + + 0 + true + + true + true + Builtin.DefaultTidyAndClazy + 2 + + + + true + + + + + ProjectExplorer.Project.Target.0 + + Desktop + Desktop + Desktop + {65a14f9e-e008-4c1b-89df-4eaa4774b6e3} + 0 + 0 + 0 + + /Big/Data/00__Electronics/STM32/F303-nolib/blink + + + + all + + true + GenericProjectManager.GenericMakeStep + + 1 + Сборка + Сборка + ProjectExplorer.BuildSteps.Build + + + + + clean + + true + GenericProjectManager.GenericMakeStep + + 1 + Очистка + Очистка + ProjectExplorer.BuildSteps.Clean + + 2 + false + + false + + Default + 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/F3:F303/ADC/adc.cxxflags b/F3:F303/ADC/adc.cxxflags new file mode 100644 index 0000000..6435dfc --- /dev/null +++ b/F3:F303/ADC/adc.cxxflags @@ -0,0 +1 @@ +-std=c++17 \ No newline at end of file diff --git a/F3:F303/ADC/adc.files b/F3:F303/ADC/adc.files new file mode 100644 index 0000000..ee5fb49 --- /dev/null +++ b/F3:F303/ADC/adc.files @@ -0,0 +1,17 @@ +adc.c +adc.h +hardware.c +hardware.h +main.c +proto.c +proto.h +ringbuffer.c +ringbuffer.h +strfunc.c +strfunc.h +usb.c +usb.h +usb_lib.c +usb_lib.h +usbhw.c +usbhw.h diff --git a/F3:F303/ADC/adc.h b/F3:F303/ADC/adc.h new file mode 100644 index 0000000..c0654c4 --- /dev/null +++ b/F3:F303/ADC/adc.h @@ -0,0 +1,40 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 NUMBER_OF_ADC1_CHANNELS (4) +#define NUMBER_OF_ADC2_CHANNELS (1) +// total number of channels - for array +#define NUMBER_OF_ADC_CHANNELS ((NUMBER_OF_ADC1_CHANNELS+NUMBER_OF_ADC2_CHANNELS)) + +// channels of ADC in array +#define ADC_AIN0 (0) +#define ADC_AIN1 (1) +#define ADC_TS (2) +#define ADC_VREF (3) +#define ADC_AIN5 (4) +// starting index of ADC2 +#define ADC2START (9*NUMBER_OF_ADC1_CHANNELS) + +void adc_setup(); +float getMCUtemp(); +float getVdd(); +uint16_t getADCval(int nch); +float getADCvoltage(int nch); diff --git a/F3:F303/ADC/adc.includes b/F3:F303/ADC/adc.includes new file mode 100644 index 0000000..06d1130 --- /dev/null +++ b/F3:F303/ADC/adc.includes @@ -0,0 +1,6 @@ +. +../inc +../inc/Fx +../inc/cm +../inc/ld +../inc/startup diff --git a/F3:F303/ADC/hardware.c b/F3:F303/ADC/hardware.c new file mode 100644 index 0000000..f2eb078 --- /dev/null +++ b/F3:F303/ADC/hardware.c @@ -0,0 +1,33 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 "adc.h" +#include "hardware.h" + +TRUE_INLINE void gpio_setup(){ + RCC->AHBENR |= RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN; // for USART and LEDs + for(int i = 0; i < 10000; ++i) nop(); + GPIOB->MODER = GPIO_MODER_MODER0_O | GPIO_MODER_MODER1_O; + GPIOB->ODR = 1; +} + +void hw_setup(){ + gpio_setup(); + adc_setup(); +} + diff --git a/F3:F303/ADC/hardware.h b/F3:F303/ADC/hardware.h new file mode 100644 index 0000000..bcce2b8 --- /dev/null +++ b/F3:F303/ADC/hardware.h @@ -0,0 +1,26 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 + +extern volatile uint32_t Tms; + +void hw_setup(); + diff --git a/F3:F303/ADC/main.c b/F3:F303/ADC/main.c new file mode 100644 index 0000000..e17a9fd --- /dev/null +++ b/F3:F303/ADC/main.c @@ -0,0 +1,66 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 "adc.h" +#include "hardware.h" +#include "proto.h" +#include "usb.h" + +#define MAXSTRLEN RBINSZ +#define ADCthreshold (20) + +volatile uint32_t Tms = 0; + +void sys_tick_handler(void){ + ++Tms; +} + +int main(void){ + uint32_t oldADCval = 0; + char inbuff[MAXSTRLEN+1]; + if(StartHSE()){ + SysTick_Config((uint32_t)72000); // 1ms + }else{ + StartHSI(); + SysTick_Config((uint32_t)48000); // 1ms + } + hw_setup(); + USB_setup(); + uint32_t ctr = Tms; + while(1){ + if(Tms - ctr > 499){ + ctr = Tms; + pin_toggle(GPIOB, 1 << 1 | 1 << 0); // toggle LED @ PB0 + if(ADCmon){ + uint16_t v = getADCval(ADC_AIN0); + int32_t d = v - oldADCval; + if(d < -ADCthreshold || d > ADCthreshold){ + oldADCval = v; + printADCvals(); + } + } + } + USB_proc(); + int l = USB_receivestr(inbuff, MAXSTRLEN); + if(l < 0) USB_sendstr("ERROR: USB buffer overflow or string was too long\n"); + else if(l){ + const char *ans = parse_cmd(inbuff); + if(ans) USB_sendstr(ans); + } + } +} diff --git a/F3:F303/ADC/openocd.cfg b/F3:F303/ADC/openocd.cfg new file mode 100644 index 0000000..fe6fbb8 --- /dev/null +++ b/F3:F303/ADC/openocd.cfg @@ -0,0 +1,110 @@ +# script for stm32f3x family + +# +# stm32 devices support both JTAG and SWD transports. +# +source [find interface/stlink-v2-1.cfg] +source [find target/swj-dp.tcl] +source [find mem_helper.tcl] + +if { [info exists CHIPNAME] } { + set _CHIPNAME $CHIPNAME +} else { + set _CHIPNAME stm32f3x +} + +set _ENDIAN little + +# Work-area is a space in RAM used for flash programming +# By default use 16kB +if { [info exists WORKAREASIZE] } { + set _WORKAREASIZE $WORKAREASIZE +} else { + set _WORKAREASIZE 0x4000 +} + +# JTAG speed should be <= F_CPU/6. F_CPU after reset is 8MHz, so use F_JTAG = 1MHz +# +# Since we may be running of an RC oscilator, we crank down the speed a +# bit more to be on the safe side. Perhaps superstition, but if are +# running off a crystal, we can run closer to the limit. Note +# that there can be a pretty wide band where things are more or less stable. +adapter speed 1000 + +adapter srst delay 100 +if {[using_jtag]} { + jtag_ntrst_delay 100 +} + +#jtag scan chain +if { [info exists CPUTAPID] } { + set _CPUTAPID $CPUTAPID +} else { + if { [using_jtag] } { + # See STM Document RM0316 + # Section 29.6.3 - corresponds to Cortex-M4 r0p1 + set _CPUTAPID 0x4ba00477 + } { + set _CPUTAPID 0x2ba01477 + } +} + +swj_newdap $_CHIPNAME cpu -irlen 4 -ircapture 0x1 -irmask 0xf -expected-id $_CPUTAPID +dap create $_CHIPNAME.dap -chain-position $_CHIPNAME.cpu + +if {[using_jtag]} { + jtag newtap $_CHIPNAME bs -irlen 5 +} + +set _TARGETNAME $_CHIPNAME.cpu +target create $_TARGETNAME cortex_m -endian $_ENDIAN -dap $_CHIPNAME.dap + +$_TARGETNAME configure -work-area-phys 0x20000000 -work-area-size $_WORKAREASIZE -work-area-backup 0 + +set _FLASHNAME $_CHIPNAME.flash +flash bank $_FLASHNAME stm32f1x 0 0 0 0 $_TARGETNAME + +reset_config srst_nogate + +if {![using_hla]} { + # if srst is not fitted use SYSRESETREQ to + # perform a soft reset + cortex_m reset_config sysresetreq +} + +proc stm32f3x_default_reset_start {} { + # Reset clock is HSI (8 MHz) + adapter speed 1000 +} + +proc stm32f3x_default_examine_end {} { + # Enable debug during low power modes (uses more power) + mmw 0xe0042004 0x00000007 0 ;# DBGMCU_CR |= DBG_STANDBY | DBG_STOP | DBG_SLEEP + + # Stop watchdog counters during halt + mmw 0xe0042008 0x00001800 0 ;# DBGMCU_APB1_FZ |= DBG_IWDG_STOP | DBG_WWDG_STOP +} + +proc stm32f3x_default_reset_init {} { + # Configure PLL to boost clock to HSI x 8 (64 MHz) + mww 0x40021004 0x00380400 ;# RCC_CFGR = PLLMUL[3:1] | PPRE1[2] + mmw 0x40021000 0x01000000 0 ;# RCC_CR |= PLLON + mww 0x40022000 0x00000012 ;# FLASH_ACR = PRFTBE | LATENCY[1] + sleep 10 ;# Wait for PLL to lock + mmw 0x40021004 0x00000002 0 ;# RCC_CFGR |= SW[1] + + # Boost JTAG frequency + adapter speed 8000 +} + +# Default hooks +$_TARGETNAME configure -event examine-end { stm32f3x_default_examine_end } +$_TARGETNAME configure -event reset-start { stm32f3x_default_reset_start } +$_TARGETNAME configure -event reset-init { stm32f3x_default_reset_init } + +$_TARGETNAME configure -event trace-config { + # Set TRACE_IOEN; TRACE_MODE is set to async; when using sync + # change this value accordingly to configure trace pins + # assignment + mmw 0xe0042004 0x00000020 0 +} diff --git a/F3:F303/ADC/proto.c b/F3:F303/ADC/proto.c new file mode 100644 index 0000000..d3b64fa --- /dev/null +++ b/F3:F303/ADC/proto.c @@ -0,0 +1,115 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 +#include + +#include "adc.h" +#include "strfunc.h" +#include "usb.h" +#include "version.inc" + +//#define LOCBUFFSZ (32) +// local buffer for I2C data to send +//static uint8_t locBuffer[LOCBUFFSZ]; +extern volatile uint32_t Tms; +volatile uint8_t ADCmon = 0; + +const char *helpstring = + "https://github.com/eddyem/stm32samples/tree/master/F3:F303/I2C_scan build#" BUILD_NUMBER " @ " BUILD_DATE "\n" + "A - get ADC values\n" + "dx - change DAC current value to x\n" + "m - monitor ADC on/off\n" + "t - MCU temperature\n" + "T - print current Tms\n" + "v - Vdd\n" +; +/* +// read N numbers from buf, @return 0 if wrong or none +TRUE_INLINE uint16_t readNnumbers(const char *buf){ + uint32_t D; + const 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: "); USND(uhex2str(D&0xff)); USND("\n"); + } + USND("Send "); USND(u2str(N)); USND(" bytes\n"); + return N; +} +*/ + +TRUE_INLINE const char *DAC_chval(const char *buf){ + uint32_t D; + const char *nxt = getnum(buf, &D); + if(!nxt || nxt == buf || D > 4095) return "Wrong DAC amplitude\n"; + DAC1->DHR12R1 = D; + return "OK"; +} + +void printADCvals(){ + USB_sendstr("AIN0: "); USB_sendstr(u2str(getADCval(ADC_AIN0))); + USB_sendstr(" ("); USB_sendstr(float2str(getADCvoltage(ADC_AIN0), 2)); + USB_sendstr(" V)\nAIN1: "); USB_sendstr(u2str(getADCval(ADC_AIN1))); + USB_sendstr(" ("); USB_sendstr(float2str(getADCvoltage(ADC_AIN1), 2)); + USB_sendstr(" V)\nAIN5: "); USB_sendstr(u2str(getADCval(ADC_AIN5))); + USB_sendstr(" ("); USB_sendstr(float2str(getADCvoltage(ADC_AIN5), 2)); + USB_sendstr(" V)\nTS: "); + USB_sendstr(u2str(getADCval(ADC_TS))); + USB_sendstr("\nVREF: "); + USB_sendstr(u2str(getADCval(ADC_VREF))); + newline(); +} + +const char *parse_cmd(const char *buf){ + // "long" commands + switch(*buf){ + case 'd': + return DAC_chval(buf + 1); + break; + } + // "short" commands + if(buf[1]) return buf; // echo wrong data + switch(*buf){ + case 'A': + printADCvals(); + break; + case 'm': + ADCmon = !ADCmon; + USB_sendstr("Monitoring is "); + if(ADCmon) USB_sendstr("on\n"); + else USB_sendstr("off\n"); + break; + case 't': + return float2str(getMCUtemp(), 2); + break; + case 'T': + USB_sendstr("T="); + USB_sendstr(u2str(Tms)); + newline(); + break; + case 'v': + return float2str(getVdd(), 2); + break; + default: // help + USB_sendstr(helpstring); + break; + } + return NULL; +} diff --git a/F3:F303/ADC/proto.h b/F3:F303/ADC/proto.h new file mode 100644 index 0000000..d4a73e9 --- /dev/null +++ b/F3:F303/ADC/proto.h @@ -0,0 +1,25 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 + +extern volatile uint8_t ADCmon; +char *parse_cmd(char *buf); +void printADCvals(); diff --git a/F3:F303/ADC/ringbuffer.c b/F3:F303/ADC/ringbuffer.c new file mode 100644 index 0000000..2a90a65 --- /dev/null +++ b/F3:F303/ADC/ringbuffer.c @@ -0,0 +1,124 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 "ringbuffer.h" + +// stored data length +int RB_datalen(ringbuffer *b){ + if(b->tail >= b->head) return (b->tail - b->head); + else return (b->length - b->head + b->tail); +} + +/** + * @brief RB_hasbyte - check if buffer has given byte stored + * @param b - buffer + * @param byte - byte to find + * @return index if found, -1 if none + */ +int RB_hasbyte(ringbuffer *b, uint8_t byte){ + if(b->head == b->tail) return -1; // no data in buffer + int startidx = b->head; + if(b->head > b->tail){ // + for(int found = b->head; found < b->length; ++found) + if(b->data[found] == byte) return found; + startidx = 0; + } + for(int found = startidx; found < b->tail; ++found) + if(b->data[found] == byte) return found; + return -1; +} + +// poor memcpy +static void mcpy(uint8_t *targ, const uint8_t *src, int l){ + while(l--) *targ++ = *src++; +} + +// increment head or tail +TRUE_INLINE void incr(ringbuffer *b, volatile int *what, int n){ + *what += n; + if(*what >= b->length) *what -= b->length; +} + +/** + * @brief RB_read - read data from ringbuffer + * @param b - buffer + * @param s - array to write data + * @param len - max len of `s` + * @return bytes read + */ +int RB_read(ringbuffer *b, uint8_t *s, int len){ + int l = RB_datalen(b); + if(!l) return 0; + if(l > len) l = len; + int _1st = b->length - b->head; + if(_1st > l) _1st = l; + if(_1st > len) _1st = len; + mcpy(s, b->data + b->head, _1st); + if(_1st < len && l > _1st){ + mcpy(s+_1st, b->data, l - _1st); + incr(b, &b->head, l); + return l; + } + incr(b, &b->head, _1st); + return _1st; +} + +/** + * @brief RB_readto fill array `s` with data until byte `byte` (with it) + * @param b - ringbuffer + * @param byte - check byte + * @param s - buffer to write data + * @param len - length of `s` + * @return amount of bytes written (negative, if lenhead; + // now calculate length of new data portion + if(idx < b->head) partlen += b->length; + if(partlen > len) return -RB_read(b, s, len); + return RB_read(b, s, partlen); +} + +/** + * @brief RB_write - write some data to ringbuffer + * @param b - buffer + * @param str - data + * @param l - length + * @return amount of bytes written + */ +int RB_write(ringbuffer *b, const uint8_t *str, int l){ + int r = b->length - 1 - RB_datalen(b); // rest length + if(l > r) l = r; + if(!l) return 0; + int _1st = b->length - b->tail; + if(_1st > l) _1st = l; + mcpy(b->data + b->tail, str, _1st); + if(_1st < l){ // add another piece from start + mcpy(b->data, str+_1st, l-_1st); + } + incr(b, &b->tail, l); + return l; +} + +// just delete all information in buffer `b` +void RB_clearbuf(ringbuffer *b){ + b->head = 0; + b->tail = 0; +} diff --git a/F3:F303/ADC/ringbuffer.h b/F3:F303/ADC/ringbuffer.h new file mode 100644 index 0000000..fbf6c14 --- /dev/null +++ b/F3:F303/ADC/ringbuffer.h @@ -0,0 +1,35 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 + +typedef struct{ + uint8_t *data; // data buffer + const int length; // its length + int head; // head index + int tail; // tail index +} ringbuffer; + +int RB_read(ringbuffer *b, uint8_t *s, int len); +int RB_readto(ringbuffer *b, uint8_t byte, uint8_t *s, int len); +int RB_hasbyte(ringbuffer *b, uint8_t byte); +int RB_write(ringbuffer *b, const uint8_t *str, int l); +int RB_datalen(ringbuffer *b); +void RB_clearbuf(ringbuffer *b); diff --git a/F3:F303/ADC/strfunc.c b/F3:F303/ADC/strfunc.c new file mode 100644 index 0000000..4845ce6 --- /dev/null +++ b/F3:F303/ADC/strfunc.c @@ -0,0 +1,343 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 +#include +#include +/** + * @brief hexdump - dump hex array by 16 bytes in string + * @param sendfun - function to send data + * @param arr - array to dump + * @param len - length of `arr` + */ +void hexdump(int (*sendfun)(const char *s), 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; + sendfun(buf); + bptr = buf; + }else *bptr++ = ' '; + } + if(bptr != buf){ + *bptr++ = '\n'; + *bptr = 0; + sendfun(buf); + } +} + +/** + * @brief _2str - convert value into string buffer + * @param val - |value| + * @param minus - ==0 if value > 0 + * @return buffer with number + */ +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){ + uint32_t x = val / 10; + *(--bufptr) = (val - 10*x) + '0'; + val = x; + //*(--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); +} + +/** + * @brief uhex2str - print 32bit unsigned int as hex + * @param val - value + * @return string with number + */ +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; +} + +/** + * @brief omit_spaces - eliminate leading spaces and other trash in string + * @param buf - string + * @return - pointer to first character in `buf` > ' ' + */ +const char *omit_spaces(const char *buf){ + while(*buf){ + if(*buf > ' ') break; + ++buf; + } + return buf; +} + +/** + * @brief getdec - read decimal number & return pointer to next non-number symbol + * @param buf - string + * @param N - number read + * @return Next non-number symbol. In case of overflow return `buf` and N==0xffffffff + */ +static const 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 buf; +} +// read hexadecimal number (without 0x prefix!) +static const char *gethex(const char *buf, uint32_t *N){ + const char *start = 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 buf; +} +// read octal number (without 0 prefix!) +static const char *getoct(const char *buf, uint32_t *N){ + const 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 buf; +} +// read binary number (without b prefix!) +static const char *getbin(const char *buf, uint32_t *N){ + const 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 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) + */ +const char *getnum(const char *txt, uint32_t *N){ + const char *nxt = NULL; + const 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; +} + +// get signed integer +const char *getint(const char *txt, int32_t *I){ + const char *s = omit_spaces(txt); + int32_t sign = 1; + uint32_t U; + if(*s == '-'){ + sign = -1; + ++s; + } + const char *nxt = getnum(s, &U); + if(nxt == s) return txt; + if(U & 0x80000000) return txt; // overfull + *I = sign * (int32_t)U; + return nxt; +} + +/* +void mymemcpy(char *dest, const char *src, int len){ + if(len < 1) return; + while(len--) *dest++ = *src++; +} +*/ + +// be careful: if pow10 would be bigger you should change str[] size! +static const float pwr10[] = {1.f, 10.f, 100.f, 1000.f, 10000.f}; +static const float rounds[] = {0.5f, 0.05f, 0.005f, 0.0005f, 0.00005f}; +#define P10L (sizeof(pwr10)/sizeof(uint32_t) - 1) +char * float2str(float x, uint8_t prec){ + static char str[16] = {0}; // -117.5494E-36\0 - 14 symbols max! + if(prec > P10L) prec = P10L; + if(isnan(x)){ memcpy(str, "NAN", 4); return str;} + else{ + int i = isinf(x); + if(i){memcpy(str, "-INF", 5); if(i == 1) return str+1; else return str;} + } + char *s = str + 14; // go to end of buffer + uint8_t minus = 0; + if(x < 0){ + x = -x; + minus = 1; + } + int pow = 0; // xxxEpow + // now convert float to 1.xxxE3y + while(x > 1000.f){ + x /= 1000.f; + pow += 3; + } + if(x > 0.) while(x < 1.){ + x *= 1000.f; + pow -= 3; + } + // print Eyy + if(pow){ + uint8_t m = 0; + if(pow < 0){pow = -pow; m = 1;} + while(pow){ + register int p10 = pow/10; + *s-- = '0' + (pow - 10*p10); + pow = p10; + } + if(m) *s-- = '-'; + *s-- = 'E'; + } + // now our number is in [1, 1000] + uint32_t units; + if(prec){ + units = (uint32_t) x; + uint32_t decimals = (uint32_t)((x-units+rounds[prec])*pwr10[prec]); + // print decimals + while(prec){ + register int d10 = decimals / 10; + *s-- = '0' + (decimals - 10*d10); + decimals = d10; + --prec; + } + // decimal point + *s-- = '.'; + }else{ // without decimal part + units = (uint32_t) (x + 0.5); + } + // print main units + if(units == 0) *s-- = '0'; + else while(units){ + register uint32_t u10 = units / 10; + *s-- = '0' + (units - 10*u10); + units = u10; + } + if(minus) *s-- = '-'; + return s+1; +} diff --git a/F3:F303/ADC/strfunc.h b/F3:F303/ADC/strfunc.h new file mode 100644 index 0000000..44f893e --- /dev/null +++ b/F3:F303/ADC/strfunc.h @@ -0,0 +1,32 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 + +void hexdump(int (*sendfun)(const char *s), uint8_t *arr, uint16_t len); +const char *u2str(uint32_t val); +const char *i2str(int32_t i); +const char *uhex2str(uint32_t val); +const char *getnum(const char *txt, uint32_t *N); +const char *omit_spaces(const char *buf); +const char *getint(const char *txt, int32_t *I); +//void mymemcpy(char *dest, const char *src, int len); +char * float2str(float x, uint8_t prec); diff --git a/F3:F303/ADC/usb.c b/F3:F303/ADC/usb.c new file mode 100644 index 0000000..e36a8a6 --- /dev/null +++ b/F3:F303/ADC/usb.c @@ -0,0 +1,176 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 + +#include "hardware.h" +#include "ringbuffer.h" +#include "usb.h" +#include "usb_lib.h" + +static volatile uint8_t usbbuff[USB_TXBUFSZ]; // temporary buffer for sending data +// ring buffers for incoming and outgoing data +static uint8_t obuf[RBOUTSZ], ibuf[RBINSZ]; +static volatile ringbuffer out = {.data = obuf, .length = RBOUTSZ, .head = 0, .tail = 0}; +static volatile ringbuffer in = {.data = ibuf, .length = RBINSZ, .head = 0, .tail = 0}; +// transmission is succesfull +static volatile uint8_t bufisempty = 1; +static volatile uint8_t bufovrfl = 0; + +static void send_next(){ + if(bufisempty) return; + static int lastdsz = 0; + int buflen = RB_read((ringbuffer*)&out, (uint8_t*)usbbuff, USB_TXBUFSZ); + if(!buflen){ + if(lastdsz == 64) EP_Write(3, NULL, 0); // send ZLP after 64 bits packet when nothing more to send + lastdsz = 0; + bufisempty = 1; + return; + } + EP_Write(3, (uint8_t*)usbbuff, buflen); + lastdsz = buflen; +} + +// blocking send full content of ring buffer +int USB_sendall(){ + while(!bufisempty){ + if(!usbON) return 0; + } + return 1; +} + +// put `buf` into queue to send +int USB_send(const uint8_t *buf, int len){ + if(!buf || !usbON || !len) return 0; + while(len){ + int a = RB_write((ringbuffer*)&out, buf, len); + len -= a; + buf += a; + if(bufisempty){ + bufisempty = 0; + send_next(); + } + } + return 1; +} + +int USB_putbyte(uint8_t byte){ + if(!usbON) return 0; + while(0 == RB_write((ringbuffer*)&out, &byte, 1)){ + if(bufisempty){ + bufisempty = 0; + send_next(); + } + } + return 1; +} + +int USB_sendstr(const char *string){ + if(!string || !usbON) return 0; + int len = 0; + const char *b = string; + while(*b++) ++len; + if(!len) return 0; + return USB_send((const uint8_t*)string, len); +} + +/** + * @brief USB_receive - get binary data from receiving ring-buffer + * @param buf (i) - buffer for received data + * @param len - length of `buf` + * @return amount of received bytes (negative, if overfull happened) + */ +int USB_receive(uint8_t *buf, int len){ + int sz = RB_read((ringbuffer*)&in, buf, len); + if(bufovrfl){ + RB_clearbuf((ringbuffer*)&in); + if(!sz) sz = -1; + else sz = -sz; + bufovrfl = 0; + } + return sz; +} + +/** + * @brief USB_receivestr - get string up to '\n' and replace '\n' with 0 + * @param buf - receiving buffer + * @param len - its length + * @return strlen or negative value indicating overflow (if so, string won't be ends with 0 and buffer should be cleared) + */ +int USB_receivestr(char *buf, int len){ + int l = RB_readto((ringbuffer*)&in, '\n', (uint8_t*)buf, len); + if(l == 0) return 0; + if(l < 1 || bufovrfl) RB_clearbuf((ringbuffer*)&in); + else buf[l-1] = 0; // replace '\n' with strend + if(bufovrfl){ + if(l > 0) l = -l; + else l = -1; + bufovrfl = 0; + } + return l; +} + +// 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 + 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 + send_next(); +} + +static void receive_Handler(){ // EP2OUT + uint8_t buf[USB_RXBUFSZ]; + uint16_t epstatus = KEEP_DTOG(USB->EPnR[2]); + uint8_t sz = EP_Read(2, (uint16_t*)buf); + if(sz){ + if(RB_write((ringbuffer*)&in, buf, sz) != sz) bufovrfl = 1; + } + // keep stat_tx & set ACK rx, clear RX ctr + USB->EPnR[2] = (epstatus & ~USB_EPnR_CTR_RX) ^ USB_EPnR_STAT_RX; +} + +void USB_proc(){ + 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; + } +} diff --git a/F3:F303/ADC/usb.h b/F3:F303/ADC/usb.h new file mode 100644 index 0000000..626cffe --- /dev/null +++ b/F3:F303/ADC/usb.h @@ -0,0 +1,35 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 "usbhw.h" + +// sizes of ringbuffers for outgoing and incoming data +#define RBOUTSZ (512) +#define RBINSZ (512) + +#define newline() USB_putbyte('\n') + +void USB_proc(); +int USB_sendall(); +int USB_send(const uint8_t *buf, int len); +int USB_putbyte(uint8_t byte); +int USB_sendstr(const char *string); +int USB_receive(uint8_t *buf, int len); +int USB_receivestr(char *buf, int len); diff --git a/F3:F303/ADC/usb_lib.c b/F3:F303/ADC/usb_lib.c new file mode 100644 index 0000000..a016cab --- /dev/null +++ b/F3:F303/ADC/usb_lib.c @@ -0,0 +1,389 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 +#include "usb_lib.h" + +ep_t endpoints[STM32ENDPOINTS]; + +usb_dev_t USB_Dev; +static usb_LineCoding lineCoding = {115200, 0, 0, 8}; +config_pack_t setup_packet; +uint8_t ep0databuf[EP0DATABUF_SIZE]; +uint8_t ep0dbuflen = 0; + +usb_LineCoding getLineCoding(){return lineCoding;} + +volatile uint8_t usbON = 0; // device disconnected from terminal + +// 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){ + uint16_t c; + if(packet->bmRequestType & 0x80){ // read + switch(packet->wValue){ + case 0x8484: + c = 2; + break; + case 0x0080: + c = 1; + break; + case 0x8686: + c = 0xaa; + break; + default: + c = 0; + } + EP_WriteIRQ(0, (uint8_t*)&c, 1); + }else{ // write ZLP + c = 0; + EP_WriteIRQ(0, (uint8_t *)&c, 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 uint16_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, (uint8_t*)&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 + */ +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; +} + +/** + * 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; + uint32_t *out = (uint32_t *)endpoints[number].tx_buf; + for(i = 0; i < N2; ++i, ++out){ + *out = 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, uint16_t *buf){ + int sz = endpoints[number].rx_cnt; + if(!sz) return 0; + endpoints[number].rx_cnt = 0; + int n = (sz + 1) >> 1; + uint32_t *in = (uint32_t *)endpoints[number].rx_buf; + if(n){ + for(int i = 0; i < n; ++i, ++in) + buf[i] = *(uint16_t*)in; + } + return sz; +} + diff --git a/F3:F303/ADC/usb_lib.h b/F3:F303/ADC/usb_lib.h new file mode 100644 index 0000000..3b86022 --- /dev/null +++ b/F3:F303/ADC/usb_lib.h @@ -0,0 +1,182 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 "usbhw.h" + +#define EP0DATABUF_SIZE (64) +#define LASTADDR_DEFAULT (STM32ENDPOINTS * 8) + +// 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 +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 + uint16_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 volatile uint8_t usbON; +extern config_pack_t setup_packet; +extern uint8_t ep0databuf[]; +extern uint8_t ep0dbuflen; + +void EP0_Handler(); + +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, uint16_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); diff --git a/F3:F303/ADC/usbhw.c b/F3:F303/ADC/usbhw.c new file mode 100644 index 0000000..b48bd73 --- /dev/null +++ b/F3:F303/ADC/usbhw.c @@ -0,0 +1,137 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 "usb.h" +#include "usb_lib.h" + +void USB_setup(){ + NVIC_DisableIRQ(USB_LP_IRQn); + // remap USB LP & Wakeup interrupts to 75 and 76 - works only on pure F303 + RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN; // enable tacting of SYSCFG + SYSCFG->CFGR1 |= SYSCFG_CFGR1_USB_IT_RMP; + // setup pullup + RCC->AHBENR |= RCC_AHBENR_GPIOAEN; + USBPU_OFF(); + //GPIOA->MODER = (GPIOA->MODER & ~(GPIO_MODER_MODER15_Msk | GPIO_MODER_MODER11_Msk | GPIO_MODER_MODER12_Msk)) | + GPIOA->MODER = (GPIOA->MODER & (MODER_CLR(11) & MODER_CLR(12) & MODER_CLR(15))) | + (MODER_AF(11) | MODER_AF(12) | MODER_O(15)); + //(GPIO_MODER_MODER11_AF | GPIO_MODER_MODER12_AF | GPIO_MODER_MODER15_O); + // USB - alternate function 14 @ pins PA11/PA12 + GPIOA->AFR[1] = (GPIOA->AFR[1] & ~(GPIO_AFRH_AFRH3_Msk | GPIO_AFRH_AFRH4_Msk)) | + //AFR1(14, 11) | AFR1(14, 12); + AFRf(14, 11) | AFRf(14, 12); + RCC->APB1ENR |= RCC_APB1ENR_USBEN; + USB->CNTR = USB_CNTR_FRES; // Force USB Reset + for(uint32_t ctr = 0; ctr < 72000; ++ctr) nop(); // wait >1ms + //uint32_t ctr = 0; + USB->CNTR = 0; + USB->BTABLE = 0; + USB->DADDR = 0; + USB->ISTR = 0; + USB->CNTR = USB_CNTR_RESETM | USB_CNTR_WKUPM; // allow only wakeup & reset interrupts + NVIC_EnableIRQ(USB_LP_IRQn); + USBPU_ON(); +} + +static uint16_t lastaddr = LASTADDR_DEFAULT; +/** + * Endpoint initialisation + * @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)(ep_t ep)){ + 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 > 512) 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*2); + 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 = (uint16_t *)(USB_BTABLE_BASE + lastaddr*2); + lastaddr += rxsz; + USB_BTABLE->EP[number].USB_COUNT_RX = countrx << 10; + endpoints[number].func = func; + return 0; +} + +// standard IRQ handler +void usb_lp_isr(){ + if(USB->ISTR & USB_ISTR_RESET){ + usbON = 0; + // Reinit registers + USB->CNTR = USB_CNTR_RESETM | USB_CNTR_CTRM | USB_CNTR_SUSPM | USB_CNTR_WKUPM; + // Endpoint 0 - CONTROL + // ON USB LS size of EP0 may be 8 bytes, but on FS it should be 64 bytes! + lastaddr = LASTADDR_DEFAULT; + // clear address, leave only enable bit + USB->DADDR = USB_DADDR_EF; + USB_Dev.USB_Status = USB_STATE_DEFAULT; + if(EP_Init(0, EP_TYPE_CONTROL, USB_EP0_BUFSZ, USB_EP0_BUFSZ, EP0_Handler)){ + return; + } + USB->ISTR = ~USB_ISTR_RESET; + } + 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, (uint16_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, (uint16_t*)&ep0databuf); + } + } + } + // call EP handler + if(endpoints[n].func) endpoints[n].func(endpoints[n]); + } + if(USB->ISTR & USB_ISTR_SUSP){ // suspend -> still no connection, may sleep + usbON = 0; + USB->CNTR |= USB_CNTR_FSUSP | USB_CNTR_LP_MODE; + USB->ISTR = ~USB_ISTR_SUSP; + } + if(USB->ISTR & USB_ISTR_WKUP){ // wakeup + USB->CNTR &= ~(USB_CNTR_FSUSP | USB_CNTR_LP_MODE); // clear suspend flags + USB->ISTR = ~USB_ISTR_WKUP; + } +} + diff --git a/F3:F303/ADC/usbhw.h b/F3:F303/ADC/usbhw.h new file mode 100644 index 0000000..c6baf3d --- /dev/null +++ b/F3:F303/ADC/usbhw.h @@ -0,0 +1,103 @@ +/* + * This file is part of the adc project. + * Copyright 2023 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 USBPU_port GPIOA +#define USBPU_pin (1<<15) +#define USBPU_ON() pin_clear(USBPU_port, USBPU_pin) +#define USBPU_OFF() pin_set(USBPU_port, USBPU_pin) + +// max endpoints number +#define STM32ENDPOINTS 8 +/** + * Buffers size definition + **/ +#define USB_BTABLE_SIZE 512 +// 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 +// EP1 - interrupt - buffer size +#define USB_EP1BUFSZ 8 + +#define USB_BTABLE_BASE 0x40006000 +#define USB ((USB_TypeDef *) USB_BASE) + +#ifdef USB_BTABLE +#undef USB_BTABLE +#endif +#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; +} USB_TypeDef; + +typedef struct{ + __IO uint32_t USB_ADDR_TX; + __IO uint32_t USB_COUNT_TX; + __IO uint32_t USB_ADDR_RX; + __IO uint32_t USB_COUNT_RX; +} USB_EPDATA_TypeDef; + +typedef struct{ + __IO USB_EPDATA_TypeDef EP[STM32ENDPOINTS]; +} USB_BtableDef; + +void USB_setup(); +int EP_Init(uint8_t number, uint8_t type, uint16_t txsz, uint16_t rxsz, void (*func)()); diff --git a/F3:F303/ADC/version.inc b/F3:F303/ADC/version.inc new file mode 100644 index 0000000..f4257ec --- /dev/null +++ b/F3:F303/ADC/version.inc @@ -0,0 +1,2 @@ +#define BUILD_NUMBER "10" +#define BUILD_DATE "2023-01-23" diff --git a/F3:F303/PL2303/openocd.cfg b/F3:F303/PL2303/openocd.cfg new file mode 100644 index 0000000..56ccc2e --- /dev/null +++ b/F3:F303/PL2303/openocd.cfg @@ -0,0 +1,119 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +# script for stm32f3x family + +# +# stm32 devices support both JTAG and SWD transports. +# +source [find interface/stlink-v2-1.cfg] +source [find target/swj-dp.tcl] +source [find mem_helper.tcl] + +if { [info exists CHIPNAME] } { + set _CHIPNAME $CHIPNAME +} else { + set _CHIPNAME stm32f3x +} + +set _ENDIAN little + +# Work-area is a space in RAM used for flash programming +# By default use 16kB +if { [info exists WORKAREASIZE] } { + set _WORKAREASIZE $WORKAREASIZE +} else { + set _WORKAREASIZE 0x4000 +} + +# JTAG speed should be <= F_CPU/6. F_CPU after reset is 8MHz, so use F_JTAG = 1MHz +# +# Since we may be running of an RC oscilator, we crank down the speed a +# bit more to be on the safe side. Perhaps superstition, but if are +# running off a crystal, we can run closer to the limit. Note +# that there can be a pretty wide band where things are more or less stable. +adapter speed 1000 + +adapter srst delay 100 +if {[using_jtag]} { + jtag_ntrst_delay 100 +} + +#jtag scan chain +if { [info exists CPUTAPID] } { + set _CPUTAPID $CPUTAPID +} else { + if { [using_jtag] } { + # See STM Document RM0316 + # Section 29.6.3 - corresponds to Cortex-M4 r0p1 + set _CPUTAPID 0x4ba00477 + } { + set _CPUTAPID 0x2ba01477 + } +} + +swj_newdap $_CHIPNAME cpu -irlen 4 -ircapture 0x1 -irmask 0xf -expected-id $_CPUTAPID +dap create $_CHIPNAME.dap -chain-position $_CHIPNAME.cpu + +if {[using_jtag]} { + jtag newtap $_CHIPNAME bs -irlen 5 +} + +set _TARGETNAME $_CHIPNAME.cpu +target create $_TARGETNAME cortex_m -endian $_ENDIAN -dap $_CHIPNAME.dap + +$_TARGETNAME configure -work-area-phys 0x20000000 -work-area-size $_WORKAREASIZE -work-area-backup 0 + +set _FLASHNAME $_CHIPNAME.flash +flash bank $_FLASHNAME stm32f1x 0 0 0 0 $_TARGETNAME + +reset_config srst_nogate + +if {![using_hla]} { + # if srst is not fitted use SYSRESETREQ to + # perform a soft reset + cortex_m reset_config sysresetreq +} + +proc stm32f3x_default_reset_start {} { + # Reset clock is HSI (8 MHz) + adapter speed 1000 +} + +proc stm32f3x_default_examine_end {} { + # Enable debug during low power modes (uses more power) + mmw 0xe0042004 0x00000007 0 ;# DBGMCU_CR |= DBG_STANDBY | DBG_STOP | DBG_SLEEP + + # Stop watchdog counters during halt + mmw 0xe0042008 0x00001800 0 ;# DBGMCU_APB1_FZ |= DBG_IWDG_STOP | DBG_WWDG_STOP +} + +proc stm32f3x_default_reset_init {} { + # Configure PLL to boost clock to HSI x 8 (64 MHz) + mww 0x40021004 0x00380400 ;# RCC_CFGR = PLLMUL[3:1] | PPRE1[2] + mmw 0x40021000 0x01000000 0 ;# RCC_CR |= PLLON + mww 0x40022000 0x00000012 ;# FLASH_ACR = PRFTBE | LATENCY[1] + sleep 10 ;# Wait for PLL to lock + mmw 0x40021004 0x00000002 0 ;# RCC_CFGR |= SW[1] + + # Boost JTAG frequency + adapter speed 8000 +} + +# Default hooks +$_TARGETNAME configure -event examine-end { stm32f3x_default_examine_end } +$_TARGETNAME configure -event reset-start { stm32f3x_default_reset_start } +$_TARGETNAME configure -event reset-init { stm32f3x_default_reset_init } + +tpiu create $_CHIPNAME.tpiu -dap $_CHIPNAME.dap -ap-num 0 -baseaddr 0xE0040000 + +lappend _telnet_autocomplete_skip _proc_pre_enable_$_CHIPNAME.tpiu +proc _proc_pre_enable_$_CHIPNAME.tpiu {_targetname} { + targets $_targetname + + # Set TRACE_IOEN; TRACE_MODE is set to async; when using sync + # change this value accordingly to configure trace pins + # assignment + mmw 0xe0042004 0x00000020 0 +} + +$_CHIPNAME.tpiu configure -event pre-enable "_proc_pre_enable_$_CHIPNAME.tpiu $_TARGETNAME" diff --git a/F3:F303/USB_template/openocd.cfg b/F3:F303/USB_template/openocd.cfg new file mode 100644 index 0000000..56ccc2e --- /dev/null +++ b/F3:F303/USB_template/openocd.cfg @@ -0,0 +1,119 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +# script for stm32f3x family + +# +# stm32 devices support both JTAG and SWD transports. +# +source [find interface/stlink-v2-1.cfg] +source [find target/swj-dp.tcl] +source [find mem_helper.tcl] + +if { [info exists CHIPNAME] } { + set _CHIPNAME $CHIPNAME +} else { + set _CHIPNAME stm32f3x +} + +set _ENDIAN little + +# Work-area is a space in RAM used for flash programming +# By default use 16kB +if { [info exists WORKAREASIZE] } { + set _WORKAREASIZE $WORKAREASIZE +} else { + set _WORKAREASIZE 0x4000 +} + +# JTAG speed should be <= F_CPU/6. F_CPU after reset is 8MHz, so use F_JTAG = 1MHz +# +# Since we may be running of an RC oscilator, we crank down the speed a +# bit more to be on the safe side. Perhaps superstition, but if are +# running off a crystal, we can run closer to the limit. Note +# that there can be a pretty wide band where things are more or less stable. +adapter speed 1000 + +adapter srst delay 100 +if {[using_jtag]} { + jtag_ntrst_delay 100 +} + +#jtag scan chain +if { [info exists CPUTAPID] } { + set _CPUTAPID $CPUTAPID +} else { + if { [using_jtag] } { + # See STM Document RM0316 + # Section 29.6.3 - corresponds to Cortex-M4 r0p1 + set _CPUTAPID 0x4ba00477 + } { + set _CPUTAPID 0x2ba01477 + } +} + +swj_newdap $_CHIPNAME cpu -irlen 4 -ircapture 0x1 -irmask 0xf -expected-id $_CPUTAPID +dap create $_CHIPNAME.dap -chain-position $_CHIPNAME.cpu + +if {[using_jtag]} { + jtag newtap $_CHIPNAME bs -irlen 5 +} + +set _TARGETNAME $_CHIPNAME.cpu +target create $_TARGETNAME cortex_m -endian $_ENDIAN -dap $_CHIPNAME.dap + +$_TARGETNAME configure -work-area-phys 0x20000000 -work-area-size $_WORKAREASIZE -work-area-backup 0 + +set _FLASHNAME $_CHIPNAME.flash +flash bank $_FLASHNAME stm32f1x 0 0 0 0 $_TARGETNAME + +reset_config srst_nogate + +if {![using_hla]} { + # if srst is not fitted use SYSRESETREQ to + # perform a soft reset + cortex_m reset_config sysresetreq +} + +proc stm32f3x_default_reset_start {} { + # Reset clock is HSI (8 MHz) + adapter speed 1000 +} + +proc stm32f3x_default_examine_end {} { + # Enable debug during low power modes (uses more power) + mmw 0xe0042004 0x00000007 0 ;# DBGMCU_CR |= DBG_STANDBY | DBG_STOP | DBG_SLEEP + + # Stop watchdog counters during halt + mmw 0xe0042008 0x00001800 0 ;# DBGMCU_APB1_FZ |= DBG_IWDG_STOP | DBG_WWDG_STOP +} + +proc stm32f3x_default_reset_init {} { + # Configure PLL to boost clock to HSI x 8 (64 MHz) + mww 0x40021004 0x00380400 ;# RCC_CFGR = PLLMUL[3:1] | PPRE1[2] + mmw 0x40021000 0x01000000 0 ;# RCC_CR |= PLLON + mww 0x40022000 0x00000012 ;# FLASH_ACR = PRFTBE | LATENCY[1] + sleep 10 ;# Wait for PLL to lock + mmw 0x40021004 0x00000002 0 ;# RCC_CFGR |= SW[1] + + # Boost JTAG frequency + adapter speed 8000 +} + +# Default hooks +$_TARGETNAME configure -event examine-end { stm32f3x_default_examine_end } +$_TARGETNAME configure -event reset-start { stm32f3x_default_reset_start } +$_TARGETNAME configure -event reset-init { stm32f3x_default_reset_init } + +tpiu create $_CHIPNAME.tpiu -dap $_CHIPNAME.dap -ap-num 0 -baseaddr 0xE0040000 + +lappend _telnet_autocomplete_skip _proc_pre_enable_$_CHIPNAME.tpiu +proc _proc_pre_enable_$_CHIPNAME.tpiu {_targetname} { + targets $_targetname + + # Set TRACE_IOEN; TRACE_MODE is set to async; when using sync + # change this value accordingly to configure trace pins + # assignment + mmw 0xe0042004 0x00000020 0 +} + +$_CHIPNAME.tpiu configure -event pre-enable "_proc_pre_enable_$_CHIPNAME.tpiu $_TARGETNAME"