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 "proto.h"
#include "spi.h"
#include "strfunc.h"
#include "usb_dev.h"
#define CU(a) ((const uint8_t*)a)
@@ -315,7 +316,7 @@ void canon_proc(){
/*
case CANON_GETFOCM: // don't work @EF200
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;
*/
}
@@ -393,7 +394,7 @@ int canon_asku16(uint8_t cmd){
int canon_getinfo(){
if(!ready || !canon_read(CANON_GETINFO, 6)) return 1;
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();
USB_sendstr("\n");

View File

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

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!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>
<data>
<variable>EnvironmentId</variable>
@@ -13,8 +13,8 @@
<data>
<variable>ProjectExplorer.Project.EditorSettings</variable>
<valuemap type="QVariantMap">
<value type="bool" key="EditorConfiguration.AutoDetect">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>
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0">
<value type="QString" key="language">Cpp</value>
@@ -86,12 +86,14 @@
<valuelist type="QVariantList" key="ClangTools.SuppressedDiagnostics"/>
<value type="bool" key="ClangTools.UseGlobalSettings">true</value>
</valuemap>
<value type="int" key="RcSync">0</value>
</valuemap>
</data>
<data>
<variable>ProjectExplorer.Project.Target.0</variable>
<valuemap type="QVariantMap">
<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.DisplayName">Desktop</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>
</valuemap>
<value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Сборка</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Сборка</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Build</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Build</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1">
@@ -122,8 +124,8 @@
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericMakeStep</value>
</valuemap>
<value type="qlonglong" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Очистка</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Очистка</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Clean</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Clean</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value>
@@ -133,13 +135,46 @@
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">По умолчанию</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>
<value type="qlonglong" key="ProjectExplorer.Target.BuildConfigurationCount">1</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">Развёртывание</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Развёртывание</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>
@@ -161,6 +196,7 @@
<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>
@@ -171,10 +207,6 @@
<variable>ProjectExplorer.Project.TargetCount</variable>
<value type="qlonglong">1</value>
</data>
<data>
<variable>ProjectExplorer.Project.Updater.FileVersion</variable>
<value type="int">22</value>
</data>
<data>
<variable>Version</variable>
<value type="int">22</value>

View File

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

View File

@@ -25,6 +25,7 @@
#include "flash.h"
#include "proto.h"
#include "strfunc.h"
#include "usb_dev.h" // printout
#include <string.h> // memcpy
@@ -145,7 +146,7 @@ static int write2flash(const void *start, const void *wrdata, uint32_t stor_size
}
#ifdef EBUG
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
FLASH->SR = FLASH_SR_EOP | FLASH_SR_PGERR | FLASH_SR_WRPRTERR;
}

View File

@@ -49,13 +49,11 @@ int main(void){
uint32_t SPIctr = Tms;
while(1){
IWDG->KR = IWDG_REFRESH;
int l = USB_receivestr(inbuff, 255);
if(l > 0){
parse_cmd(inbuff); // call it even for NULL (if `flood` is running)
if(Tms - SPIctr > CANONPROC_INTERVAL){ // not more than once per 10ms
SPIctr = Tms;
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 "proto.h"
#include "spi.h"
#include "strfunc.h"
#include "usb_dev.h"
#include "version.inc"
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 =
"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"
@@ -213,7 +84,7 @@ static void sendspibuf(){
USB_sendstr("Got SPI answer: ");
for(int i = 0; i < spibuflen; ++i){
if(i) USB_sendstr(", ");
USB_sendstr(u2hexstr(buf[i]));
USB_sendstr(uhex2str(buf[i]));
}
USB_sendstr("\n");
}else USB_sendstr("Failed to send SPI buffer\n");
@@ -284,7 +155,7 @@ void parse_cmd(const char *buf){
USB_sendstr(OK);
break;
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;
case 'G':
USB_sendstr("SPI ");
@@ -344,7 +215,7 @@ void parse_cmd(const char *buf){
}
uint32_t D = 0;
int16_t neg;
char *nxt;
const char *nxt;
switch(*buf++){ // long messages
case 'a': // move focus to absolute position
buf = omit_spaces(buf);
@@ -425,7 +296,7 @@ void parse_cmd(const char *buf){
USB_sendstr(helpmsg);
return;
}
USB_sendstr("SPI_CR1="); USB_sendstr(u2hexstr(SPI_CR1));
USB_sendstr("SPI_CR1="); USB_sendstr(uhex2str(SPI_CR1));
break;
case 'L':
if(0 == initspibuf(buf)){
@@ -445,7 +316,7 @@ void parse_cmd(const char *buf){
USB_sendstr("Send: ");
for(int i = 0; i < spibuflen; ++i){
if(i) USB_sendstr(", ");
USB_sendstr(u2hexstr(spibuf[i]));
USB_sendstr(uhex2str(spibuf[i]));
}
USB_sendstr("\n");
sendspibuf();
@@ -456,41 +327,3 @@ void parse_cmd(const char *buf){
}
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
#ifndef PROTO_H__
#define PROTO_H__
#include <stm32f1.h>
#define printu(x) do{USB_sendstr(u2str(x));}while(0)
#define printuhex(x) do{USB_sendstr(uhex2str(x));}while(0)
#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
#define DBG(x)
#endif
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/>.
*/
#include <string.h>
#include <stm32f1.h>
#include "ringbuffer.h"
static int datalen(ringbuffer *b){
@@ -24,7 +26,7 @@ static int datalen(ringbuffer *b){
// stored data length
int RB_datalen(ringbuffer *b){
if(b->busy) return -1;
if(!b || b->busy) return -1;
b->busy = 1;
int l = datalen(b);
b->busy = 0;
@@ -32,7 +34,7 @@ int RB_datalen(ringbuffer *b){
}
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;
if(b->head > b->tail){ //
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
*/
int RB_hasbyte(ringbuffer *b, uint8_t byte){
if(b->busy) return -1;
if(!b || b->busy) return -1;
b->busy = 1;
int ret = hasbyte(b, byte);
b->busy = 0;
return ret;
}
// poor memcpy
static void mcpy(uint8_t *targ, const uint8_t *src, int l){
while(l--) *targ++ = *src++;
}
// increment head or tail
TRUE_INLINE void incr(ringbuffer *b, volatile int *what, int n){
*what += n;
@@ -76,9 +73,9 @@ static int read(ringbuffer *b, uint8_t *s, int len){
int _1st = b->length - b->head;
if(_1st > l) _1st = l;
if(_1st > len) _1st = len;
mcpy(s, b->data + b->head, _1st);
memcpy(s, b->data + b->head, _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);
return l;
}
@@ -94,20 +91,27 @@ static int read(ringbuffer *b, uint8_t *s, int len){
* @return bytes read or -1 if busy
*/
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;
int r = read(b, s, len);
b->busy = 0;
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);
if(idx < 0) return 0;
int partlen = idx + 1 - b->head;
// now calculate length of new data portion
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);
}
@@ -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)
* @param b - ringbuffer
* @param byte - check byte
* @param s - buffer to write data
* @param len - length of `s`
* @param s - buffer to write data or NULL to clear data
* @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)
*/
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;
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;
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){
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;
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
mcpy(b->data, str+_1st, l-_1st);
memcpy(b->data, str+_1st, l-_1st);
}
incr(b, &b->tail, 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
*/
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;
int w = write(b, str, l);
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`
int RB_clearbuf(ringbuffer *b){
if(b->busy) return -1;
if(!b || b->busy) return -1;
b->busy = 1;
b->head = 0;
b->tail = 0;

View File

@@ -17,13 +17,7 @@
#pragma once
#if defined STM32F0
#include <stm32f0.h>
#elif defined STM32F1
#include <stm32f1.h>
#elif defined STM32F3
#include <stm32f3.h>
#endif
#include <stdint.h>
typedef struct{
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_write(ringbuffer *b, const uint8_t *str, int l);
int RB_datalen(ringbuffer *b);
int RB_datalento(ringbuffer *b, uint8_t byte);
int RB_clearbuf(ringbuffer *b);

View File

@@ -21,9 +21,10 @@
#include "spi.h"
#include "hardware.h"
#ifdef EBUG
#include "usb.h"
#include "usb_dev.h"
#endif
#include "proto.h"
#include "strfunc.h"
/*
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(SPI_status != SPI_READY) return 0; // spi not ready to transmit data
#ifdef EBUG
USB_send("SPI send "); USB_send(u2str(len));
USB_send("bytes, data: ");
USB_sendstr("SPI send "); USB_sendstr(u2str(len));
USB_sendstr("bytes, data: ");
#endif
for(uint8_t x = 0; x < len; ++x){
WAITX(!(SPI1->SR & SPI_SR_TXE));
SPI1->DR = buf[x];
WAITX(!(SPI1->SR & SPI_SR_BSY));
#ifdef EBUG
USB_send(u2hexstr(buf[x])); USB_send(", ");
USB_sendstr(uhex2str(buf[x])); USB_sendstr(", ");
#endif
WAITX(!(SPI1->SR & SPI_SR_RXNE));
buf[x] = SPI1->DR;
for(int ctr = 0; ctr < 3600; ++ctr) IWDG->KR = IWDG_REFRESH; // ~100mks delay
}
#ifdef EBUG
USB_send("\nReceive: ");
USB_sendstr("\nReceive: ");
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
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
L16(bcdUSB), // bcdUSB_L
H16(bcdUSB), // bcdUSB_H
USB_CLASS_COMM, // bDeviceClass
USB_CLASS_MISC, // bDeviceClass
bDeviceSubClass, // bDeviceSubClass
bDeviceProtocol, // bDeviceProtocol
USB_EP0BUFSZ, // bMaxPacketSize
@@ -140,7 +140,7 @@ static const uint8_t USB_ConfigDescriptor[] = {
//const uint8_t HID_ReportDescriptor[];
_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_(PD, u"USB/CAN Canon lens controller");
_USB_STRING_(ID, u"canonlens");

View File

@@ -15,7 +15,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stm32f1.h>
#include <string.h>
#include "ringbuffer.h"
@@ -41,10 +40,10 @@
static volatile uint8_t bufovrfl = 0;
// 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;
// line coding
usb_LineCoding WEAK lineCoding = {115200, 0, 0, 8};
usb_LineCoding lineCoding = {115200, 0, 0, 8};
// CDC configured and ready to use
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
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);
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;
return;
}else if(buflen < 0){
@@ -103,21 +102,20 @@ static void rxtx_handler(){
// weak handlers: change them somewhere else if you want to setup USART
// SET_LINE_CODING
void WEAK linecoding_handler(usb_LineCoding *lc){
void linecoding_handler(usb_LineCoding *lc){
lineCoding = *lc;
}
// 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
}
// SEND_BREAK
void WEAK break_handler(){
void break_handler(){
CDCready = 0;
}
// USB is configured: setup endpoints
void set_configuration(){
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){
if(!buf || !CDCready || !len) return FALSE;
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){
len -= 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
* @param buf - receiving buffer
* @param len - its length
* @return strlen or negative value indicating overflow (if so, string won't be ends with 0 and buffer should be cleared)
* @return strlen or negative value indicating overflow
*/
int USB_receivestr(char *buf, int len){
chkin();
@@ -226,14 +233,18 @@ int USB_receivestr(char *buf, int len){
bufovrfl = 0;
return -1;
}
int l = RB_readto((ringbuffer*)&rbin, '\n', (uint8_t*)buf, len);
if(l < 1){
int l = RB_datalento((ringbuffer*)&rbin, '\n');
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
while(1 != RB_clearbuf((ringbuffer*)&rbin));
return -1;
}
return 0;
}
l = RB_readto((ringbuffer*)&rbin, '\n', (uint8_t*)buf, len);
if(l == 0) return 0;
buf[l-1] = 0; // replace '\n' with strend
return l;

View File

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

View File

@@ -23,7 +23,7 @@
static ep_t endpoints[STM32ENDPOINTS];
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;
volatile uint8_t usbON = 0; // device is configured and active
@@ -81,8 +81,7 @@ void WEAK usb_standard_request(){
break;
case REQ_RECIPIENT_ENDPOINT:
if(setup_packet->bRequest == CLEAR_FEATURE){
}else{
}
}else{ /* wrong */ }
break;
default:
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
break;
default:
break;
break;
}
if(0 == (setup_packet->bmRequestType & 0x80)) // host2dev
EP_WriteIRQ(0, NULL, 0);
@@ -119,7 +118,7 @@ bmRequestType: 76543210
*/
static void EP0_Handler(){
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
int rxflag = RX_FLAG(epstatus);
// check direction
@@ -128,6 +127,7 @@ static void EP0_Handler(){
EP_Read(0, setupdatabuf);
// interrupt handler will be called later
}else if(epstatus & USB_EPnR_CTR_RX){ // data packet -> push received data to ep0databuf
//if(endpoints[0].rx_cnt){ }
ep0dbuflen = EP_Read(0, ep0databuf);
}
}
@@ -137,8 +137,7 @@ static void EP0_Handler(){
case REQ_TYPE_STANDARD:
if(SETUP_FLAG(epstatus)){
usb_standard_request();
}else{
}
}else{ }
break;
case REQ_TYPE_CLASS:
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){
if(size > endpoints[number].txbufsz) size = endpoints[number].txbufsz;
#ifndef USB32
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;
#else
int N4 = (size + 3) >> 2;
uint32_t *buf32 = (uint32_t *)buf;
#endif
#if defined USB1_16
// very bad: what if `size` is odd?
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
// use memcpy instead?
for(int i = 0; i < N2; i++){
for(int i = 0; i < N2; ++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
#error "Define USB1_16 or USB2_16"
#error "Define USB1_16 / USB2_16 / USB32"
#endif
#ifndef USB32
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?
for(int i = 0; i < sz; ++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
#error "Define USB1_16 or USB2_16"
#error "Define USB1_16 / USB2_16 / USB32"
#endif
return sz;
}
@@ -243,11 +257,16 @@ static uint16_t lastaddr = LASTADDR_DEFAULT;
* @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)){
#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(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
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
uint16_t countrx = 0;
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
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);
#endif
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_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);
lastaddr += rxsz;
USB_BTABLE->EP[number].USB_ADDR_RX = lastaddr;
USB_BTABLE->EP[number].USB_COUNT_RX = countrx << 10;
#endif
lastaddr += rxsz;
endpoints[number].func = func;
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(){
uint32_t CNTR = USB->CNTR;
USB->CNTR = 0;
if(USB->ISTR & USB_ISTR_RESET){
uint32_t istr = USB->ISTR;
if(istr & USB_ISTR_RESET){
usbON = 0;
// Reinit registers
CNTR = USB_CNTR_RESETM | USB_CNTR_CTRM | USB_CNTR_SUSPM;
@@ -281,42 +314,56 @@ void USB_IRQ(){
lastaddr = LASTADDR_DEFAULT;
// clear address, leave only enable bit
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)){
return;
};
}
if(USB->ISTR & USB_ISTR_CTR){
if(istr & USB_ISTR_CTR){
// 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
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
if(endpoints[n].func) endpoints[n].func();
}
if(USB->ISTR & USB_ISTR_WKUP){ // wakeup
#ifndef STM32F0
CNTR &= ~(USB_CNTR_FSUSP | USB_CNTR_LP_MODE | USB_CNTR_WKUPM); // clear suspend flags
#else
if(istr & USB_ISTR_WKUP){ // wakeup
#if defined STM32F0
CNTR &= ~(USB_CNTR_FSUSP | USB_CNTR_LPMODE | USB_CNTR_WKUPM);
#endif
USB->ISTR = ~USB_ISTR_WKUP;
}
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;
#elif defined STM32G0
CNTR &= ~(USB_CNTR_SUSPEN | USB_CNTR_PDWN | USB_CNTR_WKUPM);
#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;
#elif defined STM32G0
CNTR |= USB_CNTR_SUSPEN | USB_CNTR_WKUPM;
#else
CNTR |= USB_CNTR_FSUSP | USB_CNTR_LP_MODE | USB_CNTR_WKUPM;
#endif
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
}
// here we suppose that all PIN settings done in hw_setup earlier
void USB_setup(){
lastaddr = LASTADDR_DEFAULT; // clear last address settings
#if defined STM32F3
NVIC_DisableIRQ(USB_LP_IRQn);
// 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_HP_CAN1_TX_IRQn);
#elif defined STM32F0
// All is clocking from HSI48
NVIC_DisableIRQ(USB_IRQn);
RCC->APB1ENR |= RCC_APB1ENR_CRSEN;
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_CEN; // enable freq counter & block CRS->CFGR as read-only
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
#ifndef STM32G0
RCC->APB1ENR |= RCC_APB1ENR_USBEN;
//??
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;
#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->ISTR = 0;
USB->CNTR = USB_CNTR_RESETM; // allow only reset interrupts
#if defined STM32F3
NVIC_EnableIRQ(USB_LP_IRQn);
#elif defined STM32F1
@@ -355,6 +420,9 @@ void USB_setup(){
#elif defined STM32F0
USB->BCDR |= USB_BCDR_DPPU;
NVIC_EnableIRQ(USB_IRQn);
#elif defined STM32G0
USB->BCDR |= USB_BCDR_DPPU; // turn ON DP pullup
NVIC_EnableIRQ(USB_UCPD1_2_IRQn);
#endif
}
@@ -365,4 +433,6 @@ void usb_lp_isr() __attribute__ ((alias ("USB_IRQ")));
void usb_lp_can_rx0_isr() __attribute__ ((alias ("USB_IRQ")));
#elif defined STM32F0
void usb_isr() __attribute__ ((alias ("USB_IRQ")));
#elif defined STM32G0
void usb_ucpd1_2_isr() __attribute__ ((alias ("USB_IRQ")));
#endif

View File

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