add RS-485

This commit is contained in:
Edward Emelianov
2026-11-23 23:10:03 +03:00
parent 140155460e
commit f1a455947f
17 changed files with 372 additions and 63 deletions

View File

@@ -28,8 +28,9 @@ Key features:
| PA5 | SPI1 SCK | SPI clock |
| PA6 | SPI1 MISO | SPI Master In / Slave Out |
| PA7 | SPI1 MOSI | SPI Master Out / Slave In |
| PA9 | USART1 Tx | (unused in this version) |
| PA10 | USART1 Rx | (unused) |
| PA8 | DE | RS-485 Tx enable / Rx disable |
| PA9 | USART1 Tx | RS-485 Tx |
| PA10 | USART1 Rx | RS-485 Rx |
| PA15 | GPIO | USB D+ pull-up control (1.5 kΩ) |
| PC13 | GPIO | On-board LED (active low) |
@@ -183,6 +184,7 @@ These commands do not require a channel number.
| `setiface` | Get/set the USB interface name string (max 16 characters) |
| `time` | Current uptime in milliseconds |
| `vdd` | Supply voltage VDD in hundredths of a volt (e.g., 330 = 3.30 V) |
| `usartspeed` | Get/set RS-485 baudrate (1200..921600) |
**Examples:**

Binary file not shown.

View File

