start fixed F1 testboard for new board type

This commit is contained in:
Edward Emelianov 2022-12-27 20:54:43 +03:00
parent c152315922
commit c4ba010c17
34 changed files with 2678 additions and 272 deletions

View File

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

View File

@ -0,0 +1,6 @@
#define FAMILY F1
#define MCU F103xB
#define USARTNUM 1
#define STM32F1 1
#define STM32F103xB 1
#define DENSITY MD

View File

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

View File

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

View File

@ -0,0 +1,16 @@
Readme.md
adc.c
adc.h
hardware.c
hardware.h
main.c
pl2303.bin
proto.c
proto.h
usart.c
usart.h
usb.c
usb.h
usb_defs.h
usb_lib.c
usb_lib.h

View File

@ -0,0 +1,3 @@
.
../inc/cm
../inc/Fx

View File

@ -4,11 +4,11 @@ BOOTSPEED ?= 115200
# MCU FAMILY
FAMILY ?= F1
# MCU code
MCU ?= F103x8
MCU ?= F103x6
# density (stm32f10x.h, lines 70-84)
DENSITY ?= MD
DENSITY ?= LD
# change this linking script depending on particular MCU model,
LDSCRIPT ?= stm32f103x8.ld
LDSCRIPT ?= stm32f103x6.ld
# debug
#DEFS = -DEBUG

View File

@ -18,12 +18,6 @@
#include "adc.h"
/**
* @brief ADC_array - array for ADC channels with median filtering:
* 0 - Rvar
* 1 - internal Tsens
* 2 - Vref
*/
uint16_t ADC_array[NUMBER_OF_ADC_CHANNELS*9];
/**
@ -51,11 +45,19 @@ uint16_t getADCval(int nch){
#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(){
// Temp = (V25 - Vsense)/Avg_Slope + 25
// V_25 = 1.45V, Slope = 4.3e-3
int32_t Vsense = getVdd() * getADCval(1);
int32_t Vsense = getVdd() * getADCval(CHTSENS);
int32_t temperature = 593920 - Vsense; // 593920 == 145*4096
temperature /= 172; // == /(4096*10*4.3e-3), 10 - to convert from *100 to *10
temperature += 250;
@ -65,6 +67,6 @@ int32_t getMCUtemp(){
// return Vdd * 100 (V)
uint32_t getVdd(){
uint32_t vdd = 120 * 4096; // 1.2V
vdd /= getADCval(2);
vdd /= getADCval(CHVREF);
return vdd;
}

View File

@ -19,11 +19,25 @@
#define ADC_H
#include "stm32f1.h"
#define NUMBER_OF_ADC_CHANNELS (3)
#define NUMBER_OF_ADC_CHANNELS (5)
// channels for Tsens and Vref
#define CHTSENS (3)
#define CHVREF (4)
/**
* @brief ADC_array - array for ADC channels with median filtering:
* 0 - Rvar
* 1 - Rvar/2
* 2 - AIN5
* 3 - internal Tsens
* 4 - Vref
*/
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

