fixed stupid bug

This commit is contained in:
2026-03-25 15:08:51 +03:00
parent 8e591d73bd
commit 0e9c7361b9
19 changed files with 583 additions and 306 deletions

View File

@@ -21,6 +21,7 @@
#include "hardware.h" #include "hardware.h"
#include "proto.h" #include "proto.h"
#include "spi.h" #include "spi.h"
#include "strfunc.h"
#include "usb_dev.h" #include "usb_dev.h"
#define CU(a) ((const uint8_t*)a) #define CU(a) ((const uint8_t*)a)
@@ -315,7 +316,7 @@ void canon_proc(){
/* /*
case CANON_GETFOCM: // don't work @EF200 case CANON_GETFOCM: // don't work @EF200
uval = (rbuf[1] << 24) | (rbuf[2] << 16) | (rbuf[3] << 8) | rbuf[4]; uval = (rbuf[1] << 24) | (rbuf[2] << 16) | (rbuf[3] << 8) | rbuf[4];
USB_send("Fval="); USB_send(u2str(uval)); USB_send("\n"); USB_sendstr("Fval="); USB_sendstr(u2str(uval)); USB_sendstr("\n");
break; break;
*/ */
} }
@@ -393,7 +394,7 @@ int canon_asku16(uint8_t cmd){
int canon_getinfo(){ int canon_getinfo(){
if(!ready || !canon_read(CANON_GETINFO, 6)) return 1; if(!ready || !canon_read(CANON_GETINFO, 6)) return 1;
USB_sendstr("Info="); for(int i = 1; i < 7; ++i){ USB_sendstr("Info="); for(int i = 1; i < 7; ++i){
USB_sendstr(u2hexstr(buf[i])); USB_sendstr(" "); USB_sendstr(uhex2str(buf[i])); USB_sendstr(" ");
} }
//canon_poll(); //canon_poll();
USB_sendstr("\n"); USB_sendstr("\n");

View File

@@ -18,7 +18,7 @@
#pragma once #pragma once
#include <stm32f1.h> #include <stdint.h>
// all data sent in big-endian format // all data sent in big-endian format

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject> <!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 15.0.1, 2025-03-11T16:16:01. --> <!-- Written by QtCreator 18.0.0, 2026-03-25T15:00:48. -->
<qtcreator> <qtcreator>
<data> <data>
<variable>EnvironmentId</variable> <variable>EnvironmentId</variable>
@@ -13,8 +13,8 @@
<data> <data>
<variable>ProjectExplorer.Project.EditorSettings</variable> <variable>ProjectExplorer.Project.EditorSettings</variable>
<valuemap type="QVariantMap"> <valuemap type="QVariantMap">
<value type="bool" key="EditorConfiguration.AutoDetect">true</value>
<value type="bool" key="EditorConfiguration.AutoIndent">true</value> <value type="bool" key="EditorConfiguration.AutoIndent">true</value>
<value type="bool" key="EditorConfiguration.AutoSpacesForTabs">false</value>
<value type="bool" key="EditorConfiguration.CamelCaseNavigation">true</value> <value type="bool" key="EditorConfiguration.CamelCaseNavigation">true</value>
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0"> <valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0">
<value type="QString" key="language">Cpp</value> <value type="QString" key="language">Cpp</value>
@@ -86,12 +86,14 @@
<valuelist type="QVariantList" key="ClangTools.SuppressedDiagnostics"/> <valuelist type="QVariantList" key="ClangTools.SuppressedDiagnostics"/>
<value type="bool" key="ClangTools.UseGlobalSettings">true</value> <value type="bool" key="ClangTools.UseGlobalSettings">true</value>
</valuemap> </valuemap>
<value type="int" key="RcSync">0</value>
</valuemap> </valuemap>
</data> </data>
<data> <data>
<variable>ProjectExplorer.Project.Target.0</variable> <variable>ProjectExplorer.Project.Target.0</variable>
<valuemap type="QVariantMap"> <valuemap type="QVariantMap">
<value type="QString" key="DeviceType">Desktop</value> <value type="QString" key="DeviceType">Desktop</value>
<value type="bool" key="HasPerBcDcs">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Desktop</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Desktop</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Desktop</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Desktop</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">{91347f2c-5221-46a7-80b1-0a054ca02f79}</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">{91347f2c-5221-46a7-80b1-0a054ca02f79}</value>
@@ -109,8 +111,8 @@
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericMakeStep</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericMakeStep</value>
</valuemap> </valuemap>
<value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">1</value> <value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Сборка</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Build</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Сборка</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Build</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value>
</valuemap> </valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1"> <valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1">
@@ -122,8 +124,8 @@
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericMakeStep</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericMakeStep</value>
</valuemap> </valuemap>
<value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">1</value> <value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Очистка</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Clean</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Очистка</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Clean</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value>
</valuemap> </valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value> <value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value>
@@ -133,13 +135,46 @@
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/> <valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">По умолчанию</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">По умолчанию</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericBuildConfiguration</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericBuildConfiguration</value>
<value type="qlonglong" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value>
<value type="qlonglong" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">0</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deploy</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Deploy</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Deploy</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.DeployConfiguration.CustomData"/>
<value type="bool" key="ProjectExplorer.DeployConfiguration.CustomDataEnabled">false</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.DefaultDeployConfiguration</value>
</valuemap>
<value type="qlonglong" key="ProjectExplorer.Target.DeployConfigurationCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.RunConfiguration.0">
<value type="bool" key="Analyzer.Perf.Settings.UseGlobalSettings">true</value>
<value type="bool" key="Analyzer.QmlProfiler.Settings.UseGlobalSettings">true</value>
<value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value>
<valuelist type="QVariantList" key="CustomOutputParsers"/>
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
<value type="bool" key="PE.EnvironmentAspect.PrintOnRun">false</value>
<value type="QString" key="PerfRecordArgsId">-e cpu-cycles --call-graph dwarf,4096 -F 250</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value>
<value type="QString" key="ProjectExplorer.RunConfiguration.BuildKey"></value>
<value type="bool" key="ProjectExplorer.RunConfiguration.Customized">false</value>
<value type="QString" key="ProjectExplorer.RunConfiguration.UniqueId"></value>
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
<value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value>
</valuemap>
<value type="qlonglong" key="ProjectExplorer.Target.RunConfigurationCount">1</value>
</valuemap> </valuemap>
<value type="qlonglong" key="ProjectExplorer.Target.BuildConfigurationCount">1</value> <value type="qlonglong" key="ProjectExplorer.Target.BuildConfigurationCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0"> <valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0"> <valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">0</value> <value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">0</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Развёртывание</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deploy</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Развёртывание</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Deploy</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Deploy</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Deploy</value>
</valuemap> </valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">1</value> <value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">1</value>
@@ -161,6 +196,7 @@
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value> <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value>
<value type="QString" key="ProjectExplorer.RunConfiguration.BuildKey"></value> <value type="QString" key="ProjectExplorer.RunConfiguration.BuildKey"></value>
<value type="bool" key="ProjectExplorer.RunConfiguration.Customized">false</value> <value type="bool" key="ProjectExplorer.RunConfiguration.Customized">false</value>
<value type="QString" key="ProjectExplorer.RunConfiguration.UniqueId"></value>
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value> <value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
<value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value> <value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value>
</valuemap> </valuemap>
@@ -171,10 +207,6 @@
<variable>ProjectExplorer.Project.TargetCount</variable> <variable>ProjectExplorer.Project.TargetCount</variable>
<value type="qlonglong">1</value> <value type="qlonglong">1</value>
</data> </data>
<data>
<variable>ProjectExplorer.Project.Updater.FileVersion</variable>
<value type="int">22</value>
</data>
<data> <data>
<variable>Version</variable> <variable>Version</variable>
<value type="int">22</value> <value type="int">22</value>

View File

@@ -13,6 +13,8 @@ ringbuffer.c
ringbuffer.h ringbuffer.h
spi.c spi.c
spi.h spi.h
strfunc.c
strfunc.h
usb.c usb.c
usb.h usb.h
usb_descr.c usb_descr.c

View File

@@ -25,6 +25,7 @@
#include "flash.h" #include "flash.h"
#include "proto.h" #include "proto.h"
#include "strfunc.h"
#include "usb_dev.h" // printout #include "usb_dev.h" // printout
#include <string.h> // memcpy #include <string.h> // memcpy
@@ -145,7 +146,7 @@ static int write2flash(const void *start, const void *wrdata, uint32_t stor_size
} }
#ifdef EBUG #ifdef EBUG
USB_sendstr(u2str(stor_size)); USB_sendstr("bytes stored @0x"); USB_sendstr(u2str(stor_size)); USB_sendstr("bytes stored @0x");
USB_sendstr(u2hexstr((uint32_t)(address + i))); USB_sendstr("\n"); USB_sendstr(uhex2str((uint32_t)(address + i))); USB_sendstr("\n");
#endif #endif
FLASH->SR = FLASH_SR_EOP | FLASH_SR_PGERR | FLASH_SR_WRPRTERR; FLASH->SR = FLASH_SR_EOP | FLASH_SR_PGERR | FLASH_SR_WRPRTERR;
} }