@@ -23,7 +23,7 @@
#define MODE_WRITE (0)
#define MODE_MASK (0x3f)
extern uint32_t Tms;
extern volatile uint32_t Tms;
// read one register
int as3935_read(uint8_t reg, uint8_t *data){
@@ -126,6 +126,7 @@ int as3935_get_calib(uint8_t *n){
// wakeup - call this function after first run
int as3935_wakeup(){
t_afe_gain g;
if(!as3935_live()) return FALSE;
if(!as3935_read(AFE_GAIN, &g.u8)) return FALSE;
g.PWD = 0;
if(!as3935_write(AFE_GAIN, g.u8)) return FALSE;
@@ -216,7 +217,12 @@ int as3935_clearstat(){
t_lightning_reg lr;
if(!as3935_read(LIGHTNING_REG, &lr.u8)) return FALSE;
lr.CL_STAT = 1;
return as3935_write(LIGHTNING_REG, lr.u8);
if(!as3935_write(LIGHTNING_REG, lr.u8)) return FALSE;
lr.CL_STAT = 0;
if(!as3935_write(LIGHTNING_REG, lr.u8)) return FALSE;
lr.CL_STAT = 1;
if(!as3935_write(LIGHTNING_REG, lr.u8)) return FALSE;
return TRUE;
}
// get interrupt code
@@ -289,3 +295,22 @@ int as3935_distance(uint8_t *d){
int as3935_resetdef(){
return as3935_write(PRESET_DEFAULT, DIRECT_COMMAND);
}
/**
* Check if AS3935 sensor on current channel responds with valid register signature.
* @return 1 if sensor is alive, 0 if missing or bus error
*/
int as3935_live(){
uint8_t r00, r02, r08;
if(!as3935_read(AFE_GAIN, &r00)) return 0;
if(!as3935_read(LIGHTNING_REG, &r02)) return 0;
if(!as3935_read(TUN_DISP, &r08)) return 0;
// If MISO is stuck low (0x00) or high (0xFF), these checks will fail:
// REG 0x00: bits [7:6] are reserved and always 0
if((r00 & 0xC0) != 0x00) return 0;
// REG 0x02: bit [7] (reserved) is 1
if((r02 & 0x80) != 0x80) return 0;
// REG 0x08: bit [4] is reserved and always 0
if((r08 & 0x10) != 0x00) return 0;
return 1;
}

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 19.0.1, 2026-04-25T20:44:46. -->
<!-- Written by QtCreator 20.0.2, 2026-11-23T23:08:56. -->
<qtcreator>
<data>
<variable>EnvironmentId</variable>
@@ -14,8 +14,6 @@
<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.CamelCaseNavigation">true</value>
<valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0">
<value type="QString" key="language">Cpp</value>
<valuemap type="QVariantMap" key="value">
@@ -30,33 +28,14 @@
</valuemap>
<value type="qlonglong" key="EditorConfiguration.CodeStyle.Count">2</value>
<value type="QByteArray" key="EditorConfiguration.Codec">KOI8-R</value>
<value type="bool" key="EditorConfiguration.ConstrainTooltips">false</value>
<value type="int" key="EditorConfiguration.IndentSize">4</value>
<value type="bool" key="EditorConfiguration.KeyboardTooltips">false</value>
<value type="int" key="EditorConfiguration.LineEndingBehavior">0</value>
<value type="int" key="EditorConfiguration.MarginColumn">80</value>
<value type="bool" key="EditorConfiguration.MouseHiding">true</value>
<value type="bool" key="EditorConfiguration.MouseNavigation">true</value>
<value type="int" key="EditorConfiguration.PaddingMode">1</value>
<value type="int" key="EditorConfiguration.PreferAfterWhitespaceComments">0</value>
<value type="bool" key="EditorConfiguration.PreferSingleLineComments">false</value>
<value type="bool" key="EditorConfiguration.ScrollWheelZooming">true</value>
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</value>
<value type="bool" key="EditorConfiguration.SmartSelectionChanging">true</value>
<value type="bool" key="EditorConfiguration.SpacesForTabs">true</value>
<value type="int" key="EditorConfiguration.TabKeyBehavior">0</value>
<value type="int" key="EditorConfiguration.TabSize">8</value>
<value type="bool" key="EditorConfiguration.UseGlobal">true</value>
<value type="bool" key="EditorConfiguration.UseIndenter">false</value>
<value type="int" key="EditorConfiguration.Utf8BomBehavior">1</value>
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
<value type="bool" key="EditorConfiguration.cleanIndentation">false</value>
<value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
<value type="QString" key="EditorConfiguration.ignoreFileTypes">*.md, *.MD, Makefile</value>
<value type="bool" key="EditorConfiguration.inEntireDocument">false</value>
<value type="bool" key="EditorConfiguration.skipTrailingWhitespace">true</value>
<value type="bool" key="EditorConfiguration.tintMarginArea">true</value>
</valuemap>
</data>
<data>
@@ -76,11 +55,7 @@
<value type="int" key="AutoTest.RunAfterBuild">0</value>
<value type="bool" key="AutoTest.UseGlobal">true</value>
<valuemap type="QVariantMap" key="ClangTools">
<value type="bool" key="ClangTools.AnalyzeOpenFiles">true</value>
<value type="bool" key="ClangTools.BuildBeforeAnalysis">true</value>
<value type="QString" key="ClangTools.DiagnosticConfig">Builtin.DefaultTidyAndClazy</value>
<value type="int" key="ClangTools.ParallelJobs">8</value>
<value type="bool" key="ClangTools.PreferConfigFile">true</value>
<value type="Utils::Id" key="ClangTools.DiagnosticConfig"></value>
<valuelist type="QVariantList" key="ClangTools.SelectedDirs"/>
<valuelist type="QVariantList" key="ClangTools.SelectedFiles"/>
<valuelist type="QVariantList" key="ClangTools.SuppressedDiagnostics"/>
@@ -131,7 +106,7 @@
<value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.CustomParsers"/>
<value type="bool" key="ProjectExplorer.BuildConfiguration.ParseStandardOutput">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
<value type="UnknownType" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Default</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">GenericProjectManager.GenericBuildConfiguration</value>
<value type="qlonglong" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value>
@@ -158,7 +133,7 @@
<value type="QList&lt;int&gt;" key="Analyzer.Valgrind.VisibleErrorKinds"></value>
<valuelist type="QVariantList" key="CustomOutputParsers"/>
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
<value type="UnknownType" key="PE.EnvironmentAspect.Changes"></value>
<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>
@@ -194,7 +169,7 @@
<value type="QList&lt;int&gt;" key="Analyzer.Valgrind.VisibleErrorKinds"></value>
<valuelist type="QVariantList" key="CustomOutputParsers"/>
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
<value type="UnknownType" key="PE.EnvironmentAspect.Changes"></value>
<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>

View File

@@ -121,6 +121,8 @@ typedef union{
// distance out of range
#define DIST_OUT_OF_RANGE (0x3f)
int as3935_live();
int as3935_read(uint8_t reg, uint8_t *data);
int as3935_write(uint8_t reg, uint8_t data);
int as3935_wakeup();

View File

@@ -28,6 +28,7 @@ extern "C"{
#include "hardware.h"
#include "spi.h"
#include "strfunc.h"
#include "usart.h"
}
// sending function
@@ -66,6 +67,7 @@ static uint8_t curbuf[MAXSTRLEN];
COMMAND(srej, "spike rejection (0..15)") \
COMMAND(time, "show current time (ms)") \
COMMAND(tuncap, "set 'tune capasitors' to given value (0..15)") \
COMMAND(usartspeed, "get/set RS-485 speed (1200..921600)") \
COMMAND(vdd, "get approx Vdd value (V*100)") \
COMMAND(wakeup, "wake-up given sensor and make its calibration") \
COMMAND(wdthres, "watchdog threshold (0..15)" )
@@ -171,6 +173,7 @@ static errcodes_t cmd_readconf(const char*, char* args){
splitargs(args, &CHno);
if(CHno < 0 || CHno >= SENSORS_AMOUNT) return ERR_BADPAR;
as3935_channel = static_cast<uint8_t>(CHno);
if(!as3935_live()) return ERR_CANTRUN;
uint8_t par;
if(!as3935_get_gain(&par)) return ERR_CANTRUN;
the_conf.spars[CHno].AFE_GB = par;
@@ -236,10 +239,11 @@ static void showpar(const char *par, uint8_t n, uint8_t v){
static errcodes_t cmd_dumpconf(const char*, char*){
SEND("userconf_sz="); SEND(u2str(the_conf.userconf_sz));
SEND("\ncurr_idx="); SEND(u2str(currentconfidx));
SEND("\ncurr_idx="); SEND(i2str(currentconfidx));
SEND("\ncapacity="); SEND(u2str(maxCnum-2));
cmd_setiface("\nsetiface", NULL);
cmd_restonstart("restonstart", NULL);
cmd_usartspeed("usartspeed", NULL);
for(int i = 0; i < SENSORS_AMOUNT; ++i){
showpar("gain", i, the_conf.spars[i].AFE_GB);
showpar("\nlco_fdiv", i, the_conf.spars[i].LCO_FDIV);
@@ -280,6 +284,7 @@ static errcodes_t senscmd8(int32_t CHno, int (*cmd)(uint8_t), int32_t arg){
if(CHno < 0 || CHno >= SENSORS_AMOUNT) return ERR_BADPAR;
uint8_t par = static_cast<uint8_t>(arg);
as3935_channel = static_cast<uint8_t>(CHno);
if(!as3935_live()) return ERR_CANTRUN;
int ans = cmd(par);
if(ans) return ERR_OK;
return ERR_CANTRUN;
@@ -289,6 +294,7 @@ static errcodes_t getta(const char *cmd, int32_t CHno, int (*fn)(uint8_t*)){
if(CHno < 0 || CHno >= SENSORS_AMOUNT) return ERR_BADPAR;
uint8_t par;
as3935_channel = static_cast<uint8_t>(CHno);
if(!as3935_live()) return ERR_CANTRUN;
int ans = fn(&par);
if(!ans) return ERR_CANTRUN;
CMDEQP(CHno); SEND(u2str(par)); SEND("\n");
@@ -298,6 +304,7 @@ static errcodes_t getta(const char *cmd, int32_t CHno, int (*fn)(uint8_t*)){
static errcodes_t senscmd(int32_t CHno, int (*cmd)()){
if(CHno < 0 || CHno >= SENSORS_AMOUNT) return ERR_BADPAR;
as3935_channel = static_cast<uint8_t>(CHno);
if(!as3935_live()) return ERR_CANTRUN;
int ans = cmd();
if(ans) return ERR_OK;
return ERR_CANTRUN;
@@ -340,6 +347,7 @@ static errcodes_t cmd_ ## nm(const char* cmd, char* args){ \
splitargs(args, &CHno); \
if(CHno < 0 || CHno >= SENSORS_AMOUNT) return ERR_BADPAR; \
as3935_channel = static_cast<uint8_t>(CHno); \
if(!as3935_live()) return ERR_CANTRUN; \
int ans = as3935_ ## nm(&par); \
if(!ans) return ERR_CANTRUN; \
CMDEQP(CHno); SEND(u2str(par)); SEND("\n"); \
@@ -368,11 +376,25 @@ static errcodes_t cmd_energy(const char* cmd, char* args){
splitargs(args, &CHno);
if(CHno < 0 || CHno >= SENSORS_AMOUNT) return ERR_BADPAR;
as3935_channel = static_cast<uint8_t>(CHno);
if(!as3935_live()) return ERR_CANTRUN;
if(!as3935_energy(&par)) return ERR_CANTRUN;
CMDEQP(CHno); SEND(u2str(par)); SEND("\n");
return ERR_AMOUNT;
}
static errcodes_t cmd_usartspeed(const char *cmd, char *args){
int32_t val;
if(argsvals(args, NULL, &val)){ // setter
if(val < 1200 || val > 921600) return ERR_BADVAL;
the_conf.usartspeed = (uint32_t)val;
usart_setup(the_conf.usartspeed);
}
CMDEQ();
SEND(u2str(the_conf.usartspeed));
SEND("\n");
return ERR_AMOUNT;
}
/**
* @brief parse_hex_data - data parsing in case of `hex + text` input format
* @param input - input string

View File

@@ -32,6 +32,7 @@ static int write2flash(const void*, const void*, uint32_t);
const user_conf *Flash_Data = (const user_conf *)(&__varsstart);
user_conf the_conf = {
.userconf_sz = sizeof(user_conf),
.usartspeed = 115200,
};
int currentconfidx = -1; // index of current configuration
@@ -78,6 +79,7 @@ void flashstorage_init(){
if(currentconfidx > -1){
memcpy(&the_conf, &Flash_Data[currentconfidx], sizeof(user_conf));
}
if(the_conf.usartspeed < 1200 || the_conf.usartspeed > 1000000) the_conf.usartspeed = 115200;
}
// store new configuration

View File

@@ -50,9 +50,10 @@ typedef struct{
/*
* struct to save user configurations
*/
typedef struct __attribute__((packed, aligned(4))){
uint16_t userconf_sz; // "magick number"
typedef struct __attribute__((aligned(4))){
uint16_t userconf_sz; // "magick number"
uint16_t iInterface[MAX_IINTERFACE_SZ]; // interface name
uint32_t usartspeed; // RS-485 baudrate
uint8_t iIlength; // length in symbols
sens_pars_t spars[SENSORS_AMOUNT]; // sensors' stored flags
flags_t flags; // common flags

View File

@@ -26,8 +26,9 @@
* PA2 - CS0 - PP out
* PA3 - CS1 - PP out
* PA5 - SPI1 SCK
* PA6 - SPI1 MISO
* PA6 - SPI1 MISO (int. pulldown)
* PA7 - SPI1 MOSI
* PA8 - RS-485 DE
* PA9 - USART1 Tx
* PA10- USART1 Rx
*/
@@ -42,9 +43,10 @@ static inline void gpio_setup(){
// PA pins
GPIOA->ODR = 0; // for pull-down
GPIOA->CRL = CRL(0, CNF_PUDINPUT|MODE_INPUT) | CRL(1, CNF_PUDINPUT|MODE_INPUT) | CRL(2, CNF_PPOUTPUT|MODE_SLOW) |
CRL(3, CNF_PPOUTPUT|MODE_SLOW) | CRL(5, CNF_AFPP|MODE_FAST) | CRL(6, CNF_FLINPUT|MODE_INPUT) | CRL(7, CNF_AFPP|MODE_FAST);
GPIOA->CRH = CRH(9, CNF_AFPP|MODE_FAST) | CRH(10, CNF_FLINPUT|MODE_INPUT) | CRH(15, CNF_PPOUTPUT|MODE_SLOW);
CRL(3, CNF_PPOUTPUT|MODE_SLOW) | CRL(5, CNF_AFPP|MODE_FAST) | CRL(6, CNF_PUDINPUT|MODE_INPUT) | CRL(7, CNF_AFPP|MODE_FAST);
GPIOA->CRH = CRH(8, CNF_PPOUTPUT|MODE_FAST) | CRH(9, CNF_AFPP|MODE_FAST) | CRH(10, CNF_FLINPUT|MODE_INPUT) | CRH(15, CNF_PPOUTPUT|MODE_SLOW);
CS_OFF();
RS485_RX();
}
void hw_setup(){

View File

@@ -27,6 +27,10 @@
#define LED0_port GPIOC
#define LED0_pin (1<<13)
// RS-485 receive/transmit (PA8: 0-Rx, 1-Tx)
#define RS485_TX() pin_set(GPIOA, (1<<8))
#define RS485_RX() pin_clear(GPIOA, (1<<8))
// USB pullup (not present in bluepill, should be soldered) - PA15
#define USBPU_port GPIOA
#define USBPU_pin (1<<15)
@@ -51,6 +55,7 @@ enum{
DISPLCO_LCO
};
extern volatile uint32_t Tms;
extern uint8_t DISPLCO[SENSORS_AMOUNT];
void hw_setup();

View File

@@ -23,6 +23,7 @@
#include "flash.h"
#include "spi.h"
#include "strfunc.h"
#include "usart.h"
#include "usb_dev.h"
uint8_t DISPLCO[SENSORS_AMOUNT] = {0};
@@ -35,25 +36,31 @@ void sys_tick_handler(void){
++Tms;
}
// functions to send lightning events to both interfaces
static int both_sendstr(const char *str){
USB_sendstr(str);
return usart_send(str);
}
static void both_putchar(char ch){
USB_putbyte(ch);
usart_putchar(ch);
}
int main(){
uint8_t oldint[2] = {0}; // ==1 for interrupted pins
uint8_t oldint[SENSORS_AMOUNT] = {0}; // ==1 for interrupted pins
uint32_t lastT = 0;
StartHSE();
//flashstorage_init();
hw_setup();
USBPU_OFF();
SysTick_Config(72000);
flashstorage_init();
USB_setup();
#ifndef EBUG
iwdg_setup();
#endif
//usart_setup();
usart_setup(the_conf.usartspeed);
USBPU_ON();
// wake-up all sensors and run auto-calibration
for(uint8_t ch = 0; ch < SENSORS_AMOUNT; ++ch){
as3935_channel = ch;
as3935_wakeup();
if(!as3935_wakeup()) continue;
as3935_calib_rco();
if(the_conf.flags.restore){
sens_pars_t *p = &the_conf.spars[ch];
@@ -67,18 +74,34 @@ int main(){
as3935_tuncap(p->TUN_CAP);
}
}
#ifndef EBUG
iwdg_setup();
#endif
while(1){
IWDG->KR = IWDG_REFRESH; // refresh watchdog
if(Tms - lastT > 499){
LED_blink(LED0);
lastT = Tms;
//usart_send("Test\n");
}
// USB parser
int l = USB_receivestr(inbuff, RBINSZ);
if(l < 0) USB_sendstr("ERROR: CMD USB buffer overflow or string was too long");
else if(l){
const char *ans = parse_cmd(USB_sendstr, inbuff);
if(ans) USB_sendstr(ans);
}
// USART parser
char *ustr;
int ul = usart_getline(&ustr);
if(ul < 0){
usart_send("OVERFLOW\n");
usart_transmit();
}else if(ul > 0){
const char *ans = parse_cmd(usart_send, ustr);
if(ans) usart_send(ans);
usart_transmit();
}
for(uint8_t ch = 0; ch < SENSORS_AMOUNT; ++ch){
if(DISPLCO[ch] != DISPLCO_NOTHING) continue; // don't check IRQ in if it used as clock output
if(CHK_INT(ch)){
@@ -87,23 +110,27 @@ int main(){
uint8_t code;
as3935_channel = ch;
int result = as3935_intcode(&code);
if(!result) USB_sendstr("CANTGET\n");
else if(code){
if(!result){
both_sendstr("CANTGET\n");
}else if(code){
uint8_t savedcode = code;
USB_sendstr("INTERRUPT"); USB_putbyte('0'+ch); USB_putbyte('=');
both_sendstr("INTERRUPT"); both_putchar('0'+ch); both_putchar('=');
const char *delim = NULL, *comma = ",";
if(code & INT_NH){ USB_sendstr("NOICE"); delim = comma; code &= ~INT_NH; }
if(code & INT_D){ USB_sendstr(delim); USB_sendstr("DISTURBER"); delim = comma; code &= ~INT_D; }
if(code & INT_L){ USB_sendstr(delim); USB_sendstr("LIGHTNING"); code &= ~INT_L; }
if(code) USB_sendstr(u2str(code));
newline();
if(code & INT_NH){ both_sendstr("NOICE"); delim = comma; code &= ~INT_NH; }
if(code & INT_D){ both_sendstr(delim); both_sendstr("DISTURBER"); delim = comma; code &= ~INT_D; }
if(code & INT_L){ both_sendstr(delim); both_sendstr("LIGHTNING"); code &= ~INT_L; }
if(code) both_sendstr(u2str(code));
both_putchar('\n');
if(savedcode == INT_L){ // clear lightning - show distance and power
lightning_info(USB_sendstr, ch);
lightning_info(both_sendstr, ch);
}
}
}
}else oldint[ch] = 0;
}
if(usart_has_txdata() && usart_bus_free()){
usart_transmit();
}
}
return 0;
}

View File

@@ -30,9 +30,9 @@
typedef struct{
uint8_t *data; // data buffer
const int length; // its length
int head; // head index
int tail; // tail index
volatile int busy; // == TRUE if buffer is busy now
volatile int head; // head index
volatile int tail; // tail index
volatile int busy; // == TRUE if buffer is busy now
} ringbuffer;
int RB_read(ringbuffer *b, uint8_t *s, int len);

View File

@@ -36,13 +36,13 @@ void spi_setup(){
}
volatile uint32_t wctr;
#define WAITX(x) do{wctr = 0; while((x) && (++wctr < 360000)) IWDG->KR = IWDG_REFRESH; if(wctr==360000) return -1;}while(0)
#define WAITX(x) do{wctr = 0; while((x) && (++wctr < 360000)) IWDG->KR = IWDG_REFRESH; if(wctr==360000){CS_OFF(); return 0;} }while(0)
/**
* @brief SPI_transmit - transmit data and receive new one
* @param buf - data to transmit/receive
* @param len - its length
* @return amount of transmitted data or -1 if error
* @return amount of transmitted data or 0 if error
*/
uint8_t SPI_transmit(uint8_t *buf, uint8_t len){
if(!buf || !len) return 0; // bad data format

View File

@@ -0,0 +1,188 @@
/*
* This file is part of the as3935 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://gnu.org>.
*/
#include <stm32f1.h>
#include "hardware.h"
#include "usart.h"
static volatile int idatalen[2] = {0, 0}; // received data line length (without '\n')
static volatile int odatalen[2] = {0, 0};
static volatile int usart_txrdy = 1; // DMA transmission done
static volatile int usart_linerdy = 0; // received data ready
static volatile int dlen = 0; // length of data in current buffer
static volatile int usart_bufovr = 0; // input buffer overfull
// Rx time and Rx progress flag
static volatile uint32_t last_rx_time = 0;
static volatile uint8_t rx_in_progress = 0;
static int rbufno = 0, tbufno = 0; // current rbuf/tbuf numbers
static char rbuf[2][UARTBUFSZI], tbuf[2][UARTBUFSZO]; // receive & transmit buffers
static char* volatile recvdata = NULL;
/**
* return length of received data (without trailing zero) or -1 if overflow
*/
int usart_getline(char **line){
if(usart_bufovr){
usart_bufovr = 0;
usart_linerdy = 0;
return -1;
}
if(!usart_linerdy) return 0;
*line = recvdata;
usart_linerdy = 0;
int x = dlen;
dlen = 0;
return x;
}
// transmit current tbuf and swap buffers
int usart_transmit(){
register int l = odatalen[tbufno];
if(!l) return 0;
uint32_t tmout = 18000000;
while(!usart_txrdy){
IWDG->KR = IWDG_REFRESH;
if(--tmout == 0) return 0;
} // wait for previous DMA buffer transmission
usart_txrdy = 0;
DMA1_Channel4->CCR &= ~DMA_CCR_EN;
DMA1_Channel4->CMAR = (uint32_t) tbuf[tbufno];
DMA1_Channel4->CNDTR = l;
RS485_TX();
DMA1_Channel4->CCR |= DMA_CCR_EN;
tbufno = !tbufno;
odatalen[tbufno] = 0;
return l;
}
int usart_putchar(const char ch){
if(odatalen[tbufno] == UARTBUFSZO){
if(!usart_transmit()) return 0;
}
tbuf[tbufno][odatalen[tbufno]++] = ch;
return 1;
}
int usart_send(const char *str){
if(!str) return 0;
int l = 0;
while(*str){
IWDG->KR = IWDG_REFRESH;
if(odatalen[tbufno] == UARTBUFSZO){
if(!usart_transmit()) return 0;
}
tbuf[tbufno][odatalen[tbufno]++] = *str++;
++l;
}
return l;
}
void usart_setup(uint32_t speed){
if(speed < 1200) speed = 115200;
// PA9 - Tx, PA10 - Rx (configured in gpio_setup, ensure clocks enabled)
RCC->APB2ENR |= RCC_APB2ENR_USART1EN;
RCC->AHBENR |= RCC_AHBENR_DMA1EN;
// USART1 Tx DMA - Channel4
DMA1_Channel4->CPAR = (uint32_t) &USART1->DR;
DMA1_Channel4->CCR |= DMA_CCR_MINC | DMA_CCR_DIR | DMA_CCR_TCIE; // 8bit, mem++, mem->per, transcompl irq
NVIC_SetPriority(DMA1_Channel4_IRQn, 3);
NVIC_EnableIRQ(DMA1_Channel4_IRQn);
NVIC_SetPriority(USART1_IRQn, 0);
// setup usart1
USART1->BRR = 72000000 / speed;
USART1->CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE; // 1start, 8data, nstop; enable Rx/Tx
uint32_t tmout = 16000000;
while(!(USART1->SR & USART_SR_TC)){ // polling idle frame Transmission
IWDG->KR = IWDG_REFRESH;
if(--tmout == 0) break;
}
(void) USART1->DR; // clear IDLE/RXNE etc
USART1->SR = 0; // clear flags
USART1->CR3 = USART_CR3_DMAT; // enable DMA Tx
USART1->CR1 |= USART_CR1_RXNEIE | USART_CR1_TCIE; // allow Rx and Transmission Complete IRQs
RS485_RX();
NVIC_EnableIRQ(USART1_IRQn);
}
// return 1 if there's some data in Tx buffer
int usart_has_txdata(){
return odatalen[tbufno] > 0;
}
// return 1 if Rx isn't in progress
int usart_bus_free(){
if(rx_in_progress){
if(Tms - last_rx_time > 50){ // 50ms timeout of broken message
rx_in_progress = 0;
idatalen[rbufno] = 0;
}else{
return 0;
}
}
if(usart_linerdy || !usart_txrdy) return 0;
return (Tms - last_rx_time) >= 5; // 5ms pause of receiving data
}
void usart1_isr(){
uint32_t sr = USART1->SR;
if(sr & USART_SR_RXNE){ // RX not empty - receive next char
uint8_t rb = USART1->DR;
last_rx_time = Tms;
if(rb == '\r') return; // ignore CR if CRLF is sent
if(idatalen[rbufno] < UARTBUFSZI - 1){ // keep 1 byte for '\0'
if(rb == '\n'){ // got newline - line ready
rx_in_progress = 0;
rbuf[rbufno][idatalen[rbufno]] = 0;
usart_linerdy = 1;
dlen = idatalen[rbufno];
recvdata = rbuf[rbufno];
// prepare other buffer
rbufno = !rbufno;
idatalen[rbufno] = 0;
}else{
rx_in_progress = 1;
rbuf[rbufno][idatalen[rbufno]++] = rb;
}
}else{ // buffer overrun
usart_bufovr = 1;
idatalen[rbufno] = 0;
}
}
if(sr & USART_SR_TC){ // last bit shifted out -> switch RS-485 back to RX
USART1->SR &= ~USART_SR_TC;
if(usart_txrdy){
RS485_RX();
}
}
}
void dma1_channel4_isr(){
if(DMA1->ISR & DMA_ISR_TCIF4){ // Tx DMA complete
DMA1->IFCR = DMA_IFCR_CTCIF4;
usart_txrdy = 1;
// If USART already finished shifting out the last byte, switch to RX immediately
if(USART1->SR & USART_SR_TC){
USART1->SR &= ~USART_SR_TC;
RS485_RX();
}
}
}

View File

@@ -0,0 +1,36 @@
/*
* This file is part of the as3935 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://gnu.org>.
*/
#pragma once
#include <stdint.h>
// input and output buffers size
#define UARTBUFSZI (256)
#define UARTBUFSZO (512)
#define usartrx() (usart_linerdy)
#define usartovr() (usart_bufovr)
int usart_transmit();
void usart_setup(uint32_t speed);
int usart_getline(char **line);
int usart_send(const char *str);
int usart_putchar(const char ch);
int usart_bus_free();
int usart_has_txdata();

View File

@@ -36,6 +36,9 @@
#define CONTROL_DTR 0x01
#define CONTROL_RTS 0x02
// Tx timeout (for stalled host)
#define USB_TX_TIMEOUT_MS (50)
// inbuf overflow when receiving
static volatile uint8_t bufovrfl = 0;
@@ -160,10 +163,19 @@ int USB_sendall(){
return TRUE;
}
extern volatile uint32_t Tms;
// put `buf` into queue to send
int USB_send(const uint8_t *buf, int len){
if(!buf || !CDCready || !len) return FALSE;
uint32_t t0 = Tms;
while(len){
if(!CDCready) return FALSE;
if(Tms - t0 >= USB_TX_TIMEOUT_MS){ // Tx timeout -> clear
NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
RB_clearbuf((ringbuffer*)&rbout);
NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
return FALSE;
}
IWDG->KR = IWDG_REFRESH;
int l = RB_datalen((ringbuffer*)&rbout);
if(l < 0) continue;
@@ -175,6 +187,7 @@ int USB_send(const uint8_t *buf, int len){
if(portion > len) portion = len;
int a = RB_write((ringbuffer*)&rbout, buf, portion);
if(a > 0){
t0 = Tms;
len -= a;
buf += a;
} else if (a < 0) continue; // do nothing if buffer is in reading state
@@ -186,7 +199,16 @@ int USB_send(const uint8_t *buf, int len){
int USB_putbyte(uint8_t byte){
if(!CDCready) return FALSE;
int l = 0;
uint32_t t0 = Tms;
while((l = RB_write((ringbuffer*)&rbout, &byte, 1)) != 1){
if(!CDCready) return FALSE;
IWDG->KR = IWDG_REFRESH;
if(Tms - t0 >= USB_TX_TIMEOUT_MS){
NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
RB_clearbuf((ringbuffer*)&rbout);
NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
return FALSE;
}
if(l < 0) continue;
}
if(lastdsz == 0) send_next(); // need to run manually - all data sent, so no IRQ on IN

View File

@@ -1,2 +1,2 @@
#define BUILD_NUMBER "43"
#define BUILD_DATE "2026-04-14"
#define BUILD_NUMBER "62"
#define BUILD_DATE "2026-11-23"