@ -28,30 +28,80 @@
static inline void gpio_setup(){
// Enable clocks to the GPIO subsystems (PB for ADC), turn on AFIO clocking to disable SWD/JTAG
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPBEN | RCC_APB2ENR_AFIOEN;
// turn off SWJ/JTAG
AFIO->MAPR = AFIO_MAPR_SWJ_CFG_DISABLE;
AFIO->MAPR = AFIO_MAPR_SWJ_CFG_JTAGDISABLE; // for PA15
// turn off USB pullup
GPIOA->ODR = (1<<13)|(1<<14)|(1<<15); // turn off usb pullup & turn on pullups for buttons
// Set leds (PA0/PA4) as opendrain output
GPIOA->CRL = CRL(0, CNF_ODOUTPUT|MODE_SLOW) | CRL(4, CNF_ODOUTPUT|MODE_SLOW);
// Set buttons (PA14/15) as inputs with weak pullups, USB pullup (PA13) - opendrain output
GPIOA->CRH = CRH(13, CNF_ODOUTPUT|MODE_SLOW) | CRH(14, CNF_PUDINPUT|MODE_INPUT)
| CRH(15, CNF_PUDINPUT|MODE_INPUT);
GPIOA->ODR = (1<<15); // turn off usb pullup & turn on pullups for buttons
// Set LEDS (PA6-8, PB0/1) as Out & AF (PWM)
GPIOA->CRL = CRL(6, CNF_AFOD|MODE_NORMAL) | CRL(7, CNF_AFOD|MODE_NORMAL);
// USB pullup (PA15) - pushpull output
GPIOA->CRH = CRH(8, CNF_AFOD|MODE_NORMAL) | CRH(15, CNF_PPOUTPUT|MODE_SLOW);
GPIOB->CRL = CRL(0, CNF_AFOD|MODE_NORMAL) | CRL(1, CNF_AFOD|MODE_NORMAL);
}
static inline 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) */
}
// TIM3 - PWM @ all 4 channels. TIM1 - PWM @ ch1
static inline void tim1_setup(){
RCC->APB2ENR |= RCC_APB2ENR_TIM1EN; // enable TIM1 clocking
RCC->APB1ENR |= RCC_APB1ENR_TIM3EN;
TIM1->PSC = 8; // 72/9 = 8MHz
TIM3->PSC = 8;
// ARR for 8-bit PWM
TIM1->ARR = 255; // 100 ticks for 80kHz
TIM3->ARR = 255;
TIM1->CCR1 = 127; // 50%
TIM3->CCR1 = 63; TIM3->CCR2 = 127; TIM3->CCR3 = 191; TIM3->CCR4 = 250;
// PWM mode 2
TIM1->CCMR1 = TIM_CCMR1_OC1M;
TIM3->CCMR1 = TIM_CCMR1_OC1M | TIM_CCMR1_OC2M;
TIM3->CCMR2 = TIM_CCMR2_OC3M | TIM_CCMR2_OC4M;
// main output
TIM1->BDTR = TIM_BDTR_MOE;
TIM3->BDTR |= TIM_BDTR_MOE;
// main PWM output
TIM1->CCER = TIM_CCER_CC1E;
TIM3->CCER = TIM_CCER_CC1E | TIM_CCER_CC2E | TIM_CCER_CC3E | TIM_CCER_CC4E;
// turn it on
TIM1->CR1 = TIM_CR1_CEN;// | TIM_CR1_ARPE;
TIM3->CR1 |= TIM_CR1_CEN;
TIM1->EGR |= TIM_EGR_UG; // generate update event to refresh all
TIM3->EGR |= TIM_EGR_UG;
}
static inline void adc_setup(){
GPIOB->CRL |= CRL(0, CNF_ANALOG|MODE_INPUT);
GPIOA->CRL |= CRL(0, CNF_ANALOG|MODE_INPUT) | CRL(1, CNF_ANALOG|MODE_INPUT) | CRL(5, CNF_ANALOG|MODE_INPUT);
uint32_t ctr = 0;
// Enable clocking
RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;
RCC->CFGR &= ~(RCC_CFGR_ADCPRE);
RCC->CFGR |= RCC_CFGR_ADCPRE_DIV8; // ADC clock = RCC / 8
// sampling time - 239.5 cycles for channels 8, 16 and 17
ADC1->SMPR2 = ADC_SMPR2_SMP8;
// sampling time - 239.5 cycles for channels 0, 1, 5, 16 and 17
ADC1->SMPR2 = ADC_SMPR2_SMP0 | ADC_SMPR2_SMP1 | ADC_SMPR2_SMP5;
ADC1->SMPR1 = ADC_SMPR1_SMP16 | ADC_SMPR1_SMP17;
// we have three conversions in group -> ADC1->SQR1[L] = 2, order: 8->16->17
ADC1->SQR3 = 8 | (16<<5) | (17<<10);
ADC1->SQR1 = ADC_SQR1_L_1;
// sequence order: 0 -> 1 -> 5 -> 16 -> 17
ADC1->SQR3 = 0 | (1<<5) | (5<<10) | (16<<15) | (17<<20);
ADC1->SQR1 = (NUMBER_OF_ADC_CHANNELS - 1) << 20; // amount of conversions
ADC1->CR1 |= ADC_CR1_SCAN; // scan mode
// DMA configuration
RCC->AHBENR |= RCC_AHBENR_DMA1EN;
@ -76,4 +126,6 @@ static inline void adc_setup(){
void hw_setup(){
gpio_setup();
adc_setup();
tim1_setup();
iwdg_setup();
}

View File

@ -24,30 +24,32 @@
#ifndef __HARDWARE_H__
#define __HARDWARE_H__
#include "stm32f1.h"
#include <stm32f1.h>
// LEDS: 0 - PA0, 1 - PA4
// LED0 - blinking each second
#define LED0_port GPIOA
#define LED0_pin (1<<0)
// LED1 - PWM
#define LED1_port GPIOA
#define LED1_pin (1<<4)
#if 0
#ifndef CONCAT
#define CONCAT(a,b) a ## b
#endif
#ifndef STR_HELPER
#define STR_HELPER(s) #s
#endif
#ifndef STR
#define STR(s) STR_HELPER(s)
#endif
// Buttons' state: PA14 (1)/PA15 (0)
#define GET_BTN0() ((GPIOA->IDR & (1<<15)) ? 0 : 1)
#define GET_BTN1() ((GPIOA->IDR & (1<<14)) ? 0 : 1)
// 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)
#endif
// USB pullup (not used in STM32F0x2!) - PA13
#define USBPU_port GPIOA
#define USBPU_pin (1<<13)
#define USBPU_pin (1<<15)
#define USBPU_ON() pin_clear(USBPU_port, USBPU_pin)
#define USBPU_OFF() pin_set(USBPU_port, USBPU_pin)
#define LED_blink(x) pin_toggle(x ## _port, x ## _pin)
#define LED_on(x) pin_clear(x ## _port, x ## _pin)
#define LED_off(x) pin_set(x ## _port, x ## _pin)
void hw_setup();
#endif // __HARDWARE_H__

View File

@ -21,10 +21,14 @@
#include "adc.h"
#include "hardware.h"
#include "proto.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 */
@ -32,123 +36,11 @@ void sys_tick_handler(void){
++Tms;
}
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) */
}
volatile uint8_t ADCmon = 0; // ==1 to monitor ADC (change PWM of LEDS & show current value)
uint16_t oldADCval = 0;
#define USND(str) do{USB_send((uint8_t*)str, sizeof(str)-1);}while(0)
char *parse_cmd(char *buf){
static char btns[] = "BTN0=0, BTN1=0\n";
if(buf[1] != '\n') return buf;
switch(*buf){
case '0':
pin_set(GPIOA, 1<<4);
break;
case '1':
pin_clear(GPIOA, 1<<4);
break;
case 'b':
btns[5] = GET_BTN0() + '0';
btns[13] = GET_BTN1() + '0';
return btns;
break;
case 'p':
pin_toggle(USBPU_port, USBPU_pin);
SEND("USB pullup is ");
if(pin_read(USBPU_port, USBPU_pin)) SEND("off");
else SEND("on");
newline();
break;
case 'A':
return u2str(getADCval(0));
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\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\n";
break;
case 'T':
return u2str(getMCUtemp());
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
"0/1 - turn on/off LED1\n"
"'b' - get buttons's state\n"
"'p' - toggle USB pullup\n"
"'A' - get ADC8 value\n"
"'L' - send long string over USB\n"
"'R' - software reset\n"
"'S' - send short string over USB\n"
"'T' - MCU temperature\n"
"'V' - Vdd\n"
"'W' - test watchdog\n"
;
break;
}
return NULL;
}
// usb getline
char *get_USB(){
static char tmpbuf[512], *curptr = tmpbuf;
static int rest = 511;
int x = USB_receive((uint8_t*)curptr);
curptr[x] = 0;
if(!x) return NULL;
if(curptr[x-1] == '\n'){
curptr = tmpbuf;
rest = 511;
return tmpbuf;
}
curptr += x; rest -= x;
if(rest <= 0){ // buffer overflow
SEND("USB buffer overflow!\n");
curptr = tmpbuf;
rest = 511;
}
return NULL;
}
//int8_t dump = 0;
int main(void){
uint32_t lastT = 0, lastB = 0, LEDperiod = 499;
uint32_t lastT = 0;
sysreset();
StartHSE();
hw_setup();
@ -167,21 +59,45 @@ int main(void){
USBPU_OFF();
USB_setup();
iwdg_setup();
USBPU_ON();
while (1){
IWDG->KR = IWDG_REFRESH; // refresh watchdog
if(lastT > Tms || Tms - lastT > LEDperiod){
LED_blink(LED0);
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();
int r = 0;
char *txt, *ans;
if((txt = get_USB())){
ans = parse_cmd(txt);
ans = (char*)parse_cmd(txt);
SEND("Received data over USB:\n");
SEND(txt);
newline();
@ -189,30 +105,20 @@ int main(void){
uint16_t l = 0; char *p = ans;
while(*p++) l++;
USB_send((uint8_t*)ans, l);
if(ans[l-1] != '\n') USND("\n");
}
}
if(usartrx()){ // usart1 received data, store in in buffer
r = usart_getline(&txt);
if(r){
txt[r] = 0;
ans = parse_cmd(txt);
ans = (char*)parse_cmd(txt);
if(ans){
usart_send(ans);
transmit_tbuf();
}
}
}
// check buttons - each 50ms (increase / decrease LED blinking period by 10)
if(Tms - lastB > 49){
lastB = Tms;
uint8_t btn0 = GET_BTN0(), btn1 = GET_BTN1();
// both: set to default
if(btn0 && btn1){
LEDperiod = 499;
}else if(btn0){
if(LEDperiod < 1989) LEDperiod += 10;
}else if(btn1){
if(LEDperiod > 29) LEDperiod -= 10;
USND("Got string over USART:\n");
USB_sendstr(txt);
}
}
}

Binary file not shown.

558
F1:F103/F1_testbrd/proto.c Normal file
View File

@ -0,0 +1,558 @@
/*
* 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 "hardware.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 = (uint32_t*)&(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(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);
}
static inline char *wrI2C(char *buf){
uint16_t N = readNnumbers(buf);
//if(!write_i2c(I2Caddress, locBuffer, N)) return "Error writing I2C";
if(N < 1) return "bad";
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){
if(SPIidx < 0 || SPIidx > 2) return;
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(SPIidx < 0 || SPIidx > 2) return;
//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"
"0 - USB Pullup change\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((uint32_t*)&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':
return "TODO";
/*
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);
return "TODO";
break;
case 'U':
return USARTsend(buf + 1);
break;
}
// "short" commands
if(buf[1] != '\n') return buf;
switch(*buf){
case '0':
pin_toggle(USBPU_port, USBPU_pin);
if(USBPU_port->ODR & USBPU_pin) return "Pullup clear";
else return "Pullup set";
break;
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,38 @@
/*
* 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 <stm32f1.h>
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

@ -20,6 +20,7 @@
*/
#include "stm32f1.h"
#include "usart.h"
#include "usb.h"
extern volatile uint32_t Tms;
static volatile int idatalen[2] = {0,0}; // received data line length (including '\n')
@ -52,10 +53,13 @@ int usart_getline(char **line){
// transmit current tbuf and swap buffers
void transmit_tbuf(){
uint32_t tmout = 72000;
while(!txrdy){if(--tmout == 0) return;}; // wait for previos buffer transmission
//uint32_t tmout = 72000000;
while(!txrdy);
//while(!txrdy){if(--tmout == 0) return;}; // wait for previos buffer transmission
register int l = odatalen[tbufno];
if(!l) return;
//USND("\n\nUTX:\n"); USB_send((uint8_t*)tbuf[tbufno], odatalen[tbufno]);
//USND("\n\n\n");
txrdy = 0;
odatalen[tbufno] = 0;
DMA1_Channel4->CCR &= ~DMA_CCR_EN;
@ -66,13 +70,12 @@ void transmit_tbuf(){
}
void usart_putchar(const char ch){
for(int i = 0; odatalen[tbufno] == UARTBUFSZO && i < 1024; ++i) transmit_tbuf();
if(odatalen[tbufno] == UARTBUFSZO) transmit_tbuf();
tbuf[tbufno][odatalen[tbufno]++] = ch;
}
void usart_send(const char *str){
uint32_t x = 512;
while(*str && --x){
while(*str){
if(odatalen[tbufno] == UARTBUFSZO){
transmit_tbuf();
continue;
@ -158,91 +161,6 @@ void usart1_isr(){
}
}
// return string buffer with val
char *u2str(uint32_t val){
static char bufa[11];
char bufb[10];
int l = 0, bpos = 0;
if(!val){
bufa[0] = '0';
l = 1;
}else{
while(val){
bufb[l++] = val % 10 + '0';
val /= 10;
}
int i;
bpos += l;
for(i = 0; i < l; ++i){
bufa[--bpos] = bufb[i];
}
}
bufa[l + bpos] = 0;
return bufa;
}
// print 32bit unsigned int
void printu(uint32_t val){
usart_send(u2str(val));
}
// print 32bit unsigned int as hex
void printuhex(uint32_t val){
usart_send("0x");
uint8_t *ptr = (uint8_t*)&val + 3;
int i, j;
for(i = 0; i < 4; ++i, --ptr){
for(j = 1; j > -1; --j){
register uint8_t half = (*ptr >> (4*j)) & 0x0f;
if(half < 10) usart_putchar(half + '0');
else usart_putchar(half - 10 + 'a');
}
}
}
// dump memory buffer
void hexdump(uint8_t *arr, uint16_t len){
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) usart_putchar(half + '0');
else usart_putchar(half - 10 + 'a');
}
if(l % 16 == 15) usart_putchar('\n');
else if((l & 3) == 3) usart_putchar(' ');
}
}
// dump USB memory (uint16_t mapped as uint32_t); len - in uint16_t
void hexdump16(uint16_t *arr, uint16_t len){
for(uint16_t l = 0; l < len; ++l, ++arr){
uint16_t x = arr[l];
for(int8_t i = 0; i < 2; ++i){
for(int16_t j = 1; j > -1; --j){
register uint8_t half = (x >> (4*j+8*i)) & 0x0f;
if(half < 10) usart_putchar(half + '0');
else usart_putchar(half - 10 + 'a');
}
}
if(l % 8 == 7) usart_putchar('\n');
else if(l & 1) usart_putchar(' ');
}
}
void hexdump32(uint32_t *arr, uint16_t len){
for(uint16_t l = 0; l < len; ++l, ++arr){
uint16_t x = (uint16_t)arr[l];
for(int8_t i = 0; i < 2; ++i){
for(int16_t j = 1; j > -1; --j){
register uint8_t half = (x >> (4*j+8*i)) & 0x0f;
if(half < 10) usart_putchar(half + '0');
else usart_putchar(half - 10 + 'a');
}
}
if(l % 8 == 7) usart_putchar('\n');
else if(l & 1) usart_putchar(' ');
}
}
void dma1_channel4_isr(){
if(DMA1->ISR & DMA_ISR_TCIF4){ // Tx
DMA1->IFCR = DMA_IFCR_CTCIF4; // clear TC flag

View File

@ -57,11 +57,5 @@ int usart_getline(char **line);
void usart_send(const char *str);
void newline();
void usart_putchar(const char ch);
char *u2str(uint32_t val);
void printu(uint32_t val);
void printuhex(uint32_t val);
void hexdump(uint8_t *arr, uint16_t len);
void hexdump16(uint16_t *arr, uint16_t len);
void hexdump32(uint32_t *arr, uint16_t len);
#endif // __USART_H__

View File

@ -28,6 +28,8 @@
#define BUFFSIZE (64)
#define USND(str) do{USB_send((uint8_t*)str, sizeof(str)-1);}while(0)
void USB_setup();
void usb_proc();
void USB_send(const uint8_t *buf, uint16_t len);

View File

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

View File

@ -0,0 +1 @@
Simple test for STM32F103, blinking PA0/PA1, two user buttons (PA14 and PA15) and USB (PL2303 emulator) <> USART1 echo.

View File

@ -0,0 +1,70 @@
/*
* 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 - internal Tsens
* 2 - Vref
*/
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
}
// return MCU temperature (degrees of celsius * 10)
int32_t getMCUtemp(){
// Temp = (V25 - Vsense)/Avg_Slope + 25
// V_25 = 1.45V, Slope = 4.3e-3
int32_t Vsense = getVdd() * getADCval(1);
int32_t temperature = 593920 - Vsense; // 593920 == 145*4096
temperature /= 172; // == /(4096*10*4.3e-3), 10 - to convert from *100 to *10
temperature += 250;
return(temperature);
}
// return Vdd * 100 (V)
uint32_t getVdd(){
uint32_t vdd = 120 * 4096; // 1.2V
vdd /= getADCval(2);
return vdd;
}

View File

@ -0,0 +1,29 @@
/*
* 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 "stm32f1.h"
#define NUMBER_OF_ADC_CHANNELS (3)
extern uint16_t ADC_array[];
int32_t getMCUtemp();
uint32_t getVdd();
uint16_t getADCval(int nch);
#endif // ADC_H

View File

@ -0,0 +1,79 @@
/*
* 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 "usart.h"
static inline void gpio_setup(){
// Enable clocks to the GPIO subsystems (PB for ADC), turn on AFIO clocking to disable SWD/JTAG
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPBEN | RCC_APB2ENR_AFIOEN;
// turn off SWJ/JTAG
AFIO->MAPR = AFIO_MAPR_SWJ_CFG_DISABLE;
// turn off USB pullup
GPIOA->ODR = (1<<13)|(1<<14)|(1<<15); // turn off usb pullup & turn on pullups for buttons
// Set leds (PA0/PA4) as opendrain output
GPIOA->CRL = CRL(0, CNF_ODOUTPUT|MODE_SLOW) | CRL(4, CNF_ODOUTPUT|MODE_SLOW);
// Set buttons (PA14/15) as inputs with weak pullups, USB pullup (PA13) - opendrain output
GPIOA->CRH = CRH(13, CNF_ODOUTPUT|MODE_SLOW) | CRH(14, CNF_PUDINPUT|MODE_INPUT)
| CRH(15, CNF_PUDINPUT|MODE_INPUT);
}
static inline void adc_setup(){
GPIOB->CRL |= CRL(0, CNF_ANALOG|MODE_INPUT);
uint32_t ctr = 0;
// Enable clocking
RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;
RCC->CFGR &= ~(RCC_CFGR_ADCPRE);
RCC->CFGR |= RCC_CFGR_ADCPRE_DIV8; // ADC clock = RCC / 8
// sampling time - 239.5 cycles for channels 8, 16 and 17
ADC1->SMPR2 = ADC_SMPR2_SMP8;
ADC1->SMPR1 = ADC_SMPR1_SMP16 | ADC_SMPR1_SMP17;
// we have three conversions in group -> ADC1->SQR1[L] = 2, order: 8->16->17
ADC1->SQR3 = 8 | (16<<5) | (17<<10);
ADC1->SQR1 = ADC_SQR1_L_1;
ADC1->CR1 |= ADC_CR1_SCAN; // scan mode
// DMA configuration
RCC->AHBENR |= RCC_AHBENR_DMA1EN;
DMA1_Channel1->CPAR = (uint32_t) (&(ADC1->DR));
DMA1_Channel1->CMAR = (uint32_t)(ADC_array);
DMA1_Channel1->CNDTR = NUMBER_OF_ADC_CHANNELS * 9;
DMA1_Channel1->CCR |= DMA_CCR_MINC | DMA_CCR_MSIZE_0 | DMA_CCR_PSIZE_0
| DMA_CCR_CIRC | DMA_CCR_PL | DMA_CCR_EN;
// continuous mode & DMA; enable vref & Tsens; wake up ADC
ADC1->CR2 |= ADC_CR2_DMA | ADC_CR2_TSVREFE | ADC_CR2_CONT | ADC_CR2_ADON;
// wait for Tstab - at least 1us
while(++ctr < 0xff) nop();
// calibration
ADC1->CR2 |= ADC_CR2_RSTCAL;
ctr = 0; while((ADC1->CR2 & ADC_CR2_RSTCAL) && ++ctr < 0xfffff);
ADC1->CR2 |= ADC_CR2_CAL;
ctr = 0; while((ADC1->CR2 & ADC_CR2_CAL) && ++ctr < 0xfffff);
// turn ON ADC
ADC1->CR2 |= ADC_CR2_ADON;
}
void hw_setup(){
gpio_setup();
adc_setup();
}

View File

@ -0,0 +1,53 @@
/*
* 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 "stm32f1.h"
// LEDS: 0 - PA0, 1 - PA4
// LED0 - blinking each second
#define LED0_port GPIOA
#define LED0_pin (1<<0)
// LED1 - PWM
#define LED1_port GPIOA
#define LED1_pin (1<<4)
// Buttons' state: PA14 (1)/PA15 (0)
#define GET_BTN0() ((GPIOA->IDR & (1<<15)) ? 0 : 1)
#define GET_BTN1() ((GPIOA->IDR & (1<<14)) ? 0 : 1)
// USB pullup (not used in STM32F0x2!) - PA13
#define USBPU_port GPIOA
#define USBPU_pin (1<<13)
#define USBPU_ON() pin_clear(USBPU_port, USBPU_pin)
#define USBPU_OFF() pin_set(USBPU_port, USBPU_pin)
#define LED_blink(x) pin_toggle(x ## _port, x ## _pin)
#define LED_on(x) pin_clear(x ## _port, x ## _pin)
#define LED_off(x) pin_set(x ## _port, x ## _pin)
void hw_setup();
#endif // __HARDWARE_H__

View File

@ -0,0 +1,221 @@
/*
* 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 "usart.h"
#include "usb.h"
#include "usb_lib.h"
volatile uint32_t Tms = 0;
/* Called when systick fires */
void sys_tick_handler(void){
++Tms;
}
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) */
}
#define USND(str) do{USB_send((uint8_t*)str, sizeof(str)-1);}while(0)
char *parse_cmd(char *buf){
static char btns[] = "BTN0=0, BTN1=0\n";
if(buf[1] != '\n') return buf;
switch(*buf){
case '0':
pin_set(GPIOA, 1<<4);
break;
case '1':
pin_clear(GPIOA, 1<<4);
break;
case 'b':
btns[5] = GET_BTN0() + '0';
btns[13] = GET_BTN1() + '0';
return btns;
break;
case 'p':
pin_toggle(USBPU_port, USBPU_pin);
SEND("USB pullup is ");
if(pin_read(USBPU_port, USBPU_pin)) SEND("off");
else SEND("on");
newline();
break;
case 'A':
return u2str(getADCval(0));
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\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\n";
break;
case 'T':
return u2str(getMCUtemp());
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
"0/1 - turn on/off LED1\n"
"'b' - get buttons's state\n"
"'p' - toggle USB pullup\n"
"'A' - get ADC8 value\n"
"'L' - send long string over USB\n"
"'R' - software reset\n"
"'S' - send short string over USB\n"
"'T' - MCU temperature\n"
"'V' - Vdd\n"
"'W' - test watchdog\n"
;
break;
}
return NULL;
}
// usb getline
char *get_USB(){
static char tmpbuf[512], *curptr = tmpbuf;
static int rest = 511;
int x = USB_receive((uint8_t*)curptr);
curptr[x] = 0;
if(!x) return NULL;
if(curptr[x-1] == '\n'){
curptr = tmpbuf;
rest = 511;
return tmpbuf;
}
curptr += x; rest -= x;
if(rest <= 0){ // buffer overflow
SEND("USB buffer overflow!\n");
curptr = tmpbuf;
rest = 511;
}
return NULL;
}
//int8_t dump = 0;
int main(void){
uint32_t lastT = 0, lastB = 0, LEDperiod = 499;
sysreset();
StartHSE();
hw_setup();
usart_setup();
SysTick_Config(72000);
SEND("Hello! I'm ready.\n");
if(RCC->CSR & RCC_CSR_IWDGRSTF){ // watchdog reset occured
SEND("WDGRESET=1\n");
}
if(RCC->CSR & RCC_CSR_SFTRSTF){ // software reset occured
SEND("SOFTRESET=1\n");
}
RCC->CSR |= RCC_CSR_RMVF; // remove reset flags
USBPU_OFF();
USB_setup();
iwdg_setup();
USBPU_ON();
while (1){
IWDG->KR = IWDG_REFRESH; // refresh watchdog
if(lastT > Tms || Tms - lastT > LEDperiod){
LED_blink(LED0);
lastT = Tms;
transmit_tbuf(); // non-blocking transmission of data from UART buffer every 0.5s
}
usb_proc();
int r = 0;
char *txt, *ans;
if((txt = get_USB())){
ans = parse_cmd(txt);
SEND("Received data over USB:\n");
SEND(txt);
newline();
if(ans){
uint16_t l = 0; char *p = ans;
while(*p++) l++;
USB_send((uint8_t*)ans, l);
}
}
if(usartrx()){ // usart1 received data, store in in buffer
r = usart_getline(&txt);
if(r){
txt[r] = 0;
ans = parse_cmd(txt);
if(ans){
usart_send(ans);
transmit_tbuf();
}
}
}
// check buttons - each 50ms (increase / decrease LED blinking period by 10)
if(Tms - lastB > 49){
lastB = Tms;
uint8_t btn0 = GET_BTN0(), btn1 = GET_BTN1();
// both: set to default
if(btn0 && btn1){
LEDperiod = 499;
}else if(btn0){
if(LEDperiod < 1989) LEDperiod += 10;
}else if(btn1){
if(LEDperiod > 29) LEDperiod -= 10;
}
}
}
return 0;
}

Binary file not shown.

View File

@ -0,0 +1,251 @@
/*
* usart.c
*
* Copyright 2018 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 "stm32f1.h"
#include "usart.h"
extern volatile uint32_t Tms;
static volatile int idatalen[2] = {0,0}; // received data line length (including '\n')
static volatile int odatalen[2] = {0,0};
volatile int linerdy = 0, // received data ready
dlen = 0, // length of data (including '\n') in current buffer
bufovr = 0, // input buffer overfull
txrdy = 1 // transmission done
;
int rbufno = 0, tbufno = 0; // current rbuf/tbuf numbers
static char rbuf[2][UARTBUFSZI], tbuf[2][UARTBUFSZO]; // receive & transmit buffers
static char *recvdata = NULL;
/**
* return length of received data (without trailing zero)
*/
int usart_getline(char **line){
if(bufovr){
bufovr = 0;
linerdy = 0;
return 0;
}
*line = recvdata;
linerdy = 0;
return dlen;
}
// transmit current tbuf and swap buffers
void transmit_tbuf(){
uint32_t tmout = 72000;
while(!txrdy){if(--tmout == 0) return;}; // wait for previos buffer transmission
register int l = odatalen[tbufno];
if(!l) return;
txrdy = 0;
odatalen[tbufno] = 0;
DMA1_Channel4->CCR &= ~DMA_CCR_EN;
DMA1_Channel4->CMAR = (uint32_t) tbuf[tbufno]; // mem
DMA1_Channel4->CNDTR = l;
DMA1_Channel4->CCR |= DMA_CCR_EN;
tbufno = !tbufno;
}
void usart_putchar(const char ch){
for(int i = 0; odatalen[tbufno] == UARTBUFSZO && i < 1024; ++i) transmit_tbuf();
tbuf[tbufno][odatalen[tbufno]++] = ch;
}
void usart_send(const char *str){
uint32_t x = 512;
while(*str && --x){
if(odatalen[tbufno] == UARTBUFSZO){
transmit_tbuf();
continue;
}
tbuf[tbufno][odatalen[tbufno]++] = *str++;
}
}
void newline(){
usart_putchar('\n');
transmit_tbuf();
}
/*
* USART speed: baudrate = Fck/(USARTDIV)
* USARTDIV stored in USART->BRR
*
* for 72MHz USARTDIV=72000/f(kboud); so for 115200 USARTDIV=72000/115.2=625 -> BRR=0x271
* 9600: BRR = 7500 (0x1D4C)
*/
void usart_setup(){
uint32_t tmout = 16000000;
// PA9 - Tx, PA10 - Rx
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_USART1EN;
RCC->AHBENR |= RCC_AHBENR_DMA1EN;
GPIOA->CRH |= CRH(9, CNF_AFPP|MODE_NORMAL) | CRH(10, CNF_FLINPUT|MODE_INPUT);
// USART1 Tx DMA - Channel4 (Rx - channel 5)
DMA1_Channel4->CPAR = (uint32_t) &USART1->DR; // periph
DMA1_Channel4->CCR |= DMA_CCR_MINC | DMA_CCR_DIR | DMA_CCR_TCIE; // 8bit, mem++, mem->per, transcompl irq
// Tx CNDTR set @ each transmission due to data size
NVIC_SetPriority(DMA1_Channel4_IRQn, 3);
NVIC_EnableIRQ(DMA1_Channel4_IRQn);
NVIC_SetPriority(USART1_IRQn, 0);
// setup usart1
USART1->BRR = 72000000 / 115200;
USART1->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_UE; // 1start,8data,nstop; enable Rx,Tx,USART
while(!(USART1->SR & USART_SR_TC)){if(--tmout == 0) break;} // polling idle frame Transmission
USART1->SR = 0; // clear flags
USART1->CR1 |= USART_CR1_RXNEIE; // allow Rx IRQ
USART1->CR3 = USART_CR3_DMAT; // enable DMA Tx
NVIC_EnableIRQ(USART1_IRQn);
}
void usart1_isr(){
#ifdef CHECK_TMOUT
static uint32_t tmout = 0;
#endif
if(USART1->SR & USART_SR_RXNE){ // RX not emty - receive next char
#ifdef CHECK_TMOUT
if(tmout && Tms >= tmout){ // set overflow flag
bufovr = 1;
idatalen[rbufno] = 0;
}
tmout = Tms + TIMEOUT_MS;
if(!tmout) tmout = 1; // prevent 0
#endif
uint8_t rb = USART1->DR;
if(idatalen[rbufno] < UARTBUFSZI){ // put next char into buf
rbuf[rbufno][idatalen[rbufno]++] = rb;
if(rb == '\n'){ // got newline - line ready
linerdy = 1;
dlen = idatalen[rbufno];
recvdata = rbuf[rbufno];
// prepare other buffer
rbufno = !rbufno;
idatalen[rbufno] = 0;
#ifdef CHECK_TMOUT
// clear timeout at line end
tmout = 0;
#endif
}
}else{ // buffer overrun
bufovr = 1;
idatalen[rbufno] = 0;
#ifdef CHECK_TMOUT
tmout = 0;
#endif
}
}
}
// return string buffer with val
char *u2str(uint32_t val){
static char bufa[11];
char bufb[10];
int l = 0, bpos = 0;
if(!val){
bufa[0] = '0';
l = 1;
}else{
while(val){
bufb[l++] = val % 10 + '0';
val /= 10;
}
int i;
bpos += l;
for(i = 0; i < l; ++i){
bufa[--bpos] = bufb[i];
}
}
bufa[l + bpos] = 0;
return bufa;
}
// print 32bit unsigned int
void printu(uint32_t val){
usart_send(u2str(val));
}
// print 32bit unsigned int as hex
void printuhex(uint32_t val){
usart_send("0x");
uint8_t *ptr = (uint8_t*)&val + 3;
int i, j;
for(i = 0; i < 4; ++i, --ptr){
for(j = 1; j > -1; --j){
register uint8_t half = (*ptr >> (4*j)) & 0x0f;
if(half < 10) usart_putchar(half + '0');
else usart_putchar(half - 10 + 'a');
}
}
}
// dump memory buffer
void hexdump(uint8_t *arr, uint16_t len){
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) usart_putchar(half + '0');
else usart_putchar(half - 10 + 'a');
}
if(l % 16 == 15) usart_putchar('\n');
else if((l & 3) == 3) usart_putchar(' ');
}
}
// dump USB memory (uint16_t mapped as uint32_t); len - in uint16_t
void hexdump16(uint16_t *arr, uint16_t len){
for(uint16_t l = 0; l < len; ++l, ++arr){
uint16_t x = arr[l];
for(int8_t i = 0; i < 2; ++i){
for(int16_t j = 1; j > -1; --j){
register uint8_t half = (x >> (4*j+8*i)) & 0x0f;
if(half < 10) usart_putchar(half + '0');
else usart_putchar(half - 10 + 'a');
}
}
if(l % 8 == 7) usart_putchar('\n');
else if(l & 1) usart_putchar(' ');
}
}
void hexdump32(uint32_t *arr, uint16_t len){
for(uint16_t l = 0; l < len; ++l, ++arr){
uint16_t x = (uint16_t)arr[l];
for(int8_t i = 0; i < 2; ++i){
for(int16_t j = 1; j > -1; --j){
register uint8_t half = (x >> (4*j+8*i)) & 0x0f;
if(half < 10) usart_putchar(half + '0');
else usart_putchar(half - 10 + 'a');
}
}
if(l % 8 == 7) usart_putchar('\n');
else if(l & 1) usart_putchar(' ');
}
}
void dma1_channel4_isr(){
if(DMA1->ISR & DMA_ISR_TCIF4){ // Tx
DMA1->IFCR = DMA_IFCR_CTCIF4; // clear TC flag
txrdy = 1;
}
}

View File

@ -0,0 +1,67 @@
/*
* 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 <stdint.h>
// 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(str) usart_send(str)
#define STR_HELPER(s) #s
#define STR(s) STR_HELPER(s)
#ifdef EBUG
#define MSG(str) do{SEND(__FILE__ " (L" STR(__LINE__) "): " str);}while(0)
#define DBG(str) do{SEND(str); usart_putchar('\n'); }while(0)
#else
#define MSG(str)
#define DBG(str)
#endif
#define usartrx() (linerdy)
#define usartovr() (bufovr)
extern volatile int linerdy, bufovr, txrdy;
void transmit_tbuf();
void usart_setup();
int usart_getline(char **line);
void usart_send(const char *str);
void newline();
void usart_putchar(const char ch);
char *u2str(uint32_t val);
void printu(uint32_t val);
void printuhex(uint32_t val);
void hexdump(uint8_t *arr, uint16_t len);
void hexdump16(uint16_t *arr, uint16_t len);
void hexdump32(uint32_t *arr, uint16_t len);
#endif // __USART_H__

View File

@ -0,0 +1,167 @@
/*
* 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 "usart.h"
#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
DBG("RXh");
}
void USB_setup(){
NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
NVIC_DisableIRQ(USB_HP_CAN1_TX_IRQn);
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_CAN1_RX0_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;
DBG("Get data");
SEND((char*)buf); newline();
uint8_t sz = EP_Read(2, (uint16_t*)buf);
uint16_t epstatus = KEEP_DTOG(USB->EPnR[2]);
// keep stat_tx & set ACK rx
USB->EPnR[2] = (epstatus & ~(USB_EPnR_STAT_TX)) ^ USB_EPnR_STAT_RX;
rxNE = 0;
return sz;
}

View File

@ -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,107 @@
/*
* 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 <stm32f1.h>
// 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_BASE ((uint32_t)0x40005C00)
#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
#ifdef USB_TypeDef
#define USB_TypeDef USB_TypeDef_custom
#endif
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;
#endif // __USB_DEFS_H__

View File

@ -0,0 +1,482 @@
/*
* 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;
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;}
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){
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 = 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;
}
//extern int8_t dump;
// standard IRQ handler
void usb_lp_can_rx0_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;
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;
// clear address, leave only enable bit
USB->DADDR = USB_DADDR_EF;
USB_Dev.USB_Status = USB_STATE_DEFAULT;
USB->ISTR = ~USB_ISTR_RESET;
if(EP_Init(0, EP_TYPE_CONTROL, USB_EP0_BUFSZ, USB_EP0_BUFSZ, EP0_Handler)){
return;
}
}
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;
}
}
/**
* 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;
}

View File

@ -0,0 +1,189 @@
/*
* 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)
// 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 uint8_t usbON;
void USB_Init();
void USB_ResetState();
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, 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);
#endif // __USB_LIB_H__

View File

@ -149,7 +149,7 @@ void WEAK __attribute__ ((naked)) __attribute__ ((noreturn)) reset_handler(void)
char *src = &_ldata;
// enable 8-byte stack alignment to comply with AAPCS
SCB->CCR |= 0x00000200;
//SCB->CCR |= 0x00000200;
// copy initialized variables data
while ( dst < &_edata ) { *dst++ = *src++; }