View File

@@ -49,13 +49,11 @@ int main(void){
uint32_t SPIctr = Tms; uint32_t SPIctr = Tms;
while(1){ while(1){
IWDG->KR = IWDG_REFRESH; IWDG->KR = IWDG_REFRESH;
int l = USB_receivestr(inbuff, 255); if(Tms - SPIctr > CANONPROC_INTERVAL){ // not more than once per 10ms
if(l > 0){ SPIctr = Tms;
parse_cmd(inbuff); // call it even for NULL (if `flood` is running) canon_proc();
if(Tms - SPIctr > CANONPROC_INTERVAL){ // not more than once per 10ms
SPIctr = Tms;
canon_proc();
}
} }
int l = USB_receivestr(inbuff, 255);
if(l > 0) parse_cmd(inbuff); // call it even for NULL (if `flood` is running)
} }
} }

View File

@@ -23,141 +23,12 @@
#include "hardware.h" #include "hardware.h"
#include "proto.h" #include "proto.h"
#include "spi.h" #include "spi.h"
#include "strfunc.h"
#include "usb_dev.h" #include "usb_dev.h"
#include "version.inc" #include "version.inc"
static const char *OK = "OK", *FAIL = "FAIL"; static const char *OK = "OK", *FAIL = "FAIL";
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;
}
const char* helpmsg = const char* helpmsg =
"https://github.com/eddyem/stm32samples/tree/master/F1-nolib/Canon_managing_device build#" BUILD_NUMBER " @ " BUILD_DATE "\n" "https://github.com/eddyem/stm32samples/tree/master/F1-nolib/Canon_managing_device build#" BUILD_NUMBER " @ " BUILD_DATE "\n"
"0 - move to smallest foc value (e.g. 2.5m)\n" "0 - move to smallest foc value (e.g. 2.5m)\n"
@@ -213,7 +84,7 @@ static void sendspibuf(){
USB_sendstr("Got SPI answer: "); USB_sendstr("Got SPI answer: ");
for(int i = 0; i < spibuflen; ++i){ for(int i = 0; i < spibuflen; ++i){
if(i) USB_sendstr(", "); if(i) USB_sendstr(", ");
USB_sendstr(u2hexstr(buf[i])); USB_sendstr(uhex2str(buf[i]));
} }
USB_sendstr("\n"); USB_sendstr("\n");
}else USB_sendstr("Failed to send SPI buffer\n"); }else USB_sendstr("Failed to send SPI buffer\n");
@@ -284,7 +155,7 @@ void parse_cmd(const char *buf){
USB_sendstr(OK); USB_sendstr(OK);
break; break;
case 'F': // just watch SPI->CR1 value case 'F': // just watch SPI->CR1 value
USB_sendstr("SPI1->CR1="); USB_sendstr(u2hexstr(SPI_CR1)); USB_sendstr("SPI1->CR1="); USB_sendstr(uhex2str(SPI_CR1));
break; break;
case 'G': case 'G':
USB_sendstr("SPI "); USB_sendstr("SPI ");
@@ -344,7 +215,7 @@ void parse_cmd(const char *buf){
} }
uint32_t D = 0; uint32_t D = 0;
int16_t neg; int16_t neg;
char *nxt; const char *nxt;
switch(*buf++){ // long messages switch(*buf++){ // long messages
case 'a': // move focus to absolute position case 'a': // move focus to absolute position
buf = omit_spaces(buf); buf = omit_spaces(buf);
@@ -425,7 +296,7 @@ void parse_cmd(const char *buf){
USB_sendstr(helpmsg); USB_sendstr(helpmsg);
return; return;
} }
USB_sendstr("SPI_CR1="); USB_sendstr(u2hexstr(SPI_CR1)); USB_sendstr("SPI_CR1="); USB_sendstr(uhex2str(SPI_CR1));
break; break;
case 'L': case 'L':
if(0 == initspibuf(buf)){ if(0 == initspibuf(buf)){
@@ -445,7 +316,7 @@ void parse_cmd(const char *buf){
USB_sendstr("Send: "); USB_sendstr("Send: ");
for(int i = 0; i < spibuflen; ++i){ for(int i = 0; i < spibuflen; ++i){
if(i) USB_sendstr(", "); if(i) USB_sendstr(", ");
USB_sendstr(u2hexstr(spibuf[i])); USB_sendstr(uhex2str(spibuf[i]));
} }
USB_sendstr("\n"); USB_sendstr("\n");
sendspibuf(); sendspibuf();
@@ -456,41 +327,3 @@ void parse_cmd(const char *buf){
} }
newline(); newline();
} }
// return string with number `val`
char *u2str(uint32_t val){
static char strbuf[11];
char *bufptr = &strbuf[10];
*bufptr = 0;
if(!val){
*(--bufptr) = '0';
}else{
while(val){
*(--bufptr) = val % 10 + '0';
val /= 10;
}
}
return bufptr;
}
char *u2hexstr(uint32_t val){
static char strbuf[11] = "0x";
char *sptr = strbuf + 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) *sptr++ = half + '0';
else *sptr++ = half - 10 + 'a';
}
}
*sptr = 0;
return strbuf;
}

View File

@@ -17,24 +17,15 @@
*/ */
#pragma once #pragma once
#ifndef PROTO_H__
#define PROTO_H__
#include <stm32f1.h>
#define printu(x) do{USB_sendstr(u2str(x));}while(0) #define printu(x) do{USB_sendstr(u2str(x));}while(0)
#define printuhex(x) do{USB_sendstr(uhex2str(x));}while(0) #define printuhex(x) do{USB_sendstr(uhex2str(x));}while(0)
#ifdef EBUG #ifdef EBUG
#define DBG(x) do{USB_send(x); USB_send("\n");}while(0) #define DBG(x) do{USB_sendstr(x); newline();}while(0)
#else #else
#define DBG(x) #define DBG(x)
#endif #endif
void parse_cmd(const char *buf); void parse_cmd(const char *buf);
char *omit_spaces(const char *buf);
char *getnum(const char *buf, uint32_t *N);
char *u2str(uint32_t val);
char *u2hexstr(uint32_t val);
#endif // PROTO_H__

View File

@@ -15,6 +15,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <string.h>
#include <stm32f1.h>
#include "ringbuffer.h" #include "ringbuffer.h"
static int datalen(ringbuffer *b){ static int datalen(ringbuffer *b){
@@ -24,7 +26,7 @@ static int datalen(ringbuffer *b){
// stored data length // stored data length
int RB_datalen(ringbuffer *b){ int RB_datalen(ringbuffer *b){
if(b->busy) return -1; if(!b || b->busy) return -1;
b->busy = 1; b->busy = 1;
int l = datalen(b); int l = datalen(b);
b->busy = 0; b->busy = 0;
@@ -32,7 +34,7 @@ int RB_datalen(ringbuffer *b){
} }
static int hasbyte(ringbuffer *b, uint8_t byte){ static int hasbyte(ringbuffer *b, uint8_t byte){
if(b->head == b->tail) return -1; // no data in buffer if(!b || b->head == b->tail) return -1; // no data in buffer
int startidx = b->head; int startidx = b->head;
if(b->head > b->tail){ // if(b->head > b->tail){ //
for(int found = b->head; found < b->length; ++found) for(int found = b->head; found < b->length; ++found)
@@ -51,18 +53,13 @@ static int hasbyte(ringbuffer *b, uint8_t byte){
* @return index if found, -1 if none or busy * @return index if found, -1 if none or busy
*/ */
int RB_hasbyte(ringbuffer *b, uint8_t byte){ int RB_hasbyte(ringbuffer *b, uint8_t byte){
if(b->busy) return -1; if(!b || b->busy) return -1;
b->busy = 1; b->busy = 1;
int ret = hasbyte(b, byte); int ret = hasbyte(b, byte);
b->busy = 0; b->busy = 0;
return ret; return ret;
} }
// poor memcpy
static void mcpy(uint8_t *targ, const uint8_t *src, int l){
while(l--) *targ++ = *src++;
}
// increment head or tail // increment head or tail
TRUE_INLINE void incr(ringbuffer *b, volatile int *what, int n){ TRUE_INLINE void incr(ringbuffer *b, volatile int *what, int n){
*what += n; *what += n;
@@ -76,9 +73,9 @@ static int read(ringbuffer *b, uint8_t *s, int len){
int _1st = b->length - b->head; int _1st = b->length - b->head;
if(_1st > l) _1st = l; if(_1st > l) _1st = l;
if(_1st > len) _1st = len; if(_1st > len) _1st = len;
mcpy(s, b->data + b->head, _1st); memcpy(s, b->data + b->head, _1st);
if(_1st < len && l > _1st){ if(_1st < len && l > _1st){
mcpy(s+_1st, b->data, l - _1st); memcpy(s+_1st, b->data, l - _1st);
incr(b, &b->head, l); incr(b, &b->head, l);
return l; return l;
} }
@@ -94,20 +91,27 @@ static int read(ringbuffer *b, uint8_t *s, int len){
* @return bytes read or -1 if busy * @return bytes read or -1 if busy
*/ */
int RB_read(ringbuffer *b, uint8_t *s, int len){ int RB_read(ringbuffer *b, uint8_t *s, int len){
if(b->busy) return -1; if(!b || b->busy || !s || len < 1) return -1;
b->busy = 1; b->busy = 1;
int r = read(b, s, len); int r = read(b, s, len);
b->busy = 0; b->busy = 0;
return r; return r;
} }
static int readto(ringbuffer *b, uint8_t byte, uint8_t *s, int len){ // length of data from current position to `byte` (including byte)
static int lento(ringbuffer *b, uint8_t byte){
int idx = hasbyte(b, byte); int idx = hasbyte(b, byte);
if(idx < 0) return 0; if(idx < 0) return 0;
int partlen = idx + 1 - b->head; int partlen = idx + 1 - b->head;
// now calculate length of new data portion // now calculate length of new data portion
if(idx < b->head) partlen += b->length; if(idx < b->head) partlen += b->length;
if(partlen > len) return -read(b, s, len); return partlen;
}
static int readto(ringbuffer *b, uint8_t byte, uint8_t *s, int len){
int partlen = lento(b, byte);
if(!partlen) return 0;
if(partlen > len) return -1;
return read(b, s, partlen); return read(b, s, partlen);
} }
@@ -115,26 +119,41 @@ static int readto(ringbuffer *b, uint8_t byte, uint8_t *s, int len){
* @brief RB_readto fill array `s` with data until byte `byte` (with it) * @brief RB_readto fill array `s` with data until byte `byte` (with it)
* @param b - ringbuffer * @param b - ringbuffer
* @param byte - check byte * @param byte - check byte
* @param s - buffer to write data * @param s - buffer to write data or NULL to clear data
* @param len - length of `s` * @param len - length of `s` or 0 to clear data
* @return amount of bytes written (negative, if len<data in buffer or buffer is busy) * @return amount of bytes written (negative, if len<data in buffer or buffer is busy)
*/ */
int RB_readto(ringbuffer *b, uint8_t byte, uint8_t *s, int len){ int RB_readto(ringbuffer *b, uint8_t byte, uint8_t *s, int len){
if(b->busy) return -1; if(!b || b->busy) return -1;
b->busy = 1; b->busy = 1;
int n = readto(b, byte, s, len); int n = 0;
if(s && len > 0){
n = readto(b, byte, s, len);
}else{
incr(b, &b->head, lento(b, byte)); // just throw data out
}
b->busy = 0; b->busy = 0;
return n; return n;
} }
int RB_datalento(ringbuffer *b, uint8_t byte){
if(!b || b->busy) return -1;
b->busy = 1;
int n = lento(b, byte);
b->busy = 0;
return n;
}
// if l < rest of buffer, truncate and return actually written bytes
static int write(ringbuffer *b, const uint8_t *str, int l){ static int write(ringbuffer *b, const uint8_t *str, int l){
int r = b->length - 1 - datalen(b); // rest length int r = b->length - 1 - datalen(b); // rest length
if(l > r || !l) return 0; if(r < 1) return 0;
if(l > r) l = r;
int _1st = b->length - b->tail; int _1st = b->length - b->tail;
if(_1st > l) _1st = l; if(_1st > l) _1st = l;
mcpy(b->data + b->tail, str, _1st); memcpy(b->data + b->tail, str, _1st);
if(_1st < l){ // add another piece from start if(_1st < l){ // add another piece from start
mcpy(b->data, str+_1st, l-_1st); memcpy(b->data, str+_1st, l-_1st);
} }
incr(b, &b->tail, l); incr(b, &b->tail, l);
return l; return l;
@@ -148,7 +167,7 @@ static int write(ringbuffer *b, const uint8_t *str, int l){
* @return amount of bytes written or -1 if busy * @return amount of bytes written or -1 if busy
*/ */
int RB_write(ringbuffer *b, const uint8_t *str, int l){ int RB_write(ringbuffer *b, const uint8_t *str, int l){
if(b->busy) return -1; if(!b || b->busy || !str || l < 1) return -1;
b->busy = 1; b->busy = 1;
int w = write(b, str, l); int w = write(b, str, l);
b->busy = 0; b->busy = 0;
@@ -157,7 +176,7 @@ int RB_write(ringbuffer *b, const uint8_t *str, int l){
// just delete all information in buffer `b` // just delete all information in buffer `b`
int RB_clearbuf(ringbuffer *b){ int RB_clearbuf(ringbuffer *b){
if(b->busy) return -1; if(!b || b->busy) return -1;
b->busy = 1; b->busy = 1;
b->head = 0; b->head = 0;
b->tail = 0; b->tail = 0;

View File

@@ -17,13 +17,7 @@
#pragma once #pragma once
#if defined STM32F0 #include <stdint.h>
#include <stm32f0.h>
#elif defined STM32F1
#include <stm32f1.h>
#elif defined STM32F3
#include <stm32f3.h>
#endif
typedef struct{ typedef struct{
uint8_t *data; // data buffer uint8_t *data; // data buffer
@@ -38,4 +32,5 @@ int RB_readto(ringbuffer *b, uint8_t byte, uint8_t *s, int len);
int RB_hasbyte(ringbuffer *b, uint8_t byte); int RB_hasbyte(ringbuffer *b, uint8_t byte);
int RB_write(ringbuffer *b, const uint8_t *str, int l); int RB_write(ringbuffer *b, const uint8_t *str, int l);
int RB_datalen(ringbuffer *b); int RB_datalen(ringbuffer *b);
int RB_datalento(ringbuffer *b, uint8_t byte);
int RB_clearbuf(ringbuffer *b); int RB_clearbuf(ringbuffer *b);

View File

@@ -21,9 +21,10 @@
#include "spi.h" #include "spi.h"
#include "hardware.h" #include "hardware.h"
#ifdef EBUG #ifdef EBUG
#include "usb.h" #include "usb_dev.h"
#endif #endif
#include "proto.h" #include "proto.h"
#include "strfunc.h"
/* /*
static void mymemcpy(uint8_t *dest, uint8_t *src, int len){ static void mymemcpy(uint8_t *dest, uint8_t *src, int len){
@@ -56,26 +57,26 @@ uint8_t SPI_transmit(uint8_t *buf, uint8_t len){
if(!buf || !len) return 0; // bad data format if(!buf || !len) return 0; // bad data format
if(SPI_status != SPI_READY) return 0; // spi not ready to transmit data if(SPI_status != SPI_READY) return 0; // spi not ready to transmit data
#ifdef EBUG #ifdef EBUG
USB_send("SPI send "); USB_send(u2str(len)); USB_sendstr("SPI send "); USB_sendstr(u2str(len));
USB_send("bytes, data: "); USB_sendstr("bytes, data: ");
#endif #endif
for(uint8_t x = 0; x < len; ++x){ for(uint8_t x = 0; x < len; ++x){
WAITX(!(SPI1->SR & SPI_SR_TXE)); WAITX(!(SPI1->SR & SPI_SR_TXE));
SPI1->DR = buf[x]; SPI1->DR = buf[x];
WAITX(!(SPI1->SR & SPI_SR_BSY)); WAITX(!(SPI1->SR & SPI_SR_BSY));
#ifdef EBUG #ifdef EBUG
USB_send(u2hexstr(buf[x])); USB_send(", "); USB_sendstr(uhex2str(buf[x])); USB_sendstr(", ");
#endif #endif
WAITX(!(SPI1->SR & SPI_SR_RXNE)); WAITX(!(SPI1->SR & SPI_SR_RXNE));
buf[x] = SPI1->DR; buf[x] = SPI1->DR;
for(int ctr = 0; ctr < 3600; ++ctr) IWDG->KR = IWDG_REFRESH; // ~100mks delay for(int ctr = 0; ctr < 3600; ++ctr) IWDG->KR = IWDG_REFRESH; // ~100mks delay
} }
#ifdef EBUG #ifdef EBUG
USB_send("\nReceive: "); USB_sendstr("\nReceive: ");
for(int i = 0; i < len; ++i){ for(int i = 0; i < len; ++i){
USB_send(u2hexstr(buf[i])); USB_send(", "); USB_sendstr(uhex2str(buf[i])); USB_sendstr(", ");
} }
USB_send("\n"); USB_sendstr("\n");
#endif #endif
return len; return len;
} }

View File

@@ -0,0 +1,265 @@
/*
* This file is part of the test project.
* Copyright 2026 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 "strfunc.h"
/**
* @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 const 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;
}
}
if(minus) *(--bufptr) = '-';
return bufptr;
}
// return string with number `val`
const char *u2str(uint32_t val){
return _2str(val, 0);
}
const 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
*/
const 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;
}

View File

@@ -0,0 +1,30 @@
/*
* This file is part of the test project.
* Copyright 2026 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <stdint.h>
#include <string.h>
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);

View File

@@ -26,7 +26,7 @@ static const uint8_t USB_DeviceDescriptor[] = {
USB_DT_DEVICE, // bDescriptorType USB_DT_DEVICE, // bDescriptorType
L16(bcdUSB), // bcdUSB_L L16(bcdUSB), // bcdUSB_L
H16(bcdUSB), // bcdUSB_H H16(bcdUSB), // bcdUSB_H
USB_CLASS_COMM, // bDeviceClass USB_CLASS_MISC, // bDeviceClass
bDeviceSubClass, // bDeviceSubClass bDeviceSubClass, // bDeviceSubClass
bDeviceProtocol, // bDeviceProtocol bDeviceProtocol, // bDeviceProtocol
USB_EP0BUFSZ, // bMaxPacketSize USB_EP0BUFSZ, // bMaxPacketSize
@@ -140,7 +140,7 @@ static const uint8_t USB_ConfigDescriptor[] = {
//const uint8_t HID_ReportDescriptor[]; //const uint8_t HID_ReportDescriptor[];
_USB_LANG_ID_(LD, LANG_US); _USB_LANG_ID_(LD, LANG_US);
_USB_STRING_(SD, u"0.1.0"); _USB_STRING_(SD, u"0.1.1");
_USB_STRING_(MD, u"eddy@sao.ru"); _USB_STRING_(MD, u"eddy@sao.ru");
_USB_STRING_(PD, u"USB/CAN Canon lens controller"); _USB_STRING_(PD, u"USB/CAN Canon lens controller");
_USB_STRING_(ID, u"canonlens"); _USB_STRING_(ID, u"canonlens");

View File

@@ -15,7 +15,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <stm32f1.h>
#include <string.h> #include <string.h>
#include "ringbuffer.h" #include "ringbuffer.h"
@@ -41,10 +40,10 @@
static volatile uint8_t bufovrfl = 0; static volatile uint8_t bufovrfl = 0;
// receive buffer: hold data until chkin() call // receive buffer: hold data until chkin() call
static uint8_t volatile rcvbuf[USB_RXBUFSZ]; static uint8_t volatile rcvbuf[USB_RXBUFSZ] __attribute__((aligned(4)));
static uint8_t volatile rcvbuflen = 0; static uint8_t volatile rcvbuflen = 0;
// line coding // line coding
usb_LineCoding WEAK lineCoding = {115200, 0, 0, 8}; usb_LineCoding lineCoding = {115200, 0, 0, 8};
// CDC configured and ready to use // CDC configured and ready to use
volatile uint8_t CDCready = 0; volatile uint8_t CDCready = 0;
@@ -70,10 +69,10 @@ static void chkin(){
// called from transmit EP to send next data portion or by user - when new transmission starts // called from transmit EP to send next data portion or by user - when new transmission starts
static void send_next(){ static void send_next(){
uint8_t usbbuff[USB_TXBUFSZ]; uint8_t usbbuff[USB_TXBUFSZ] __attribute__((aligned(4)));
int buflen = RB_read((ringbuffer*)&rbout, (uint8_t*)usbbuff, USB_TXBUFSZ); int buflen = RB_read((ringbuffer*)&rbout, (uint8_t*)usbbuff, USB_TXBUFSZ);
if(buflen == 0){ if(buflen == 0){
if(lastdsz == 64) EP_Write(1, NULL, 0); // send ZLP after 64 bits packet when nothing more to send if(lastdsz == USB_TXBUFSZ) EP_Write(1, NULL, 0); // send ZLP after USB_TXBUFSZ bits packet when nothing more to send
lastdsz = 0; lastdsz = 0;
return; return;
}else if(buflen < 0){ }else if(buflen < 0){
@@ -103,21 +102,20 @@ static void rxtx_handler(){
// weak handlers: change them somewhere else if you want to setup USART // weak handlers: change them somewhere else if you want to setup USART
// SET_LINE_CODING // SET_LINE_CODING
void WEAK linecoding_handler(usb_LineCoding *lc){ void linecoding_handler(usb_LineCoding *lc){
lineCoding = *lc; lineCoding = *lc;
} }
// SET_CONTROL_LINE_STATE // SET_CONTROL_LINE_STATE
void WEAK clstate_handler(uint16_t val){ void clstate_handler(uint16_t val){
CDCready = val; // CONTROL_DTR | CONTROL_RTS -> interface connected; 0 -> disconnected CDCready = val; // CONTROL_DTR | CONTROL_RTS -> interface connected; 0 -> disconnected
} }
// SEND_BREAK // SEND_BREAK
void WEAK break_handler(){ void break_handler(){
CDCready = 0; CDCready = 0;
} }
// USB is configured: setup endpoints // USB is configured: setup endpoints
void set_configuration(){ void set_configuration(){
EP_Init(1, EP_TYPE_BULK, USB_TXBUFSZ, USB_RXBUFSZ, rxtx_handler); // IN1 and OUT1 EP_Init(1, EP_TYPE_BULK, USB_TXBUFSZ, USB_RXBUFSZ, rxtx_handler); // IN1 and OUT1
@@ -166,7 +164,16 @@ int USB_sendall(){
int USB_send(const uint8_t *buf, int len){ int USB_send(const uint8_t *buf, int len){
if(!buf || !CDCready || !len) return FALSE; if(!buf || !CDCready || !len) return FALSE;
while(len){ while(len){
int a = RB_write((ringbuffer*)&rbout, buf, len); IWDG->KR = IWDG_REFRESH;
int l = RB_datalen((ringbuffer*)&rbout);
if(l < 0) continue;
int portion = rbout.length - 1 - l;
if(portion < 1){
if(lastdsz == 0) send_next();
continue;
}
if(portion > len) portion = len;
int a = RB_write((ringbuffer*)&rbout, buf, portion);
if(a > 0){ if(a > 0){
len -= a; len -= a;
buf += a; buf += a;
@@ -217,7 +224,7 @@ int USB_receive(uint8_t *buf, int len){
* @brief USB_receivestr - get string up to '\n' and replace '\n' with 0 * @brief USB_receivestr - get string up to '\n' and replace '\n' with 0
* @param buf - receiving buffer * @param buf - receiving buffer
* @param len - its length * @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) * @return strlen or negative value indicating overflow
*/ */
int USB_receivestr(char *buf, int len){ int USB_receivestr(char *buf, int len){
chkin(); chkin();
@@ -226,14 +233,18 @@ int USB_receivestr(char *buf, int len){
bufovrfl = 0; bufovrfl = 0;
return -1; return -1;
} }
int l = RB_readto((ringbuffer*)&rbin, '\n', (uint8_t*)buf, len); int l = RB_datalento((ringbuffer*)&rbin, '\n');
if(l < 1){ if(l > len){ // can't read: line too long -> clear it
RB_readto((ringbuffer*)&rbin, '\n', NULL, 0);
return -1;
}else if(l < 1){ // nothing or no '\n' ?
if(rbin.length == RB_datalen((ringbuffer*)&rbin)){ // buffer is full but no '\n' found if(rbin.length == RB_datalen((ringbuffer*)&rbin)){ // buffer is full but no '\n' found
while(1 != RB_clearbuf((ringbuffer*)&rbin)); while(1 != RB_clearbuf((ringbuffer*)&rbin));
return -1; return -1;
} }
return 0; return 0;
} }
l = RB_readto((ringbuffer*)&rbin, '\n', (uint8_t*)buf, len);
if(l == 0) return 0; if(l == 0) return 0;
buf[l-1] = 0; // replace '\n' with strend buf[l-1] = 0; // replace '\n' with strend
return l; return l;

View File

@@ -16,7 +16,7 @@
*/ */
#pragma once #pragma once
#include <stm32f1.h> #include <stdint.h>
#include "usb_lib.h" #include "usb_lib.h"
typedef struct { typedef struct {

View File

@@ -23,7 +23,7 @@
static ep_t endpoints[STM32ENDPOINTS]; static ep_t endpoints[STM32ENDPOINTS];
static uint16_t USB_Addr = 0; static uint16_t USB_Addr = 0;
static uint8_t setupdatabuf[EP0DATABUF_SIZE]; static uint8_t setupdatabuf[EP0DATABUF_SIZE] __attribute__((aligned(4)));
static config_pack_t *setup_packet = (config_pack_t*) setupdatabuf; static config_pack_t *setup_packet = (config_pack_t*) setupdatabuf;
volatile uint8_t usbON = 0; // device is configured and active volatile uint8_t usbON = 0; // device is configured and active
@@ -81,8 +81,7 @@ void WEAK usb_standard_request(){
break; break;
case REQ_RECIPIENT_ENDPOINT: case REQ_RECIPIENT_ENDPOINT:
if(setup_packet->bRequest == CLEAR_FEATURE){ if(setup_packet->bRequest == CLEAR_FEATURE){
}else{ }else{ /* wrong */ }
}
break; break;
default: default:
break; break;
@@ -97,7 +96,7 @@ void WEAK usb_class_request(config_pack_t *req, uint8_t _U_ *data, uint16_t _U_
case SET_CONFIGURATION: // set featuring by req->wValue case SET_CONFIGURATION: // set featuring by req->wValue
break; break;
default: default:
break; break;
} }
if(0 == (setup_packet->bmRequestType & 0x80)) // host2dev if(0 == (setup_packet->bmRequestType & 0x80)) // host2dev
EP_WriteIRQ(0, NULL, 0); EP_WriteIRQ(0, NULL, 0);
@@ -119,7 +118,7 @@ bmRequestType: 76543210
*/ */
static void EP0_Handler(){ static void EP0_Handler(){
uint8_t ep0dbuflen = 0; uint8_t ep0dbuflen = 0;
uint8_t ep0databuf[EP0DATABUF_SIZE]; uint8_t ep0databuf[EP0DATABUF_SIZE] __attribute__((aligned(4)));
uint16_t epstatus = KEEP_DTOG(USB->EPnR[0]); // EP0R on input -> return this value after modifications uint16_t epstatus = KEEP_DTOG(USB->EPnR[0]); // EP0R on input -> return this value after modifications
int rxflag = RX_FLAG(epstatus); int rxflag = RX_FLAG(epstatus);
// check direction // check direction
@@ -128,6 +127,7 @@ static void EP0_Handler(){
EP_Read(0, setupdatabuf); EP_Read(0, setupdatabuf);
// interrupt handler will be called later // interrupt handler will be called later
}else if(epstatus & USB_EPnR_CTR_RX){ // data packet -> push received data to ep0databuf }else if(epstatus & USB_EPnR_CTR_RX){ // data packet -> push received data to ep0databuf
//if(endpoints[0].rx_cnt){ }
ep0dbuflen = EP_Read(0, ep0databuf); ep0dbuflen = EP_Read(0, ep0databuf);
} }
} }
@@ -137,8 +137,7 @@ static void EP0_Handler(){
case REQ_TYPE_STANDARD: case REQ_TYPE_STANDARD:
if(SETUP_FLAG(epstatus)){ if(SETUP_FLAG(epstatus)){
usb_standard_request(); usb_standard_request();
}else{ }else{ }
}
break; break;
case REQ_TYPE_CLASS: case REQ_TYPE_CLASS:
usb_class_request(setup_packet, ep0databuf, ep0dbuflen); usb_class_request(setup_packet, ep0databuf, ep0dbuflen);
@@ -173,9 +172,14 @@ static void EP0_Handler(){
*/ */
void EP_WriteIRQ(uint8_t number, const uint8_t *buf, uint16_t size){ void EP_WriteIRQ(uint8_t number, const uint8_t *buf, uint16_t size){
if(size > endpoints[number].txbufsz) size = endpoints[number].txbufsz; if(size > endpoints[number].txbufsz) size = endpoints[number].txbufsz;
#ifndef USB32
uint16_t N2 = (size + 1) >> 1; uint16_t N2 = (size + 1) >> 1;
// the buffer is 16-bit, so we should copy data as it would be uint16_t // the buffer is 16-bit, so we should copy data as it would be uint16_t
uint16_t *buf16 = (uint16_t *)buf; uint16_t *buf16 = (uint16_t *)buf;
#else
int N4 = (size + 3) >> 2;
uint32_t *buf32 = (uint32_t *)buf;
#endif
#if defined USB1_16 #if defined USB1_16
// very bad: what if `size` is odd? // very bad: what if `size` is odd?
uint32_t *out = (uint32_t *)endpoints[number].tx_buf; uint32_t *out = (uint32_t *)endpoints[number].tx_buf;
@@ -184,13 +188,19 @@ void EP_WriteIRQ(uint8_t number, const uint8_t *buf, uint16_t size){
} }
#elif defined USB2_16 #elif defined USB2_16
// use memcpy instead? // use memcpy instead?
for(int i = 0; i < N2; i++){ for(int i = 0; i < N2; ++i){
endpoints[number].tx_buf[i] = buf16[i]; endpoints[number].tx_buf[i] = buf16[i];
} }
#elif defined USB32
for(int i = 0; i < N4; ++i) endpoints[number].tx_buf[i] = buf32[i];
#else #else
#error "Define USB1_16 or USB2_16" #error "Define USB1_16 / USB2_16 / USB32"
#endif #endif
#ifndef USB32
USB_BTABLE->EP[number].USB_COUNT_TX = size; USB_BTABLE->EP[number].USB_COUNT_TX = size;
#else
USB_BTABLE->EP[number].USB_ADDR_COUNT_TX = (USB_BTABLE->EP[number].USB_ADDR_COUNT_TX & 0xffff) | (size << 16);
#endif
} }
/** /**
@@ -225,8 +235,12 @@ int EP_Read(uint8_t number, uint8_t *buf){
// use memcpy instead? // use memcpy instead?
for(int i = 0; i < sz; ++i) for(int i = 0; i < sz; ++i)
buf[i] = endpoints[number].rx_buf[i]; buf[i] = endpoints[number].rx_buf[i];
#elif defined USB32
uint32_t *u32buf = (uint32_t*) buf;
int N4 = (sz + 3) >> 2;
for(int i = 0; i < N4; ++i) u32buf[i] = endpoints[number].rx_buf[i];
#else #else
#error "Define USB1_16 or USB2_16" #error "Define USB1_16 / USB2_16 / USB32"
#endif #endif
return sz; return sz;
} }
@@ -243,11 +257,16 @@ static uint16_t lastaddr = LASTADDR_DEFAULT;
* @return 0 if all OK * @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)){ int EP_Init(uint8_t number, uint8_t type, uint16_t txsz, uint16_t rxsz, void (*func)(ep_t ep)){
#ifdef STM32G0
// in STM32G0 all buffers should be aligned by 32 bits
if(txsz & 3) txsz = ((txsz >> 2)+1) << 2;
if(rxsz & 3) rxsz = ((rxsz >> 2)+1) << 2;
#endif
if(number >= STM32ENDPOINTS) return 4; // out of configured amount if(number >= STM32ENDPOINTS) return 4; // out of configured amount
if(txsz > USB_BTABLE_SIZE/ACCESSZ || rxsz > USB_BTABLE_SIZE/ACCESSZ) return 1; // buffer too large if(txsz > USB_BTABLE_SIZE/ACCESSZ || rxsz > USB_BTABLE_SIZE/ACCESSZ) return 1; // buffer too large
if(lastaddr + txsz + rxsz >= USB_BTABLE_SIZE/ACCESSZ) return 2; // out of btable if(lastaddr + txsz + rxsz >= USB_BTABLE_SIZE/ACCESSZ) return 2; // out of btable
USB->EPnR[number] = (type << 9) | (number & USB_EPnR_EA); USB->EPnR[number] = (type << 9) | (number & USB_EPnR_EA);
USB->EPnR[number] ^= USB_EPnR_STAT_RX | USB_EPnR_STAT_TX_1; USB->EPnR[number] ^= USB_EPnR_STAT_RX | USB_EPnR_STAT_TX;
if(rxsz & 1) return 3; // wrong rx buffer size if(rxsz & 1) return 3; // wrong rx buffer size
uint16_t countrx = 0; uint16_t countrx = 0;
if(rxsz < 64) countrx = rxsz / 2; if(rxsz < 64) countrx = rxsz / 2;
@@ -255,15 +274,28 @@ int EP_Init(uint8_t number, uint8_t type, uint16_t txsz, uint16_t rxsz, void (*f
if(rxsz & 0x1f) return 3; // should be multiple of 32 if(rxsz & 0x1f) return 3; // should be multiple of 32
countrx = 31 + rxsz / 32; countrx = 31 + rxsz / 32;
} }
USB_BTABLE->EP[number].USB_ADDR_TX = lastaddr; #ifdef USB32
endpoints[number].tx_buf = (uint32_t *)(USB_BTABLE_BASE + lastaddr * ACCESSZ);
#else
endpoints[number].tx_buf = (uint16_t *)(USB_BTABLE_BASE + lastaddr * ACCESSZ); endpoints[number].tx_buf = (uint16_t *)(USB_BTABLE_BASE + lastaddr * ACCESSZ);
#endif
endpoints[number].txbufsz = txsz; endpoints[number].txbufsz = txsz;
lastaddr += txsz; #ifdef USB32
USB_BTABLE->EP[number].USB_ADDR_COUNT_TX = (uint32_t) lastaddr;
#else
USB_BTABLE->EP[number].USB_ADDR_TX = lastaddr;
USB_BTABLE->EP[number].USB_COUNT_TX = 0; USB_BTABLE->EP[number].USB_COUNT_TX = 0;
USB_BTABLE->EP[number].USB_ADDR_RX = lastaddr; #endif
lastaddr += txsz;
#ifdef USB32
endpoints[number].rx_buf = (uint32_t *)(USB_BTABLE_BASE + lastaddr * ACCESSZ);
USB_BTABLE->EP[number].USB_ADDR_COUNT_RX = (uint32_t) lastaddr | countrx << 26;
#else
endpoints[number].rx_buf = (uint8_t *)(USB_BTABLE_BASE + lastaddr * ACCESSZ); endpoints[number].rx_buf = (uint8_t *)(USB_BTABLE_BASE + lastaddr * ACCESSZ);
lastaddr += rxsz; USB_BTABLE->EP[number].USB_ADDR_RX = lastaddr;
USB_BTABLE->EP[number].USB_COUNT_RX = countrx << 10; USB_BTABLE->EP[number].USB_COUNT_RX = countrx << 10;
#endif
lastaddr += rxsz;
endpoints[number].func = func; endpoints[number].func = func;
return 0; return 0;
} }
@@ -272,7 +304,8 @@ int EP_Init(uint8_t number, uint8_t type, uint16_t txsz, uint16_t rxsz, void (*f
void USB_IRQ(){ void USB_IRQ(){
uint32_t CNTR = USB->CNTR; uint32_t CNTR = USB->CNTR;
USB->CNTR = 0; USB->CNTR = 0;
if(USB->ISTR & USB_ISTR_RESET){ uint32_t istr = USB->ISTR;
if(istr & USB_ISTR_RESET){
usbON = 0; usbON = 0;
// Reinit registers // Reinit registers
CNTR = USB_CNTR_RESETM | USB_CNTR_CTRM | USB_CNTR_SUSPM; CNTR = USB_CNTR_RESETM | USB_CNTR_CTRM | USB_CNTR_SUSPM;
@@ -281,42 +314,56 @@ void USB_IRQ(){
lastaddr = LASTADDR_DEFAULT; lastaddr = LASTADDR_DEFAULT;
// clear address, leave only enable bit // clear address, leave only enable bit
USB->DADDR = USB_DADDR_EF; USB->DADDR = USB_DADDR_EF;
USB->ISTR = ~USB_ISTR_RESET; //USB->ISTR = ~(USB_ISTR_RESET); // clear all flags
if(EP_Init(0, EP_TYPE_CONTROL, USB_EP0BUFSZ, USB_EP0BUFSZ, EP0_Handler)){ if(EP_Init(0, EP_TYPE_CONTROL, USB_EP0BUFSZ, USB_EP0BUFSZ, EP0_Handler)){
return; return;
}; };
} }
if(USB->ISTR & USB_ISTR_CTR){ if(istr & USB_ISTR_CTR){
// EP number // EP number
uint8_t n = USB->ISTR & USB_ISTR_EPID; uint8_t n = istr & USB_ISTR_EPID;
if (istr & USB_ISTR_DIR){ // OUT
}else{ // IN
}
// copy received bytes amount // copy received bytes amount
endpoints[n].rx_cnt = USB_BTABLE->EP[n].USB_COUNT_RX & 0x3FF; // low 10 bits is counter endpoints[n].rx_cnt =
#ifdef USB32
(USB_BTABLE->EP[n].USB_ADDR_COUNT_RX >> 16) & 0x3FF;
#else
USB_BTABLE->EP[n].USB_COUNT_RX & 0x3FF; // low 10 bits is counter
#endif
// call EP handler // call EP handler
if(endpoints[n].func) endpoints[n].func(); if(endpoints[n].func) endpoints[n].func();
} }
if(USB->ISTR & USB_ISTR_WKUP){ // wakeup if(istr & USB_ISTR_WKUP){ // wakeup
#ifndef STM32F0 #if defined STM32F0
CNTR &= ~(USB_CNTR_FSUSP | USB_CNTR_LP_MODE | USB_CNTR_WKUPM); // clear suspend flags
#else
CNTR &= ~(USB_CNTR_FSUSP | USB_CNTR_LPMODE | USB_CNTR_WKUPM); CNTR &= ~(USB_CNTR_FSUSP | USB_CNTR_LPMODE | USB_CNTR_WKUPM);
#endif #elif defined STM32G0
USB->ISTR = ~USB_ISTR_WKUP; CNTR &= ~(USB_CNTR_SUSPEN | USB_CNTR_PDWN | USB_CNTR_WKUPM);
}
if(USB->ISTR & USB_ISTR_SUSP){ // suspend -> still no connection, may sleep
usbON = 0;
#ifndef STM32F0
CNTR |= USB_CNTR_FSUSP | USB_CNTR_LP_MODE | USB_CNTR_WKUPM;
#else #else
CNTR &= ~(USB_CNTR_FSUSP | USB_CNTR_LP_MODE | USB_CNTR_WKUPM); // clear suspend flags
#endif
//USB->ISTR = ~USB_ISTR_WKUP;
}
if(istr & USB_ISTR_SUSP){ // suspend -> still no connection, may sleep
usbON = 0;
#if defined STM32F0
CNTR |= USB_CNTR_FSUSP | USB_CNTR_LPMODE | USB_CNTR_WKUPM; CNTR |= USB_CNTR_FSUSP | USB_CNTR_LPMODE | USB_CNTR_WKUPM;
#elif defined STM32G0
CNTR |= USB_CNTR_SUSPEN | USB_CNTR_WKUPM;
#else
CNTR |= USB_CNTR_FSUSP | USB_CNTR_LP_MODE | USB_CNTR_WKUPM;
#endif #endif
CNTR &= ~(USB_CNTR_SUSPM); CNTR &= ~(USB_CNTR_SUSPM);
USB->ISTR = ~USB_ISTR_SUSP; //USB->ISTR = ~USB_ISTR_SUSP;
} }
USB->ISTR = 0; // clear all flags
USB->CNTR = CNTR; // rewoke interrupts USB->CNTR = CNTR; // rewoke interrupts
} }
// here we suppose that all PIN settings done in hw_setup earlier // here we suppose that all PIN settings done in hw_setup earlier
void USB_setup(){ void USB_setup(){
lastaddr = LASTADDR_DEFAULT; // clear last address settings
#if defined STM32F3 #if defined STM32F3
NVIC_DisableIRQ(USB_LP_IRQn); NVIC_DisableIRQ(USB_LP_IRQn);
// remap USB LP & Wakeup interrupts to 75 and 76 - works only on pure F303 // remap USB LP & Wakeup interrupts to 75 and 76 - works only on pure F303
@@ -326,6 +373,7 @@ void USB_setup(){
NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn); NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
NVIC_DisableIRQ(USB_HP_CAN1_TX_IRQn); NVIC_DisableIRQ(USB_HP_CAN1_TX_IRQn);
#elif defined STM32F0 #elif defined STM32F0
// All is clocking from HSI48
NVIC_DisableIRQ(USB_IRQn); NVIC_DisableIRQ(USB_IRQn);
RCC->APB1ENR |= RCC_APB1ENR_CRSEN; RCC->APB1ENR |= RCC_APB1ENR_CRSEN;
RCC->CFGR3 &= ~RCC_CFGR3_USBSW; // reset USB RCC->CFGR3 &= ~RCC_CFGR3_USBSW; // reset USB
@@ -338,16 +386,33 @@ void USB_setup(){
CRS->CR |= CRS_CR_AUTOTRIMEN; // enable auto trim CRS->CR |= CRS_CR_AUTOTRIMEN; // enable auto trim
CRS->CR |= CRS_CR_CEN; // enable freq counter & block CRS->CFGR as read-only CRS->CR |= CRS_CR_CEN; // enable freq counter & block CRS->CFGR as read-only
RCC->CFGR |= RCC_CFGR_SW; RCC->CFGR |= RCC_CFGR_SW;
#elif defined STM32G0
NVIC_DisableIRQ(USB_UCPD1_2_IRQn);
PWR->CR2 |= PWR_CR2_USV; // enable USB powering
//RCC->APBENR2 |= RCC_APBENR2_SYSCFGEN; // enable tacting of SYSCFG
// independent clocking of USB from HSI48
RCC->CR |= RCC_CR_HSI48ON;
uint32_t tmout = 16000000;
while(!(RCC->CR & RCC_CR_HSI48RDY)) if(--tmout == 0){ break;}
RCC->CCIPR2 &= ~RCC_CCIPR2_USBSEL; // select HSI48 for USB
RCC->APBENR1 |= RCC_APBENR1_CRSEN; // CRS clocking
CRS->CFGR = (31LL << CRS_CFGR_FELIM_Pos) | // tolerance (usually 31)
(48000LL / 1LL - 1LL) << CRS_CFGR_RELOAD_Pos | // 48MHz / 1kHZ (SOF)
CRS_CFGR_SYNCSRC_1; // USB SOF as sync source (0x2)
CRS->CR |= CRS_CR_AUTOTRIMEN | CRS_CR_CEN; // Enable autotrim and turn on Clock Recovery System
RCC->APBENR1 |= RCC_APBENR1_USBEN;
#endif #endif
#ifndef STM32G0
RCC->APB1ENR |= RCC_APB1ENR_USBEN; RCC->APB1ENR |= RCC_APB1ENR_USBEN;
//??
USB->CNTR = USB_CNTR_FRES; // Force USB Reset USB->CNTR = USB_CNTR_FRES; // Force USB Reset
for(uint32_t ctr = 0; ctr < 72000; ++ctr) nop(); // wait >1ms
USB->CNTR = 0;
USB->BTABLE = 0; USB->BTABLE = 0;
#else
USB->CNTR = USB_CNTR_USBRST;
#endif
for(uint32_t ctr = 0; ctr < 72000; ++ctr) nop(); // wait >1ms
USB->CNTR = USB_CNTR_RESETM; // allow only reset interrupts
USB->DADDR = 0; USB->DADDR = 0;
USB->ISTR = 0; USB->ISTR = 0;
USB->CNTR = USB_CNTR_RESETM; // allow only reset interrupts
#if defined STM32F3 #if defined STM32F3
NVIC_EnableIRQ(USB_LP_IRQn); NVIC_EnableIRQ(USB_LP_IRQn);
#elif defined STM32F1 #elif defined STM32F1
@@ -355,6 +420,9 @@ void USB_setup(){
#elif defined STM32F0 #elif defined STM32F0
USB->BCDR |= USB_BCDR_DPPU; USB->BCDR |= USB_BCDR_DPPU;
NVIC_EnableIRQ(USB_IRQn); NVIC_EnableIRQ(USB_IRQn);
#elif defined STM32G0
USB->BCDR |= USB_BCDR_DPPU; // turn ON DP pullup
NVIC_EnableIRQ(USB_UCPD1_2_IRQn);
#endif #endif
} }
@@ -365,4 +433,6 @@ void usb_lp_isr() __attribute__ ((alias ("USB_IRQ")));
void usb_lp_can_rx0_isr() __attribute__ ((alias ("USB_IRQ"))); void usb_lp_can_rx0_isr() __attribute__ ((alias ("USB_IRQ")));
#elif defined STM32F0 #elif defined STM32F0
void usb_isr() __attribute__ ((alias ("USB_IRQ"))); void usb_isr() __attribute__ ((alias ("USB_IRQ")));
#elif defined STM32G0
void usb_ucpd1_2_isr() __attribute__ ((alias ("USB_IRQ")));
#endif #endif

View File

@@ -19,6 +19,10 @@
#include <stdint.h> #include <stdint.h>
#include <wchar.h> #include <wchar.h>
#ifndef _U_
#define _U_ __attribute__((unused))
#endif
/****************************************************************** /******************************************************************
* Hardware registers etc * * Hardware registers etc *
*****************************************************************/ *****************************************************************/
@@ -30,6 +34,8 @@
#define USB_BASE ((uint32_t)0x40005C00) #define USB_BASE ((uint32_t)0x40005C00)
#elif defined STM32F3 #elif defined STM32F3
#include <stm32f3.h> #include <stm32f3.h>
#elif defined STM32G0
#include <stm32g0.h>
#endif #endif
// max endpoints number // max endpoints number
@@ -38,14 +44,16 @@
* Buffers size definition * Buffers size definition
**/ **/
// F0 - USB2_16; F1 - USB1_16; F3 - 1/2 depending on series // F0 - USB2_16; F1 - USB1_16; F3 - 1/2 depending on series; G0 - USB32
#if !defined USB1_16 && !defined USB2_16 #if !defined USB1_16 && !defined USB2_16 && !defined USB32
#if defined STM32F0 #if defined STM32F0
#define USB2_16 #define USB2_16
#elif defined STM32F1 #elif defined STM32F1
#define USB1_16 #define USB1_16
#elif defined STM32G0
#define USB32
#else #else
#error "Can't determine USB1_16 or USB2_16, define by hands" #error "Can't determine USB1_16/USB2_16/USB32, define by hands"
#endif #endif
#endif #endif
@@ -59,8 +67,8 @@
#if defined STM32F0 #if defined STM32F0
#define USB_BTABLE_SIZE 1024 #define USB_BTABLE_SIZE 1024
#elif defined STM32F3 #elif defined STM32F3
#define USB_BTABLE_SIZE 512 #define USB_BTABLE_SIZE 1024
#warning "Please, check real buffer size due to docs" //#warning "Please, check real buffer size due to docs"
#else #else
#error "define STM32F0 or STM32F3" #error "define STM32F0 or STM32F3"
#endif #endif
@@ -68,16 +76,21 @@
#if defined STM32F0 #if defined STM32F0
#define USB_BTABLE_SIZE 768 #define USB_BTABLE_SIZE 768
#elif defined STM32F3 #elif defined STM32F3
#define USB_BTABLE_SIZE 512 #define USB_BTABLE_SIZE 768
#warning "Please, check real buffer size due to docs" #elif defined STM32G0
#define USB_BTABLE_SIZE 2048
//#warning "Please, check real buffer size due to docs"
#else // STM32F103: 1024 bytes but with 32-bit addressing #else // STM32F103: 1024 bytes but with 32-bit addressing
#define USB_BTABLE_SIZE 1024 #define USB_BTABLE_SIZE 1024
#endif #endif
#endif // NOCAN #endif // NOCAN
// first 64 bytes of USB_BTABLE are registers! // first 64 bytes of USB_BTABLE are registers!
#ifndef STM32G0
#define USB_BTABLE_BASE 0x40006000 #define USB_BTABLE_BASE 0x40006000
#else
#define USB_BTABLE_BASE 0x40009800
#endif
#define USB ((USB_TypeDef *) USB_BASE) #define USB ((USB_TypeDef *) USB_BASE)
#ifdef USB_BTABLE #ifdef USB_BTABLE
@@ -120,8 +133,12 @@ typedef struct {
__IO uint32_t ISTR; __IO uint32_t ISTR;
__IO uint32_t FNR; __IO uint32_t FNR;
__IO uint32_t DADDR; __IO uint32_t DADDR;
#ifndef USB32
__IO uint32_t BTABLE; __IO uint32_t BTABLE;
#ifdef STM32F0 #else
__IO uint32_t RESERVED1; // there's no BTABLE register in STM32G0
#endif
#if defined STM32F0 || defined USB32
__IO uint32_t LPMCSR; __IO uint32_t LPMCSR;
__IO uint32_t BCDR; __IO uint32_t BCDR;
#endif #endif
@@ -135,16 +152,19 @@ typedef struct{
__IO uint16_t USB_ADDR_RX; __IO uint16_t USB_ADDR_RX;
__IO uint16_t USB_COUNT_RX; __IO uint16_t USB_COUNT_RX;
#define ACCESSZ (1) #define ACCESSZ (1)
#define BUFTYPE uint8_t
#elif defined USB1_16 #elif defined USB1_16
__IO uint32_t USB_ADDR_TX; __IO uint32_t USB_ADDR_TX;
__IO uint32_t USB_COUNT_TX; __IO uint32_t USB_COUNT_TX;
__IO uint32_t USB_ADDR_RX; __IO uint32_t USB_ADDR_RX;
__IO uint32_t USB_COUNT_RX; __IO uint32_t USB_COUNT_RX;
#define ACCESSZ (2) #define ACCESSZ (2)
#define BUFTYPE uint16_t #elif defined USB32
// 32-bit registers: addr & count in one!
__IO uint32_t USB_ADDR_COUNT_TX;
__IO uint32_t USB_ADDR_COUNT_RX;
#define ACCESSZ (1)
#else #else
#error "Define USB1_16 or USB2_16" #error "Define USB1_16 (16 bits over 32bit register), USB2_16 (16 bits over 16 bit register) or USB32 (32 bist over 32 bit register)"
#endif #endif
} USB_EPDATA_TypeDef; } USB_EPDATA_TypeDef;
@@ -303,9 +323,17 @@ typedef struct {
// endpoints state // endpoints state
typedef struct{ typedef struct{
#ifdef USB32
uint32_t *tx_buf; // transmission buffer address
#else
uint16_t *tx_buf; // transmission buffer address uint16_t *tx_buf; // transmission buffer address
#endif
uint16_t txbufsz; // transmission buffer size uint16_t txbufsz; // transmission buffer size
#ifdef USB32
uint32_t *rx_buf; // reception buffer address
#else
uint8_t *rx_buf; // reception buffer address uint8_t *rx_buf; // reception buffer address
#endif
void (*func)(); // endpoint action function void (*func)(); // endpoint action function
unsigned rx_cnt : 10; // received data counter unsigned rx_cnt : 10; // received data counter
} ep_t; } ep_t;