Compare commits

..

4 Commits

Author SHA1 Message Date
Edward Emelianov
140155460e Test for 128x32 screen (not tested yet) 2026-10-10 23:45:18 +03:00
Edward Emelianov
e7fcb291db fixed schematics 2026-10-01 23:42:59 +03:00
fe5989497f fixed coils read 2026-10-01 17:36:49 +03:00
a2cb827a76 fixed some errors; renew readme 2026-10-01 16:23:50 +03:00
46 changed files with 7413 additions and 523 deletions

View File

@@ -1,20 +1,140 @@
A usefull thing made of chineese FX3U clone # A useful thing made of a Chinese FX3U clone
===========================================
Works over RS-232 (default: 115200, 8N1), CAN (default: 250000 baud) Device works over RS-232 (default 115200 8N1), CAN bus (default 250 kbit/s), or MODBUS-RTU (default
or MODBUS-RTU (default: 9600, 8N1). 9600 8N1).
You can see pinout table in file `hardware.c`. Full pinout table is available in `hardware.c`.
## Serial protocol (each string ends with '\n'). The firmware help output also prints the build number and build date from `version.inc`.
Values in parentheses after flags command is its bit number in whole uint32_t. ## Startup diagnostics
E.g. to reset flag "f_relay_inverted" you can call `f_relay_inverted=0` or
`flags2=0`.
On power-up or reset the firmware prints a startup banner over USART1:
```
START
IWDGRSTF=1 # reset occurred due to independent watchdog
SFTRSTF=1 # software reset (NVIC_SystemReset)
PORRSTF=1 # power-on / power-down reset
PINRSTF=1 # reset via NRST pin
``` ```
Only the flags that were actually set are printed. After printing, all reset flags are cleared.
## Hardware notes
### Inputs (X)
X8 is not a screw terminal — it is the on-board "Prog" pushbutton (PB2).
X9 is absent. Bits of the `inchannels` mask correspond to these positions.
| Ch | Pin | Notes |
|-----|------|-------|
| X0 | PB13 | |
| X1 | PB14 | |
| X2 | PB11 | |
| X3 | PB12 | |
| X4 | PE15 | |
| X5 | PB10 | |
| X6 | PE13 | |
| X7 | PE14 | |
| X8 | PB2 | on-board "Prog" button |
| X9 | — | absent |
| X10 | PE11 | |
| X11 | PE12 | |
| X12 | PE9 | |
| X13 | PE10 | |
| X14 | PE7 | |
| X15 | PE8 | |
### Outputs (Y)
Y8 and Y9 are absent.
| Ch | Pin |
|-----|------|
| Y0 | PC9 |
| Y1 | PC8 |
| Y2 | PA8 |
| Y3 | PA0 |
| Y4 | PB3 |
| Y5 | PD12 |
| Y6 | PB15 |
| Y7 | PA7 |
| Y8 | — |
| Y9 | — |
| Y10 | PA6 |
| Y11 | PA2 |
### On-board LED
"RUN" LED is on PD10. **Active low**: `led` returns the logical state (`1` when the LED is on,
`0` when off).
### ADC channels
| № | Enum | Pin / source | Meaning |
|---|--------------|--------------|---------|
| 0 | `ADC_CH_0` | PA1 / adc1 | voltage input, up to 11 V |
| 1 | `ADC_CH_1` | PA3 / adc3 | voltage input, up to 11 V |
| 2 | `ADC_CH_2` | PC4 / adc14 | voltage input |
| 3 | `ADC_CH_3` | PC5 / adc15 | current input |
| 4 | `ADC_CH_4` | PC0 / adc10 | current input, 0..20 mA |
| 5 | `ADC_CH_5` | PC1 / adc11 | current input |
| 6 | `ADC_POT0` | PC2 / adc12 | right on-board potentiometer |
| 7 | `ADC_POT1` | PC3 / adc13 | left on-board potentiometer |
| 8 | `ADC_CH_TSEN`| internal | MCU temperature sensor |
| 9 | `ADC_CH_VDD` | internal | Vdd reference |
Each channel is sampled continuously in scan mode via DMA into a circular buffer of `9 ×
ADC_CHANNELS` values. The getter returns the median of the last 9 samples per channel. Reported raw
values are 12-bit (0..4095).
The `mcutemp` command returns MCU temperature in `°C × 10` (as `int32_t`).
## Runtime parameters
### Watchdog
IWDG prescaler `/4` (LSI ≈ 40 kHz) with reload 1250 → about **125 ms** watchdog timeout. Refreshed
in every main-loop iteration, in DMA/send wait loops and during flash writes. Any hang longer than
that triggers a reset.
### CAN timeouts
- Mailbox wait inside `CAN_send()`: `SEND_TIMEOUT_MS / 10` = **10 ms**.
- High-level send loops (command reply, ESW notifications): up to `SEND_TIMEOUT_MS` = **100 ms**.
If a message cannot be queued, `error=canbusy` is printed to USART.
### Buffer sizes
| Subsystem | Macro | Value | Notes |
|--------------|----------------------|-------|-------|
| USART input | `UARTBUFSZI` | 196 | longer lines are dropped; firmware prints `USART IN buffer overflow!` |
| USART output | `UARTBUFSZO` | 256 | |
| CAN RX queue | `CAN_INMESSAGE_SIZE` | 8 | extra messages are dropped silently |
| Modbus RX | `MODBUSBUFSZI` | 68 | |
| Modbus TX | `MODBUSBUFSZO` | 64 | |
## Serial protocol
Every command is a string terminated by `\n`. General syntax:
```
command[number][=value]
```
- `command` — command name (letters/digits);
- `number` — optional parameter number, 0..127;
- `=value` — optional setter value.
Numbers are parsed by `getnum()` and accept decimal (`123`), hexadecimal (`0x7B`), octal (`0173`)
and binary (`0b1111011`). Signed values (`getint()`) allow a leading `-`.
Values in parentheses after a flag command is its bit number in the whole `uint32_t`. E.g. to reset
flag `f_relay_inverted` you can call `f_relay_inverted=0` or `flags2=0`.
```
commands format: parameter[number][=setter] commands format: parameter[number][=setter]
parameter [CAN idx] - help parameter [CAN idx] - help
-------------------------- --------------------------
@@ -44,7 +164,7 @@ saveconf [9] - save configuration
usartspeed [15] - get/set USART1 speed usartspeed [15] - get/set USART1 speed
IN/OUT: IN/OUT:
adc [4] - get raw ADC values for given channel adc [4] - get raw ADC value for the given channel (0..9)
esw [12] - anti-bounce read inputs esw [12] - anti-bounce read inputs
eswnow [13] - read current inputs' state eswnow [13] - read current inputs' state
led [16] - work with onboard LED led [16] - work with onboard LED
@@ -59,316 +179,384 @@ outchannels [19] - get u32 with bits set on supported OUT channels
reset [1] - reset MCU reset [1] - reset MCU
time [2] - get/set time (1ms, 32bit) time [2] - get/set time (1ms, 32bit)
wdtest - test watchdog wdtest - test watchdog
``` ```
Value in square brackets is CAN bus command code. Value in square brackets is the CAN bus command code (see below).
The INs are changed compared to original "FX3U" clone: instead of the absent IN8 I use the on-board ### Notes on specific commands
button "RUN".
#### `bounce`
`bouncetime` (default 50 ms) is not a classical debounce delay — it is the **per-input sampling
interval**. Once an input has been sampled, it will not be re-read until `bouncetime` milliseconds
have elapsed. Worst-case reaction time for an input change is therefore up to `bouncetime` ms;
changes within that window are ignored (which is the debounce behaviour itself).
#### `s`
Send a CAN message. All numbers are space-separated; the first is the CAN ID (0..0x7FF), the
remaining 0..8 numbers are data bytes. Numbers may be given in any format accepted by `getnum()`.
```
s 0x123 0x11 0x22 0x33
s 291 1 2 3 4
```
On invalid arguments the firmware prints `error=badpar` / `error=badval` / `error=wronglen` and
sends nothing.
#### `cansniff`
When enabled, every received CAN frame is printed to USART in the format:
```
<time_ms> #<ID> <b0> <b1> ...
```
All fields are hexadecimal except `<time_ms>`. While messages are being received, the regular
periodic USART keep-alive is suppressed.
#### `adc`
Accepts a parameter number 0..9 (`ADC_CHANNELS - 1`). Numbers outside this range return
`error=badpar`.
#### `flags`
With a parameter number (0..`MAX_FLAG_BITNO` = 0..3): sets/reads the Nth bit only. Without a
parameter ("no par", 0x7F): operates on the whole `uint32_t`. Bits above `MAX_FLAG_BITNO` return
`error=badpar`.
### Default configuration
Flash storage is empty after flashing; on first boot `flashstorage_init()` returns `currentconfidx
= -1` and the firmware uses `USERCONF_INITIALIZER` from `flash.c`:
```
CANspeed = 250000
CANIDin = 1
CANIDout = 2
usartspeed = 115200
bouncetime = 50
modbusID = 1
modbusIDout = 2
modbusspeed = 9600
flags = { sw_send_relay_inv = 1 }
```
After the first `saveconf`, these defaults are replaced by the stored record.
## CAN bus protocol ## CAN bus protocol
Default CAN speed is 250kbaud. Default CAN ID: 1 and 2 for slave. Default speed is 250 kbit/s. Default CAN IDs are 1 (input) and 2 (output) for a slave. **All
All data in little-endian format! multi-byte data is little-endian.**
BYTE - MEANING | Byte(s) | Meaning |
|---------|---------|
| 0, 1 | `uint16_t` command code (see table below) |
| 2 | `uint8_t` parameter number: 0..126, ORed with 0x80 for setter, 127 = "no parameter" |
| 3 | `uint8_t` error code (only in device answers) |
| 4..7 | `int32_t` data |
0, 1 - (uint16_t) - command code (value in square brackets upper); When the device receives a CAN packet addressed to its own ID or to ID = 0 ("broadcast"), it
performs the requested action and sends an answer (usually a getter reply). If the command cannot
be executed or carries bad data, the device returns the same packet with the error code inserted
into byte 3.
2 - (uint8_t) - parameter number (e.g. ADC channel or X/Y channel number), 0..126 [ORed with 0x80 for setter], 127 means "no parameter"; Getters may be requested by a 3-byte packet (command code + parameter). "No parameter" (0x7F) in
some commands means "all data" — e.g. get/set all relays or get all inputs.
3 - (uint8_t) - error code (only when device answers for requests); ### CAN bus error codes (byte 3 of the answer)
4..7 - (int32_t) - data. | Code | Name | Meaning |
|------|------------------|---------|
| 0 | `ERR_OK` | all OK |
| 1 | `ERR_BADPAR` | wrong parameter |
| 2 | `ERR_BADVAL` | value out of range |
| 3 | `ERR_WRONGLEN` | wrong message length (for setter or where a parameter is required) |
| 4 | `ERR_BADCMD` | unknown command code |
| 5 | `ERR_CANTRUN` | cannot run the command (bad parameters or other reason) |
When device receives CAN packet with its ID or ID=0 ("broadcast" message) it check this packet, perform some action and sends answer Bus-level errors (stuff/form/ack/bit/CRC, bus-off, error-passive, error-warning) are not reported
(usually - getter). If command can't be execute or have wrong data (bad command, bad parameter number etc) the device sends back in byte 3. They are printed over USART by `CAN_printerr()` when the `canbuserr` printer is enabled:
the same packet with error code inserted.
When runnming getter you can send only three bytes: command code and parameter number. Sending "no parameter" instead of parno ```
means in some commands "all data" (e.g. get/set all relays or get all inputs). Receive error counter: <n>
Transmit error counter: <n>
Last error code: <name>
[Bus off] [Passive error limit] [Error counter limit]
```
### CAN bus error codes ### CAN command codes
0 - `ERR_OK` - all OK, | Code | Enum | Text command |
|------|------|--------------|
| 0 | `CMD_PING` | (ping) |
| 1 | `CMD_RESET` | `reset` |
| 2 | `CMD_TIME` | `time` |
| 3 | `CMD_MCUTEMP` | `mcutemp` |
| 4 | `CMD_ADCRAW` | `adc` |
| 5 | `CMD_CANSPEED` | `canspeed` |
| 6 | `CMD_CANID` | `canid` |
| 7 | `CMD_CANIDin` | `canidin` |
| 8 | `CMD_CANIDout` | `canidout` |
| 9 | `CMD_SAVECONF` | `saveconf` |
| 10 | `CMD_ERASESTOR` | `eraseflash` |
| 11 | `CMD_RELAY` | `relay` |
| 12 | `CMD_GETESW` | `esw` |
| 13 | `CMD_GETESWNOW` | `eswnow` |
| 14 | `CMD_BOUNCE` | `bounce` |
| 15 | `CMD_USARTSPEED` | `usartspeed` |
| 16 | `CMD_LED` | `led` |
| 17 | `CMD_FLAGS` | `flags` |
| 18 | `CMD_INCHNLS` | `inchannels` |
| 19 | `CMD_OUTCHNLS` | `outchannels` |
| 20 | `CMD_MODBUSID` | `modbusid` |
| 21 | `CMD_MODBUSIDOUT` | `modbusidout` |
| 22 | `CMD_MODBUSSPEED` | `modbusspeed` |
1 - `ERR_BADPAR` - parameter is wrong, ### Examples
2 - `ERR_BADVAL` - value is wrong (e.g. out of range), All data in hex. Slave ID is omitted.
3 - `ERR_WRONGLEN` - wrong message length (for setter or for obligatory parameter number), Get current time:
- request: `02 00 00`
- answer: `02 00 00 00 de ad be ef` — last four bytes are time in ms since power-up.
4 - `ERR_BADCMD` - unknown command code, Set relay number 5:
- request: `0b 00 85 00 01 00 00 00`
- answer: `0b 00 05 00 01 00 00 00`
5 - `ERR_CANTRUN` - can't run given command due to bad parameters or other reason. Set relays 0..3, reset the rest:
- request: `0b 00 ff 00 07 00 00 00`
- answer: `0b 00 7f 00 07 00 00 00`
### CAN bus command codes Changing flags works like the text command: with a parameter number the Nth bit is changed, without
a parameter the whole `uint32_t` is replaced.
Number - enum from canproto.h - text command analog
0 - CMD_PING - ping
1- CMD_RESET - reset
2 - CMD_TIME - time
3 - CMD_MCUTEMP - mcutemp
4 - CMD_ADCRAW - adc
5 - CMD_CANSPEED - canspeed
6 - CMD_CANID - canid
7 - CMD_CANIDin - canidin
8 - CMD_CANIDout - canidout
9 - CMD_SAVECONF - saveconf
10 - CMD_ERASESTOR - eraseflash
11 - CMD_RELAY - relay
12 - CMD_GETESW - esw
13 - CMD_GETESWNOW - eswnow
14 - CMD_BOUNCE - bounce
15 - CMD_USARTSPEED - usartspeed
16 - CMD_LED - led
17 - CMD_FLAGS - flags
18 - CMD_INCHNLS - inchannels
19 - CMD_OUTCHNLS - outchannels
20 - CMD_MODBUSID - modbusid
21 - CMD_MODBUSIDOUT - modbusidout
22 - CMD_MODBUSSPEED - modbusspeed
### Examples of CAN commands (bytes of data transmitted with given ID)
(all data in HEX)
Get current time: "02 00 00". Answer something like "02 00 00 00 de ad be ef", where last four bytes
is time value (in milliseconds) from powering on.
Set relay number 5: "0b 00 85 00 01 00 00 00", answer: "0b 00 05 00 01 00 00 00".
Set relays 0..3 and reset other: "0b 00 ff 00 07 00 00 00", answer: "0b 00 7f 00 07 00 00 00".
Changing flags is the same as for text command: with parameter number (0..31) it will only change given
bit value, without ("no par" - 0x7f) will change all bits like whole uint32_t.
## MODBUS-RTU protocol ## MODBUS-RTU protocol
The device can work as master or slave. Default format is 9600-8N1. BIG ENDIAN (like standard requires). The device can operate as master or slave. Default format is 9600-8N1. **Big-endian**, as the
Default device ID is 1 ans 2 for target of "relay command" (if ID would be changed to 0 and flag `f_send_relay_modbus` set. standard requires. Default slave ID is 1, and the "relay command" target ID is 2.
To run in master mode you should set its modbus ID to zero. Command `modbus` lets you to send strict Set `modbusid=0` to enter master mode. In master mode the device no longer answers incoming modbus
formal modbus packet in format "slaveID fcode regaddr nregs [N data]" (all are space-delimited numbers in requests, but instead parses incoming **responses** and prints them to USART.
decimal, hexadecimal (e.g. 0xFF), octal (e.g. 075) or binary (e.g. 0b1100110) format.
Here "slaveID" - one byte; "fcode" - one byte; "regaddr" - two bytes big endian; "nregs" - two bytes big endian;
"N" - one byte; "data" - N bytes.
Optional data bytes allowed only for "multiple" functions. In case of simple setters "nregs" is two bytes data
sent to slave.
The command `modbusraw` will not check your data, just add CRC and send into bus. The `modbus` command sends a formal modbus request in the format:
In master mode you can activate flag `f_send_relay_modbus`. In this case each time the IN state changes ```
device will send command with ID=`modbusidout` to change corresponding relays. So, like for CAN commands modbus = slaveID fcode regaddr nregs [N data]
you can bind several devices to transmit IN states of one to OUT states of another. ```
If `modbusidout` is zero, master will send broadcasting command. Slaves non answer for broadcast, only making
required action.
The hardware realisation of modbus based on UART4. Both input and output works over DMA, signal of packet end All numbers are space-separated and parsed by `getnum()` (decimal / hex / octal / binary).
is IDLE interrupt. This device doesn't supports full modbus protocol realisation: no 3.5 idle frames as packet `slaveID` and `fcode` are one byte each; `regaddr` and `nregs` are two bytes little-endian; `N` is
end; no long packets (input buffer is 68 bytes, allowing no more that 67 bytes; output buffer is 64 bytes, allowing one byte; `data` is N bytes. Optional data bytes are allowed only for "multiple" functions (0x0F,
no more that 64 bytes). Maximal modbus slave ID is 247. You can increase in/out buffers size changing value of 0x10). For simple setters (0x05, 0x06) `nregs` is the two-byte value written to the slave.
macros `MODBUSBUFSZI` and `MODBUSBUFSZO` in `modbusrtu.h`.
In slave mode device doesn't support whole CAN-bus commands range. Next I describe allowed commands. ```
modbus = 1 6 2 1 # slave 1, write register, register 2 (MR_LED), value 1
modbus = 1 0x0f 0 8 1 0xff # slave 1, write coils, 8 coils, 1 byte of data
```
There are five holding registers. "[R]" means read-only, "[W]" - write-only, "[RW]" - read and write. `modbusraw` does not validate the fields; it just sends the data (user should add CRC by himself).
Useful for testing unusual requests.
0 - MR_RESET [W] - reset MCU. In master mode, flag `f_send_relay_modbus` makes the device send an "write coils" command with ID =
`modbusidout` every time the IN state changes. This lets you bind several devices: inputs of one
drive the outputs of another. If `modbusidout` is zero, a broadcast is sent (slaves do not reply to
broadcasts, they just perform the action).
1 - MR_TIME [RW] - read or set MCU time (milliseconds, uint32_t). ### Implementation notes
2 - MR_LED [RW] - read or change on-board LED state. - Modbus uses UART4 with DMA for both RX and TX. End of frame is detected by the IDLE interrupt.
- There is no 3.5-character silent-interval handling — any IDLE marks the end of a packet.
- Input buffer is 68 bytes (up to 67 data bytes), output buffer is 64 bytes (up to 64 bytes).
Enlarge `MODBUSBUFSZI` / `MODBUSBUFSZO` in `modbusrtu.h` if needed.
- Maximal modbus slave ID is 247.
- The device does **not reply** to broadcast requests (ID = 0).
3 - MR_INCHANNELS [R] - get uint32_t value where each N-th bit means availability of N-th IN channel ### Slave registers
(e.g. if 9th channel is physically absent 9th bit would be 0).
### Supported functional codes Holding registers: `[R]` = read-only, `[W]` = write-only, `[RW]` = read/write.
#### 01 - read coil | № | Symbol | Access | Meaning |
Read state of all relays. Obligatory regaddr="00 00", nregs="00 N", where "N" is 8-multiple |---|-------------------|--------|---------|
number (in case of 10-relay module: 8 or 16). You will reseive N/8 bytes of data with relays' status (e.g. most | 0 | `MR_RESET` | W | reset MCU |
lest significant bit is state or relay0, next - relay1 and so on). | 1 | `MR_TIME` | RW | MCU time in ms (`uint32_t`) |
| 2 | `MR_LED` | RW | on-board LED state |
| 3 | `MR_INCHANNELS` | R | `uint32_t` of available IN channels |
| 4 | `MR_OUTCHANNELS` | R | `uint32_t` of available OUT channels |
Example: "01 01 00 00 00 10" - read state of all relays. If only relay 10 active you will ### Supported function codes
receive: "01 01 02 04 00".
Errors: "02" - "regaddr" isn't zero; "03" - N isn't multiple of 8 or too large. #### 01 — read coils
Read state of all relays. `regaddr` must be 0, `nregs` must be a multiple of 8 (in this hardware: 8 or 16). Answer contains `nregs / 8` bytes; bit 0 of the first data byte is relay 0.
#### 02 - read discrete input Example — read all relays; only relay 10 active:
Read state of all discrete inputs. Input/output parameters are the same like for "read coil". - request: `01 01 00 00 00 10`
- answer: `01 01 02 00 04`
Example: "01 02 00 00 00 08" - read 8 first INs. Answer if first 4 inputs active (disconnected): Errors: `02` — non-zero `regaddr`; `03` — `nregs` not a multiple of 8 or too large.
"01 02 01 0f".
Errors: like for "read coil". #### 02 — read discrete inputs
Same semantics as "read coils", but for the IN channels.
#### 03 - read holding register Example — read first 8 INs; all 4 low-order inputs active:
You can read value of non write-only registers. You can read only one register by time. - request: `01 02 00 00 00 08`
- answer: `01 02 01 0f`
Example: "01 03 00 01 00 01" - read time. Answer: "01 03 04 00 15 53 01", where 0x00155301 is 1397.505 seconds #### 03 — read holding register
from device start. Reads one register at a time.
Errors: "02" - "regaddr" is wrong, "03" - "regno" isn't 1. Example — read time:
- request: `01 03 00 01 00 01`
- answer: `01 03 04 01 53 15 00` — value `0x00155301` = 1397505 ms ≈ 1397.5 s.
#### 04 - read input register Errors: `02` — bad `regaddr`; `03` — `regno != 1`.
Read "nregs" ADC channels starting from "regaddr" number.
Example: "01 04 00 05 00 04" - read channels 5..8. #### 04 — read input register
Answer: "01 04 08 08 6c 00 21 00 33 00 41" - got 0x86c (2156) for 5th channel and so on. Read `nregs` ADC channels starting at `regaddr`.
Errors: "02" - wrong starting number, "03" - wrong amount (zero or N+start > last channel available). Example — read channels 5..8:
- request: `01 04 00 05 00 04`
- answer: `01 04 08 6c 08 21 00 33 00 41 00` — `0x086c` (2156) for channel 5, etc.
#### 05 - write coil Errors: `02` — bad start channel; `03` — bad amount (zero or beyond last channel).
Change single relay state. "nregs" is value (0 - off, non-0 - on), "regaddr" is relay number.
Example: "01 05 00 03 00 01" - turn 3rd relay on. Answer: "01 05 00 03 00 01". #### 05 — write coil
Changes a single relay state. `regaddr` — relay number, `nregs` — value (0 = off, non-zero = on).
Errors: "02" - wrong relay number. Example - turn on coil 3:
- request: `01 05 00 03 00 01`
- answer: `01 05 00 03 00 01`
#### 06 - write holding register Errors: `02` — bad relay number.
Write data to non read-only register (reset MCU, change time value or turn LED on/off).
Example: "01 06 00 02 00 01" - turn LED on. Answer: "01 06 00 02 00 01". #### 06 — write holding register
Writes to one register (`MR_RESET`, `MR_TIME` or `MR_LED`).
Errors: "02" - wrong register. Example — turn LED on:
- request: `01 06 00 02 00 01`
- answer: `01 06 00 02 00 01`
#### 0f - write multiple coils Errors: `02` — bad register.
Change state of all relays by once. Here "regaddr" should be "00 00",
"nregs" should be multiple of 8, "N" should be equal ("nregs"+7)/8. Each data bit means nth relay state.
Example: "01 0f 00 00 00 08 01 ff" - turn on relays 0..7. #### 0F — write multiple coils
Answer: "01 0f 00 00 00 08". Changes all relays at once. `regaddr` must be 0, `nregs` a multiple of 8, `N` = `(nregs + 7) / 8`.
Each data bit is a relay state.
Errors: "02" - "regaddr" isn't zero, "03" - wrong amount of relays, "07" - can't change relay values. Example — turn on relays 0..7:
- request: `01 0f 00 00 00 08 01 ff`
- answer: `01 0f 00 00 00 08`
Turn on all relays (0..7 and 10, 11):
- request: `01 0f 00 00 00 10 02 ff 0f`
- answer: `01 0f 00 00 00 10 56 c2`
#### 10 - write multiple registers Errors: `02` — non-zero `regaddr`; `03` — wrong amount; `07` — cannot change relays.
You can write only four "registers" by once changing appropriate uint32_t value.
The only "register" you can change is 01 - MR_TIME. "nregs" should be equal 1.
Example: "01 10 00 01 00 01 04 00 00 00 00" - clears Tms counter, starting time from zero. #### 10 — write multiple registers
Answer: "01 10 00 01 00 01". Only `MR_TIME` can be written this way; `nregs` must be 1 and the data length 4 bytes.
Errors: "02" - wrong register. Example — clear `Tms`:
- request: `01 10 00 01 00 01 04 00 00 00 00`
- answer: `01 10 00 01 00 01`
Errors: `02` — wrong register.
### Error codes ### Modbus exception codes
01 - ME_ILLEGAL_FUNCION - The function code received in the request is not an authorized action for the slave.
02 - ME_ILLEGAL_ADDRESS - The data address received by the slave is not an authorized address for the slave. | Code | Name | Meaning |
|------|------|---------|
| 01 | `ME_ILLEGAL_FUNCION` | function code is not authorized for the slave |
| 02 | `ME_ILLEGAL_ADDRESS` | data address is not authorized |
| 03 | `ME_ILLEGAL_VALUE` | data field value is not authorized |
| 04 | `ME_SLAVE_FAILURE` | unrecoverable error |
| 05 | `ME_ACK` | accepted, but processing takes a long time |
| 06 | `ME_SLAVE_BUSY` | slave is busy |
| 07 | `ME_NACK` | programming request cannot be performed |
| 08 | `ME_PARITY_ERROR` | memory parity error |
03 - ME_ILLEGAL_VALUE - The value in the request data field is not an authorized value for the slave. ## Limitations
04 - ME_SLAVE_FAILURE - The slave fails to perform a requested action because of an unrecoverable error. - CAN RX queue holds 8 messages; extras are dropped silently.
- USART RX buffer holds 196 bytes; longer lines are discarded with an error message.
- Modbus does not implement the 3.5-character silent interval. Buffers are 67/64 bytes.
- The Modbus master does not implement retries, timeouts or a transaction queue — it just prints
incoming responses. Reliable exchange should be arranged by the host.
- CAN filters accept only the configured `CANIDin` plus ID 0 (broadcast); the "monitor" mode adds a
second, match-all filter.
- The IWDG is enabled in release builds. Any hang longer than ~125 ms triggers a reset.
- The `EBUG` build disables the IWDG and enables verbose `DBG(...)` messages.
05 - ME_ACK - The slave accepts the request but needs a long time to process it. ## Short programming guide
06 - ME_SLAVE_BUSY - The slave is busy processing another command. ### Adding a new value to flash storage
07 - ME_NACK - The slave cannot perform the programming request sent by the master. All stored values are described in `struct user_conf` (`flash.h`). You can add new fields, but keep
32-bit alignment in mind. Bit flags live in `union confflags_t`, which combines 32-bit and per-bit
access.
08 - ME_PARITY_ERROR - Memory parity error: slave is almost dead. After adding a field:
1. Add a setter/getter (usually via `u32setget` or `flagsetget`).
2. Add a line in `dumpconf()` (`proto.c`).
The text protocol allows working with flags by their semantic name. To add a flag, edit `proto.c`:
- add a `static const char* S_f_...` constant with the flag name;
- add its address to the `bitfields[]` array **in the same order as the bits are defined in
`confflags_t`** (critical: `dumpconf` and `confflags` index this array by bit number);
- add an entry to the `text_cmd` enum;
- add a `funcdescr` entry to `funclist`;
- modify `confflags()` for setter/getter handling.
### Adding a new command
Base commands are processed in `canproto.c` and `proto.c`. `modbusproto.c` handles modbus-specific
commands.
# Short programming guide To add a CAN/serial command:
## Adding a new value to flash storage 1. Add an enum member in `canproto.h` (`CMD_...`). **This value is the numeric command code** on
the wire.
2. Add a string constant with the text command name in `proto.c`.
3. Add a `funcdescr` entry to `funclist`.
4. Implement the handler in `canproto.c` (returns one of `errcodes`, receives a `CAN_message *`).
All storing values described in structure `user_conf` (`flash.h`). You can add there any new value **Important:** the `funclist[]` array in `canproto.c` is indexed by enum value — the entry for
but be carefull with 32-bit alignment. Bit flags stored as union `confflags_t` combining 32-bit and 1-bit access. `CMD_X` must be at array position `CMD_X`. Use designated initializers (`[CMD_X] = {...}`) as the
After you add this new value don't forget to add setter/getter and string describing it in function `dumpconf`. existing code does.
Text protocol allows you to work with flags by their semantic name. So to add some flag you should also modify The `commonfunction` struct has fields `{fn, minval, maxval, datalen}`:
`proto.c`: - `minval == maxval` disables range checking of the value (bytes 4..7) for setter commands;
- `datalen` is the minimal packet length in bytes that the handler requires.
- add text constant with flag name; The handler only sees a `CAN_message *`. The serial parser builds an equivalent packet from user
- add address of this constant into `bitfields` array (according to bit order in flags); input: `[C C P 0 V0 V1 V2 V3]`, where `C` = command code (little-endian); `P` = parameter number
- add appropriate enum into `text_cmd`; (or 0x7F if not specified), ORed with 0x80 in case of a setter; `Vx` = bytes of the user value
- add appropriate string into `funclist`: pointer to string constant, enum field and help text; (little-endian).
- modify function `confflags` for setter/getter of new flag.
For `uint32_t` configuration values use `u32setget`; for bit flags — `flagsetget`.
## Adding a new command ### Adding a serial-only command
All base commands are processed in files `canproto.c` and `proto.c`. `modbusproto.c` is for modbus-specific commands. If the command has no CAN equivalent, work purely in `proto.c`:
- add an entry to the `text_cmd` enum (negative indices are used in `funclist`);
- add a string constant and a `funcdescr` entry;
- implement the handler with signature `errcodes fn(const char *str, text_cmd cmd)`;
- register it in the `textfunctions[]` array.
To add CAN/serial command you should first add a field to anonimous enum in `canproto.h`, which will be number code of ### Working with modbus
given CANbus command. Codes of serial-only commands are stored in enum `text_cmd` of file `proto.c`.
### Add both CAN/serial command Modbus-specific enums (`modbus_fcode`, `modbus_exceptions`) and structs (`modbus_request`,
- add enum in `canproto.c`; `modbus_response`) are declared in `modbusrtu.h`. `data` fields hold bytes in wire order. For
- add string const with text name of this command in `proto.c`; requests without data (Fcode ≤ 6), `data` may be `NULL`.
- add string to `funclist` with address of string const, enum and help;
- add command handler into `canproto.c` and describer into array `funclist` (index should be equal
to command code, struct consists from pointer to handler, minimal and maximal value and minimal data length
of can packet). If min==max then argument wouldn't be checked.
The handler returns one of `errcodes` and have as argument only pointer to `CAN_message` structure. High-level modbus slave handlers live in `modbusproto.c`. To add a new register, extend the
So, serial command parser before call this handler creates CAN packet from user data. `modbus_registers` enum in `modbusproto.h` and handle the new value in `readreg()`, `writereg()` or
Format of command is next: "cmd[X][=VAL]", where "cmd" is command text, "X" - optional parameter, `writeregs()`. The main dispatch point is `parse_modbus_request()`.
"VAL" - value for setter. So the packet would be "C C P 0 VAL0 VAL1 VAL2 VAL3", where
"C" - command code, "P" - parameter number (or 0x7f" if X is omit) OR'ed with 0x80 for setter,
VALx - xth byte (little endian) of user value.
For setting/getting uint32_t paramegers (especially configuration parameters) you can use handler `u32setget`. ---
For bit flags - `flagsetget`.
To work with bit-flags by particular name use `confflags` handler of `proto.c`. ## License
### Add serial-only command All source files are licensed under **GNU General Public License v3.0** unless stated otherwise.
In this case there's no CAN handler. You work only with `proto.c`.
- add enum in `text_cmd`;
- add string const with text name of this command;
- add string to `funclist` with address of string const, enum and help;
- add command handler;
- add pointer to this handler into `textfunctions` array.
Handler also returns one of `errcodes`, but have next arguments:
- `const char *txt` - all text (excluding spaces in beginning) after command in user string;
- `text_cmd command` - number of command (useful when you have common handler for several commands).
## Working with modbus
All exceptions and functional codes described as enums in `modbusrtu.h`.
To form request or responce use structs `modbus_request` and `modbus_responce`. `data` fields in this
structs is big-endian storing bytes in order like they will be sent via RS-485.
Amount of data bytes should be not less then `datalen` value. For requests that don't need data,
`data` may be NULL regardless `datalen` (for Fcode <= 6). `regno` is amount of registers or
data written to register dependent on `Fcode`.
The responce struct of error codes have NULL in `data` and `datalen` is appropriate exception code.
All high-level commands are in `modbusproto.c`. To add new `register` you should edit `modbus_regusters`
enum in `modbusproto.h`.
The main parsing pipeline is `parse_modbus_request` in `modbusproto.c`.
Here you can add parsing of new functional codes.
To work with new "registers" edit `readreg`, `writereg` or `writeregs`.

3
F1:F103/FX3U/TODO Normal file
View File

@@ -0,0 +1,3 @@
- Add DAC, RTC
- Add 24V power lost detection for going into sleeping state (and wake-up by interrupt from PC7)
- Add EEPROM management (but what for?)

View File

@@ -33,10 +33,11 @@ void adc_setup(){
DMA1_Channel1->CCR = DMA_CCR_MINC | DMA_CCR_MSIZE_0 | DMA_CCR_PSIZE_0 DMA1_Channel1->CCR = DMA_CCR_MINC | DMA_CCR_MSIZE_0 | DMA_CCR_PSIZE_0
| DMA_CCR_CIRC | DMA_CCR_PL | DMA_CCR_EN; | DMA_CCR_CIRC | DMA_CCR_PL | DMA_CCR_EN;
RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_ADCPRE)) | RCC_CFGR_ADCPRE_DIV8; // ADC clock = RCC / 8 RCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_ADCPRE)) | RCC_CFGR_ADCPRE_DIV8; // ADC clock = RCC / 8
// sampling time - 239.5 cycles for channels 0, 16 and 17 // sampling time - 239.5 cycles for all channels
ADC1->SMPR2 = ADC_SMPR2_SMP0; ADC1->SMPR2 = ADC_SMPR2_SMP1 | ADC_SMPR2_SMP3;
ADC1->SMPR1 = ADC_SMPR1_SMP16 | ADC_SMPR1_SMP17; ADC1->SMPR1 = ADC_SMPR1_SMP10 | ADC_SMPR1_SMP11 | ADC_SMPR1_SMP12 | ADC_SMPR1_SMP13 |
// sequence order: 1[0]->3[1]->14[2]->15[3]->10[4]->11[5] -> 16[tsen] -> 17[vdd] ADC_SMPR1_SMP14 | ADC_SMPR1_SMP15 | ADC_SMPR1_SMP16 | ADC_SMPR1_SMP17;
// sequence order: 1[0]->3[1]->14[2]->15[3]->10[4]->11[5] ->12[pot0] ->13[pot1] -> 16[tsen] -> 17[vdd]
ADC1->SQR3 = (1 << 0) | (3<<5) | (14 << 10) | (15 << 15) | (10 << 20) | (11 << 25); ADC1->SQR3 = (1 << 0) | (3<<5) | (14 << 10) | (15 << 15) | (10 << 20) | (11 << 25);
ADC1->SQR2 = (12 << 0) | (13 << 5) | (16 << 10) | (17 << 15); ADC1->SQR2 = (12 << 0) | (13 << 5) | (16 << 10) | (17 << 15);
ADC1->SQR1 = (ADC_CHANNELS - 1) << 20; // amount of conversions ADC1->SQR1 = (ADC_CHANNELS - 1) << 20; // amount of conversions
@@ -89,16 +90,16 @@ uint16_t getADCval(int nch){
uint32_t getADCvoltage(int nch){ uint32_t getADCvoltage(int nch){
uint32_t v = getADCval(nch); uint32_t v = getADCval(nch);
v *= getVdd(); v *= getVdd();
v /= 0xfff; // 12bit ADC v >>= 12; // 12bit ADC
return v; return v;
} }
// return MCU temperature (degrees of celsius * 10) // return MCU temperature (degrees of celsius * 10)
int32_t getMCUtemp(){ int32_t getMCUtemp(){
// Temp = (V25 - Vsense)/Avg_Slope + 25 // Temp = (V25 - Vsense)/Avg_Slope + 25
// V_25 = 1.45V, Slope = 4.3e-3 // V_25 = 1.43V, Slope = 4.3e-3
int32_t Vsense = getVdd() * getADCval(ADC_CH_TSEN); int32_t Vsense = getVdd() * getADCval(ADC_CH_TSEN);
int32_t temperature = 593920 - Vsense; // 593920 == 145*4096 int32_t temperature = 585728 - Vsense; // 585728 == 143*4096
temperature /= 172; // == /(4096*10*4.3e-3), 10 - to convert from *100 to *10 temperature /= 172; // == /(4096*10*4.3e-3), 10 - to convert from *100 to *10
temperature += 250; temperature += 250;
return(temperature); return(temperature);
@@ -106,7 +107,8 @@ int32_t getMCUtemp(){
// return Vdd * 100 (V) // return Vdd * 100 (V)
uint32_t getVdd(){ uint32_t getVdd(){
uint32_t vdd = 120 * 4096; // 1.2V uint32_t vdd = 120 << 12; // 1.2V
vdd /= getADCval(ADC_CH_VDD); uint32_t val = getADCval(ADC_CH_VDD);
if(val) vdd /= val;
return vdd; return vdd;
} }

View File

@@ -100,6 +100,9 @@ MASK: FBMx=0 (CAN1->FM1R), two filters (n in FR1 and n+1 in FR2)
LIST: FBMx=1, four filters (n&n+1 in FR1, n+2&n+3 in FR2) LIST: FBMx=1, four filters (n&n+1 in FR1, n+2&n+3 in FR2)
IDn: CAN1->sFilterRegister[x].FRn[0..15] IDn: CAN1->sFilterRegister[x].FRn[0..15]
IDn+1: CAN1->sFilterRegister[x].FRn[16..31] IDn+1: CAN1->sFilterRegister[x].FRn[16..31]
IDE == 0 for 11 bit ID, 1 for 29 bit ID
RTR == 1 for remote transmission request ("remote frame", I don't support them)
*/ */
/* /*
@@ -133,7 +136,7 @@ void CAN_setup(uint32_t speed){
/* (5) Leave init mode */ /* (5) Leave init mode */
/* (6) Wait the init mode leaving */ /* (6) Wait the init mode leaving */
/* (7) Enter filter init mode, (16-bit + mask, bank 0 for FIFO 0) */ /* (7) Enter filter init mode, (16-bit + mask, bank 0 for FIFO 0) */
/* (8) Acivate filter 0 for two IDs */ /* (8) Acivate filters 0 and 1 */
/* (9) Identifier mode for bank#0, mask mode for #1 */ /* (9) Identifier mode for bank#0, mask mode for #1 */
/* (10) Set the Id list */ /* (10) Set the Id list */
/* (12) Leave filter init */ /* (12) Leave filter init */
@@ -156,17 +159,17 @@ void CAN_setup(uint32_t speed){
IWDG->KR = IWDG_REFRESH; IWDG->KR = IWDG_REFRESH;
if(--tmout == 0) break; if(--tmout == 0) break;
} }
// accept depending of monitor flag // accept depending of monitor flag (CAN_FS1R after reset is 0, as we need for 2 16-bit filters in one reg)
CAN1->FMR = CAN_FMR_FINIT; /* (7) */ CAN1->FMR = CAN_FMR_FINIT; /* (7) */
CAN1->FA1R = CAN_FA1R_FACT0; /* (8) */ CAN1->FA1R = CAN_FA1R_FACT0 | CAN_FA1R_FACT1; /* (8) */
CAN1->FM1R = CAN_FM1R_FBM0; CAN1->FM1R = CAN_FM1R_FBM0;
// filter 0 for FIFO0 // filter 0 for FIFO0
CAN1->sFilterRegister[0].FR1 = the_conf.CANIDin << 5; // (10) CANIDin and 0 CAN1->sFilterRegister[0].FR1 = the_conf.CANIDin << 5; // (10) CANIDin + 0 (broadcast)
if(flags.can_monitor){ /* (11) */
CAN1->FA1R |= CAN_FA1R_FACT1; // activate filter1
CAN1->sFilterRegister[1].FR1 = 0; // all packets CAN1->sFilterRegister[1].FR1 = 0; // all packets
CAN1->FFA1R = 2; // filter 1 for FIFO1 if(!flags.can_monitor){ /* (11) */
CAN1->FM1R = CAN_FM1R_FBM0 | CAN_FM1R_FBM1; // both in ID mode
} }
CAN1->FFA1R = 2; // filter 1 for FIFO1
CAN1->FMR &= ~CAN_FMR_FINIT; /* (12) */ CAN1->FMR &= ~CAN_FMR_FINIT; /* (12) */
CAN1->IER |= CAN_IER_ERRIE | CAN_IER_FOVIE0 | CAN_IER_FOVIE1 | CAN_IER_BOFIE; /* (13) */ CAN1->IER |= CAN_IER_ERRIE | CAN_IER_FOVIE0 | CAN_IER_FOVIE1 | CAN_IER_BOFIE; /* (13) */
@@ -249,6 +252,7 @@ CAN_status CAN_send(CAN_message *message){
IWDG->KR = IWDG_REFRESH; IWDG->KR = IWDG_REFRESH;
uint8_t *msg = message->data; uint8_t *msg = message->data;
uint8_t len = message->length; uint8_t len = message->length;
if(len > 8) len = 8;
uint16_t target_id = message->ID; uint16_t target_id = message->ID;
uint8_t mailbox = 0xff; uint8_t mailbox = 0xff;
uint32_t Tstart = Tms; uint32_t Tstart = Tms;

View File

@@ -106,6 +106,7 @@ int store_userconf(){
static int write2flash(const void *start, const void *wrdata, uint32_t stor_size){ static int write2flash(const void *start, const void *wrdata, uint32_t stor_size){
int ret = 0; int ret = 0;
__disable_irq();
if (FLASH->CR & FLASH_CR_LOCK){ // unloch flash if (FLASH->CR & FLASH_CR_LOCK){ // unloch flash
FLASH->KEYR = FLASH_KEY1; FLASH->KEYR = FLASH_KEY1;
FLASH->KEYR = FLASH_KEY2; FLASH->KEYR = FLASH_KEY2;
@@ -120,11 +121,13 @@ static int write2flash(const void *start, const void *wrdata, uint32_t stor_size
*(volatile uint16_t*)(address + i) = data[i]; *(volatile uint16_t*)(address + i) = data[i];
while(FLASH->SR & FLASH_SR_BSY) IWDG->KR = IWDG_REFRESH; while(FLASH->SR & FLASH_SR_BSY) IWDG->KR = IWDG_REFRESH;
if(*(volatile uint16_t*)(address + i) != data[i]){ if(*(volatile uint16_t*)(address + i) != data[i]){
__enable_irq();
usart_send("DON'T MATCH!\n"); usart_send("DON'T MATCH!\n");
ret = 1; ret = 1;
break; break;
} }
if(FLASH->SR & FLASH_SR_PGERR){ if(FLASH->SR & FLASH_SR_PGERR){
__enable_irq();
usart_send("Prog err\n"); usart_send("Prog err\n");
ret = 1; // program error - meet not 0xffff ret = 1; // program error - meet not 0xffff
break; break;
@@ -132,6 +135,7 @@ static int write2flash(const void *start, const void *wrdata, uint32_t stor_size
FLASH->SR = FLASH_SR_EOP | FLASH_SR_PGERR | FLASH_SR_WRPRTERR; FLASH->SR = FLASH_SR_EOP | FLASH_SR_PGERR | FLASH_SR_WRPRTERR;
} }
FLASH->CR &= ~(FLASH_CR_PG); FLASH->CR &= ~(FLASH_CR_PG);
__enable_irq();
return ret; return ret;
} }

Binary file not shown.

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 18.0.0, 2025-11-06T11:01:40. --> <!-- Written by QtCreator 20.0.2, 2026-10-01T17:35:26. -->
<qtcreator> <qtcreator>
<data> <data>
<variable>EnvironmentId</variable> <variable>EnvironmentId</variable>
@@ -14,8 +14,6 @@
<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.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"> <valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0">
<value type="QString" key="language">Cpp</value> <value type="QString" key="language">Cpp</value>
<valuemap type="QVariantMap" key="value"> <valuemap type="QVariantMap" key="value">
@@ -30,33 +28,16 @@
</valuemap> </valuemap>
<value type="qlonglong" key="EditorConfiguration.CodeStyle.Count">2</value> <value type="qlonglong" key="EditorConfiguration.CodeStyle.Count">2</value>
<value type="QByteArray" key="EditorConfiguration.Codec">KOI8-R</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="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.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">false</value> <value type="bool" key="EditorConfiguration.ScrollWheelZooming">false</value>
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">1</value> <value type="int" key="EditorConfiguration.SmartBackspaceBehavior">1</value>
<value type="bool" key="EditorConfiguration.SmartSelectionChanging">true</value>
<value type="bool" key="EditorConfiguration.SpacesForTabs">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="int" key="EditorConfiguration.TabSize">8</value>
<value type="bool" key="EditorConfiguration.UseGlobal">true</value> <value type="bool" key="EditorConfiguration.UseGlobal">true</value>
<value type="bool" key="EditorConfiguration.UseIndenter">false</value>
<value type="int" key="EditorConfiguration.Utf8BomBehavior">2</value> <value type="int" key="EditorConfiguration.Utf8BomBehavior">2</value>
<value type="bool" key="EditorConfiguration.addFinalNewLine">true</value> <value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
<value type="bool" key="EditorConfiguration.cleanIndentation">true</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">true</value> <value type="bool" key="EditorConfiguration.inEntireDocument">true</value>
<value type="bool" key="EditorConfiguration.skipTrailingWhitespace">true</value>
<value type="bool" key="EditorConfiguration.tintMarginArea">true</value>
</valuemap> </valuemap>
</data> </data>
<data> <data>
@@ -76,10 +57,7 @@
<value type="int" key="AutoTest.RunAfterBuild">0</value> <value type="int" key="AutoTest.RunAfterBuild">0</value>
<value type="bool" key="AutoTest.UseGlobal">true</value> <value type="bool" key="AutoTest.UseGlobal">true</value>
<valuemap type="QVariantMap" key="ClangTools"> <valuemap type="QVariantMap" key="ClangTools">
<value type="bool" key="ClangTools.AnalyzeOpenFiles">true</value> <value type="Utils::Id" key="ClangTools.DiagnosticConfig"></value>
<value type="bool" key="ClangTools.BuildBeforeAnalysis">true</value>
<value type="QString" key="ClangTools.DiagnosticConfig">Builtin.DefaultTidyAndClazy</value>
<value type="int" key="ClangTools.ParallelJobs">4</value>
<value type="bool" key="ClangTools.PreferConfigFile">false</value> <value type="bool" key="ClangTools.PreferConfigFile">false</value>
<valuelist type="QVariantList" key="ClangTools.SelectedDirs"/> <valuelist type="QVariantList" key="ClangTools.SelectedDirs"/>
<valuelist type="QVariantList" key="ClangTools.SelectedFiles"/> <valuelist type="QVariantList" key="ClangTools.SelectedFiles"/>
@@ -132,7 +110,7 @@
<value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value> <value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.CustomParsers"/> <valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.CustomParsers"/>
<value type="bool" key="ProjectExplorer.BuildConfiguration.ParseStandardOutput">false</value> <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">По умолчанию</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.ActiveDeployConfiguration">0</value>
@@ -154,9 +132,10 @@
<value type="bool" key="Analyzer.Perf.Settings.UseGlobalSettings">true</value> <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.QmlProfiler.Settings.UseGlobalSettings">true</value>
<value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value> <value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value>
<valuelist type="QVariantList" key="Analyzer.Valgrind.SuppressionFiles"/>
<valuelist type="QVariantList" key="CustomOutputParsers"/> <valuelist type="QVariantList" key="CustomOutputParsers"/>
<value type="int" key="PE.EnvironmentAspect.Base">2</value> <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="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="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.DisplayName"></value>
@@ -187,9 +166,10 @@
<value type="bool" key="Analyzer.Perf.Settings.UseGlobalSettings">true</value> <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.QmlProfiler.Settings.UseGlobalSettings">true</value>
<value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value> <value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value>
<valuelist type="QVariantList" key="Analyzer.Valgrind.SuppressionFiles"/>
<valuelist type="QVariantList" key="CustomOutputParsers"/> <valuelist type="QVariantList" key="CustomOutputParsers"/>
<value type="int" key="PE.EnvironmentAspect.Base">2</value> <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="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="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.DisplayName"></value>

View File

@@ -1,3 +1,4 @@
Readme.md
adc.c adc.c
adc.h adc.h
buttons.c buttons.c

View File

@@ -90,8 +90,8 @@ void gpio_setup(void){
AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_DISABLE; AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_DISABLE;
#endif #endif
// be sure that all OK // be sure that all OK
// __ISB(); __ISB();
// __DSB(); __DSB();
// pullups & initial values // pullups & initial values
GPIOA->ODR = 0; GPIOA->ODR = 0;
GPIOB->ODR = (1<<2) | (1<<10) | (1<<11) | (1<<12) | (1<<13) | (1<<14); GPIOB->ODR = (1<<2) | (1<<10) | (1<<11) | (1<<12) | (1<<13) | (1<<14);
@@ -174,7 +174,7 @@ static const pin_t OUT[OUTMAX+1] = {
// bit 1 - input channel is working, 0 - no // bit 1 - input channel is working, 0 - no
uint32_t inchannels(){ uint32_t inchannels(){
return 0b1111110011111111; return 0b1111110111111111;
} }
// bit 1 - input channel is working, 0 - no // bit 1 - input channel is working, 0 - no
uint32_t outchannels(){ uint32_t outchannels(){

View File

@@ -864,6 +864,22 @@
(color 0 0 0 0) (color 0 0 0 0)
(uuid "617159a7-e972-442a-afc4-859b99b5ab99") (uuid "617159a7-e972-442a-afc4-859b99b5ab99")
) )
(junction
(at 49.53 55.245)
(diameter 0)
(color 0 0 0 0)
(uuid "f02b403f-5bfa-4c89-8c3c-cba6eca7961a")
)
(wire
(pts
(xy 47.625 55.245) (xy 49.53 55.245)
)
(stroke
(width 0)
(type default)
)
(uuid "050f5e42-5517-4a61-be02-6858a2be9689")
)
(wire (wire
(pts (pts
(xy 49.53 47.625) (xy 51.435 47.625) (xy 49.53 47.625) (xy 51.435 47.625)
@@ -884,6 +900,16 @@
) )
(uuid "34fd5b0c-e125-4544-a706-171996c9fe41") (uuid "34fd5b0c-e125-4544-a706-171996c9fe41")
) )
(wire
(pts
(xy 49.53 55.245) (xy 51.435 55.245)
)
(stroke
(width 0)
(type default)
)
(uuid "46d54f8c-ebef-4010-a2d0-efae64c3569b")
)
(wire (wire
(pts (pts
(xy 69.85 29.845) (xy 75.565 29.845) (xy 69.85 29.845) (xy 75.565 29.845)
@@ -904,16 +930,6 @@
) )
(uuid "5bf1c17f-a49c-4016-a7d6-d63b4d463e74") (uuid "5bf1c17f-a49c-4016-a7d6-d63b4d463e74")
) )
(wire
(pts
(xy 49.53 55.245) (xy 51.435 55.245)
)
(stroke
(width 0)
(type default)
)
(uuid "7ceab231-4da6-480e-af8b-da00a2eb2700")
)
(wire (wire
(pts (pts
(xy 69.85 45.085) (xy 69.85 47.625) (xy 69.85 45.085) (xy 69.85 47.625)
@@ -967,7 +983,7 @@
) )
(hierarchical_label "Xin" (hierarchical_label "Xin"
(shape input) (shape input)
(at 47.625 40.005 180) (at 47.625 55.245 180)
(effects (effects
(font (font
(size 1.27 1.27) (size 1.27 1.27)
@@ -978,7 +994,7 @@
) )
(hierarchical_label "Xcom" (hierarchical_label "Xcom"
(shape input) (shape input)
(at 49.53 55.245 180) (at 47.625 40.005 180)
(effects (effects
(font (font
(size 1.27 1.27) (size 1.27 1.27)

View File

@@ -53,6 +53,7 @@
"zone_display_mode": 0 "zone_display_mode": 0
}, },
"git": { "git": {
"integration_disabled": false,
"repo_password": "", "repo_password": "",
"repo_type": "", "repo_type": "",
"repo_username": "", "repo_username": "",

View File

@@ -3805,6 +3805,156 @@
) )
(embedded_fonts no) (embedded_fonts no)
) )
(symbol "Device:D_TVS"
(pin_numbers
(hide yes)
)
(pin_names
(offset 1.016)
(hide yes)
)
(exclude_from_sim no)
(in_bom yes)
(on_board yes)
(property "Reference" "D"
(at 0 2.54 0)
(effects
(font
(size 1.27 1.27)
)
)
)
(property "Value" "D_TVS"
(at 0 -2.54 0)
(effects
(font
(size 1.27 1.27)
)
)
)
(property "Footprint" ""
(at 0 0 0)
(effects
(font
(size 1.27 1.27)
)
(hide yes)
)
)
(property "Datasheet" "~"
(at 0 0 0)
(effects
(font
(size 1.27 1.27)
)
(hide yes)
)
)
(property "Description" "Bidirectional transient-voltage-suppression diode"
(at 0 0 0)
(effects
(font
(size 1.27 1.27)
)
(hide yes)
)
)
(property "ki_keywords" "diode TVS thyrector"
(at 0 0 0)
(effects
(font
(size 1.27 1.27)
)
(hide yes)
)
)
(property "ki_fp_filters" "TO-???* *_Diode_* *SingleDiode* D_*"
(at 0 0 0)
(effects
(font
(size 1.27 1.27)
)
(hide yes)
)
)
(symbol "D_TVS_0_1"
(polyline
(pts
(xy -2.54 1.27) (xy -2.54 -1.27) (xy 2.54 1.27) (xy 2.54 -1.27) (xy -2.54 1.27)
)
(stroke
(width 0.254)
(type default)
)
(fill
(type none)
)
)
(polyline
(pts
(xy 0.508 1.27) (xy 0 1.27) (xy 0 -1.27) (xy -0.508 -1.27)
)
(stroke
(width 0.254)
(type default)
)
(fill
(type none)
)
)
(polyline
(pts
(xy 1.27 0) (xy -1.27 0)
)
(stroke
(width 0)
(type default)
)
(fill
(type none)
)
)
)
(symbol "D_TVS_1_1"
(pin passive line
(at -3.81 0 0)
(length 2.54)
(name "A1"
(effects
(font
(size 1.27 1.27)
)
)
)
(number "1"
(effects
(font
(size 1.27 1.27)
)
)
)
)
(pin passive line
(at 3.81 0 180)
(length 2.54)
(name "A2"
(effects
(font
(size 1.27 1.27)
)
)
)
(number "2"
(effects
(font
(size 1.27 1.27)
)
)
)
)
)
(embedded_fonts no)
)
(symbol "Device:D_Zener" (symbol "Device:D_Zener"
(pin_numbers (pin_numbers
(hide yes) (hide yes)
@@ -5196,144 +5346,6 @@
) )
(embedded_fonts no) (embedded_fonts no)
) )
(symbol "Diode:SM6T6V8A"
(pin_numbers
(hide yes)
)
(pin_names
(offset 1.016)
(hide yes)
)
(exclude_from_sim no)
(in_bom yes)
(on_board yes)
(property "Reference" "D"
(at 0 2.54 0)
(effects
(font
(size 1.27 1.27)
)
)
)
(property "Value" "SM6T6V8A"
(at 0 -2.54 0)
(effects
(font
(size 1.27 1.27)
)
)
)
(property "Footprint" "Diode_SMD:D_SMB"
(at 0 -5.08 0)
(effects
(font
(size 1.27 1.27)
)
(hide yes)
)
)
(property "Datasheet" "https://www.st.com/resource/en/datasheet/sm6t.pdf"
(at -1.27 0 0)
(effects
(font
(size 1.27 1.27)
)
(hide yes)
)
)
(property "Description" "600W unidirectional Transil Transient Voltage Suppressor, 6.8Vrwm, DO-214AA"
(at 0 0 0)
(effects
(font
(size 1.27 1.27)
)
(hide yes)
)
)
(property "ki_keywords" "diode TVS voltage suppressor"
(at 0 0 0)
(effects
(font
(size 1.27 1.27)
)
(hide yes)
)
)
(property "ki_fp_filters" "D*SMB*"
(at 0 0 0)
(effects
(font
(size 1.27 1.27)
)
(hide yes)
)
)
(symbol "SM6T6V8A_0_1"
(polyline
(pts
(xy -0.762 1.27) (xy -1.27 1.27) (xy -1.27 -1.27)
)
(stroke
(width 0.254)
(type default)
)
(fill
(type none)
)
)
(polyline
(pts
(xy 1.27 1.27) (xy 1.27 -1.27) (xy -1.27 0) (xy 1.27 1.27)
)
(stroke
(width 0.254)
(type default)
)
(fill
(type none)
)
)
)
(symbol "SM6T6V8A_1_1"
(pin passive line
(at -3.81 0 0)
(length 2.54)
(name "A1"
(effects
(font
(size 1.27 1.27)
)
)
)
(number "1"
(effects
(font
(size 1.27 1.27)
)
)
)
)
(pin passive line
(at 3.81 0 180)
(length 2.54)
(name "A2"
(effects
(font
(size 1.27 1.27)
)
)
)
(number "2"
(effects
(font
(size 1.27 1.27)
)
)
)
)
)
(embedded_fonts no)
)
(symbol "Diode:SMAJ30A" (symbol "Diode:SMAJ30A"
(pin_numbers (pin_numbers
(hide yes) (hide yes)
@@ -11339,6 +11351,16 @@
) )
(uuid face456b-c4d3-4977-8e8a-a5c27ba953ff) (uuid face456b-c4d3-4977-8e8a-a5c27ba953ff)
) )
(text "(COM)"
(exclude_from_sim no)
(at 453.39 176.53 0)
(effects
(font
(size 1.27 1.27)
)
)
(uuid "13b660a1-268e-4493-beb4-6b6351d095ee")
)
(text "RS-232" (text "RS-232"
(exclude_from_sim no) (exclude_from_sim no)
(at 81.28 332.74 0) (at 81.28 332.74 0)
@@ -11389,9 +11411,9 @@
) )
(uuid "4d7f305b-00a1-493f-995a-ab259abdad08") (uuid "4d7f305b-00a1-493f-995a-ab259abdad08")
) )
(text "Analog inputs" (text "Analog inputs (Umax = 10V)"
(exclude_from_sim no) (exclude_from_sim no)
(at 254 309.88 0) (at 247.65 309.88 0)
(effects (effects
(font (font
(size 3 3) (size 3 3)
@@ -11419,9 +11441,9 @@
) )
(uuid "63aa7ac3-f03d-49c1-b81d-567c02d6c7a0") (uuid "63aa7ac3-f03d-49c1-b81d-567c02d6c7a0")
) )
(text "DAC output" (text "DAC output (1mA max; 0..10V)"
(exclude_from_sim no) (exclude_from_sim no)
(at 270.51 262.89 0) (at 283.21 261.62 0)
(effects (effects
(font (font
(size 2 2) (size 2 2)
@@ -11450,6 +11472,16 @@
) )
(uuid "6e99b878-c7ec-40c4-a4de-f1271a8da814") (uuid "6e99b878-c7ec-40c4-a4de-f1271a8da814")
) )
(text "U_{Out} ≈ 3 U_{In}"
(exclude_from_sim no)
(at 256.54 275.59 0)
(effects
(font
(size 2 2)
)
)
(uuid "900d596b-090b-43b3-91ae-a2c6ad636a1f")
)
(text "Optional!" (text "Optional!"
(exclude_from_sim no) (exclude_from_sim no)
(at 74.93 255.27 0) (at 74.93 255.27 0)
@@ -11501,6 +11533,16 @@
) )
(uuid "c405c04e-9d45-493c-a445-173823401c47") (uuid "c405c04e-9d45-493c-a445-173823401c47")
) )
(text "(Imax = 20mA)"
(exclude_from_sim no)
(at 247.65 340.36 0)
(effects
(font
(size 3 3)
)
)
(uuid "c71cecac-4533-4217-84db-c92ecac5dbce")
)
(text "Prog" (text "Prog"
(exclude_from_sim no) (exclude_from_sim no)
(at 312.42 36.195 0) (at 312.42 36.195 0)
@@ -16403,7 +16445,7 @@
(uuid "29f388ae-600b-4244-8971-cb6dd7da67b4") (uuid "29f388ae-600b-4244-8971-cb6dd7da67b4")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "R1") (reference "R1")
(unit 1) (unit 1)
@@ -16549,7 +16591,7 @@
(uuid "5ecb05b4-ca11-4ead-ba66-2f1f9a1b9191") (uuid "5ecb05b4-ca11-4ead-ba66-2f1f9a1b9191")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "SW3") (reference "SW3")
(unit 2) (unit 2)
@@ -16820,7 +16862,7 @@
(uuid "08bb7a9d-9472-4365-a3d7-2ae360f76ebc") (uuid "08bb7a9d-9472-4365-a3d7-2ae360f76ebc")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "#PWR046") (reference "#PWR046")
(unit 1) (unit 1)
@@ -16931,7 +16973,7 @@
(uuid "e354257e-d237-4e19-b7f5-02b63bdb9c55") (uuid "e354257e-d237-4e19-b7f5-02b63bdb9c55")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U3") (reference "U3")
(unit 1) (unit 1)
@@ -17001,7 +17043,7 @@
(uuid "b9ad2e85-e01b-4b9b-8975-d6c132171592") (uuid "b9ad2e85-e01b-4b9b-8975-d6c132171592")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "D20") (reference "D20")
(unit 1) (unit 1)
@@ -17292,7 +17334,7 @@
(uuid "90d13576-6e80-4704-b0e7-3ada249fa550") (uuid "90d13576-6e80-4704-b0e7-3ada249fa550")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U22") (reference "U22")
(unit 1) (unit 1)
@@ -17764,7 +17806,7 @@
(uuid "64240610-c4ea-40b7-9783-85aed92866b2") (uuid "64240610-c4ea-40b7-9783-85aed92866b2")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U24") (reference "U24")
(unit 1) (unit 1)
@@ -17831,7 +17873,7 @@
(uuid "57f9fc8a-d687-412b-ae4e-2f304f4150fc") (uuid "57f9fc8a-d687-412b-ae4e-2f304f4150fc")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "#FLG01") (reference "#FLG01")
(unit 1) (unit 1)
@@ -17897,7 +17939,7 @@
(uuid "c18acfe2-8260-4c99-be4b-099db0e70104") (uuid "c18acfe2-8260-4c99-be4b-099db0e70104")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "#PWR051") (reference "#PWR051")
(unit 1) (unit 1)
@@ -17985,7 +18027,7 @@
(uuid "c9070210-9b6c-43e4-b00b-c539795a3fb5") (uuid "c9070210-9b6c-43e4-b00b-c539795a3fb5")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U25") (reference "U25")
(unit 3) (unit 3)
@@ -18164,7 +18206,7 @@
(uuid "bb5a0fed-588b-4816-b33b-1cadfa365537") (uuid "bb5a0fed-588b-4816-b33b-1cadfa365537")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U20") (reference "U20")
(unit 1) (unit 1)
@@ -18402,7 +18444,7 @@
(uuid "5791c6a2-d543-40ab-9ae5-36e78c3c304b") (uuid "5791c6a2-d543-40ab-9ae5-36e78c3c304b")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "J7") (reference "J7")
(unit 1) (unit 1)
@@ -18747,7 +18789,7 @@
) )
) )
(symbol (symbol
(lib_id "Diode:SM6T6V8A") (lib_id "Device:D_TVS")
(at 68.58 250.19 90) (at 68.58 250.19 90)
(unit 1) (unit 1)
(exclude_from_sim no) (exclude_from_sim no)
@@ -18765,7 +18807,7 @@
(justify right) (justify right)
) )
) )
(property "Value" "SM6T6V8A" (property "Value" "P6SMB6.8"
(at 70.612 251.4021 90) (at 70.612 251.4021 90)
(effects (effects
(font (font
@@ -18775,7 +18817,7 @@
) )
) )
(property "Footprint" "Diode_SMD:D_SMB" (property "Footprint" "Diode_SMD:D_SMB"
(at 73.66 250.19 0) (at 68.58 250.19 0)
(effects (effects
(font (font
(size 1.27 1.27) (size 1.27 1.27)
@@ -18783,8 +18825,8 @@
(hide yes) (hide yes)
) )
) )
(property "Datasheet" "https://www.st.com/resource/en/datasheet/sm6t.pdf" (property "Datasheet" "~"
(at 68.58 251.46 0) (at 68.58 250.19 0)
(effects (effects
(font (font
(size 1.27 1.27) (size 1.27 1.27)
@@ -18792,7 +18834,7 @@
(hide yes) (hide yes)
) )
) )
(property "Description" "600W unidirectional Transil Transient Voltage Suppressor, 6.8Vrwm, DO-214AA" (property "Description" "Bidirectional transient-voltage-suppression diode"
(at 68.58 250.19 0) (at 68.58 250.19 0)
(effects (effects
(font (font
@@ -18954,7 +18996,7 @@
(uuid "5ecb05b4-ca11-4ead-ba66-2f1f9a1b9192") (uuid "5ecb05b4-ca11-4ead-ba66-2f1f9a1b9192")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "SW3") (reference "SW3")
(unit 1) (unit 1)
@@ -19020,7 +19062,7 @@
(uuid "9d3dbc1b-15ac-42ec-8e79-33bd7953a488") (uuid "9d3dbc1b-15ac-42ec-8e79-33bd7953a488")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "#PWR02") (reference "#PWR02")
(unit 1) (unit 1)
@@ -19157,7 +19199,7 @@
(uuid "afa81ebd-d054-4f33-bbf5-9aa05f2a9e28") (uuid "afa81ebd-d054-4f33-bbf5-9aa05f2a9e28")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "F1") (reference "F1")
(unit 1) (unit 1)
@@ -19979,7 +20021,7 @@
(uuid "c9070210-9b6c-43e4-b00b-c539795a3fb6") (uuid "c9070210-9b6c-43e4-b00b-c539795a3fb6")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U25") (reference "U25")
(unit 2) (unit 2)
@@ -20269,7 +20311,7 @@
(uuid "c9070210-9b6c-43e4-b00b-c539795a3fb7") (uuid "c9070210-9b6c-43e4-b00b-c539795a3fb7")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U25") (reference "U25")
(unit 1) (unit 1)
@@ -20296,7 +20338,7 @@
(justify left) (justify left)
) )
) )
(property "Value" "schottky" (property "Value" "1N4148?"
(at 120.142 69.4746 90) (at 120.142 69.4746 90)
(effects (effects
(font (font
@@ -20339,7 +20381,7 @@
(uuid "4939ffcd-4f71-4fa9-a0ba-37139fadf745") (uuid "4939ffcd-4f71-4fa9-a0ba-37139fadf745")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "D35") (reference "D35")
(unit 1) (unit 1)
@@ -21750,7 +21792,7 @@
(uuid "d0e2b595-fd8b-40f3-b2a6-e692ef828198") (uuid "d0e2b595-fd8b-40f3-b2a6-e692ef828198")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "L1") (reference "L1")
(unit 1) (unit 1)
@@ -21885,7 +21927,7 @@
(uuid "cce4560b-5eaf-4b66-aa7d-7b6c311f73a7") (uuid "cce4560b-5eaf-4b66-aa7d-7b6c311f73a7")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "J2") (reference "J2")
(unit 1) (unit 1)
@@ -21894,7 +21936,7 @@
) )
) )
(symbol (symbol
(lib_id "Diode:SM6T6V8A") (lib_id "Device:D_TVS")
(at 78.74 300.99 270) (at 78.74 300.99 270)
(unit 1) (unit 1)
(exclude_from_sim no) (exclude_from_sim no)
@@ -21912,7 +21954,7 @@
(justify left) (justify left)
) )
) )
(property "Value" "SM6T6V8A" (property "Value" "P6SMB6.8"
(at 80.772 302.2021 90) (at 80.772 302.2021 90)
(effects (effects
(font (font
@@ -21922,7 +21964,7 @@
) )
) )
(property "Footprint" "Diode_SMD:D_SMB" (property "Footprint" "Diode_SMD:D_SMB"
(at 73.66 300.99 0) (at 78.74 300.99 0)
(effects (effects
(font (font
(size 1.27 1.27) (size 1.27 1.27)
@@ -21930,8 +21972,8 @@
(hide yes) (hide yes)
) )
) )
(property "Datasheet" "https://www.st.com/resource/en/datasheet/sm6t.pdf" (property "Datasheet" "~"
(at 78.74 299.72 0) (at 78.74 300.99 0)
(effects (effects
(font (font
(size 1.27 1.27) (size 1.27 1.27)
@@ -21939,7 +21981,7 @@
(hide yes) (hide yes)
) )
) )
(property "Description" "600W unidirectional Transil Transient Voltage Suppressor, 6.8Vrwm, DO-214AA" (property "Description" "Bidirectional transient-voltage-suppression diode"
(at 78.74 300.99 0) (at 78.74 300.99 0)
(effects (effects
(font (font
@@ -22025,7 +22067,7 @@
(uuid "6c5c7ba7-c680-403b-b977-c868b4261bf4") (uuid "6c5c7ba7-c680-403b-b977-c868b4261bf4")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "C1") (reference "C1")
(unit 1) (unit 1)
@@ -22699,7 +22741,7 @@
) )
) )
(symbol (symbol
(lib_id "Diode:SM6T6V8A") (lib_id "Device:D_TVS")
(at 68.58 262.89 270) (at 68.58 262.89 270)
(unit 1) (unit 1)
(exclude_from_sim no) (exclude_from_sim no)
@@ -22717,7 +22759,7 @@
(justify left) (justify left)
) )
) )
(property "Value" "SM6T6V8A" (property "Value" "P6SMB6.8"
(at 70.612 264.1021 90) (at 70.612 264.1021 90)
(effects (effects
(font (font
@@ -22727,7 +22769,7 @@
) )
) )
(property "Footprint" "Diode_SMD:D_SMB" (property "Footprint" "Diode_SMD:D_SMB"
(at 63.5 262.89 0) (at 68.58 262.89 0)
(effects (effects
(font (font
(size 1.27 1.27) (size 1.27 1.27)
@@ -22735,8 +22777,8 @@
(hide yes) (hide yes)
) )
) )
(property "Datasheet" "https://www.st.com/resource/en/datasheet/sm6t.pdf" (property "Datasheet" "~"
(at 68.58 261.62 0) (at 68.58 262.89 0)
(effects (effects
(font (font
(size 1.27 1.27) (size 1.27 1.27)
@@ -22744,7 +22786,7 @@
(hide yes) (hide yes)
) )
) )
(property "Description" "600W unidirectional Transil Transient Voltage Suppressor, 6.8Vrwm, DO-214AA" (property "Description" "Bidirectional transient-voltage-suppression diode"
(at 68.58 262.89 0) (at 68.58 262.89 0)
(effects (effects
(font (font
@@ -22831,7 +22873,7 @@
(uuid "a5055c83-a704-4928-8192-5c6507dfd81c") (uuid "a5055c83-a704-4928-8192-5c6507dfd81c")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U19") (reference "U19")
(unit 1) (unit 1)
@@ -23040,7 +23082,7 @@
) )
) )
(symbol (symbol
(lib_id "Diode:SM6T6V8A") (lib_id "Device:D_TVS")
(at 78.74 288.29 90) (at 78.74 288.29 90)
(unit 1) (unit 1)
(exclude_from_sim no) (exclude_from_sim no)
@@ -23058,7 +23100,7 @@
(justify right) (justify right)
) )
) )
(property "Value" "SM6T6V8A" (property "Value" "P6SMB6.8"
(at 80.772 289.5021 90) (at 80.772 289.5021 90)
(effects (effects
(font (font
@@ -23068,7 +23110,7 @@
) )
) )
(property "Footprint" "Diode_SMD:D_SMB" (property "Footprint" "Diode_SMD:D_SMB"
(at 83.82 288.29 0) (at 78.74 288.29 0)
(effects (effects
(font (font
(size 1.27 1.27) (size 1.27 1.27)
@@ -23076,8 +23118,8 @@
(hide yes) (hide yes)
) )
) )
(property "Datasheet" "https://www.st.com/resource/en/datasheet/sm6t.pdf" (property "Datasheet" "~"
(at 78.74 289.56 0) (at 78.74 288.29 0)
(effects (effects
(font (font
(size 1.27 1.27) (size 1.27 1.27)
@@ -23085,7 +23127,7 @@
(hide yes) (hide yes)
) )
) )
(property "Description" "600W unidirectional Transil Transient Voltage Suppressor, 6.8Vrwm, DO-214AA" (property "Description" "Bidirectional transient-voltage-suppression diode"
(at 78.74 288.29 0) (at 78.74 288.29 0)
(effects (effects
(font (font
@@ -23101,7 +23143,7 @@
(uuid "1f63512f-5eda-49cc-bebc-140febe8048b") (uuid "1f63512f-5eda-49cc-bebc-140febe8048b")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "D23") (reference "D23")
(unit 1) (unit 1)
@@ -23459,7 +23501,7 @@
(uuid "5cb602bd-672c-4434-9e18-b3c46e1b7e7e") (uuid "5cb602bd-672c-4434-9e18-b3c46e1b7e7e")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "J8") (reference "J8")
(unit 1) (unit 1)
@@ -23529,7 +23571,7 @@
(uuid "770cbac8-9e9a-4520-b802-111185d206bc") (uuid "770cbac8-9e9a-4520-b802-111185d206bc")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "L2") (reference "L2")
(unit 1) (unit 1)
@@ -23932,7 +23974,7 @@
(uuid "5760a80f-2f7f-4816-85a5-d01fccfcf0ff") (uuid "5760a80f-2f7f-4816-85a5-d01fccfcf0ff")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "R93") (reference "R93")
(unit 1) (unit 1)
@@ -24196,7 +24238,7 @@
(uuid "cf7c475e-f19b-46cb-84a3-814058d501e2") (uuid "cf7c475e-f19b-46cb-84a3-814058d501e2")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "#PWR057") (reference "#PWR057")
(unit 1) (unit 1)
@@ -25202,7 +25244,7 @@
(uuid "aa0adaeb-c46a-423d-8ffc-48cb55506c3e") (uuid "aa0adaeb-c46a-423d-8ffc-48cb55506c3e")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "D1") (reference "D1")
(unit 1) (unit 1)
@@ -25481,7 +25523,7 @@
(uuid "aedf02c5-5db9-4d32-9d0d-54c752de3d0f") (uuid "aedf02c5-5db9-4d32-9d0d-54c752de3d0f")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "BT1") (reference "BT1")
(unit 1) (unit 1)
@@ -25683,7 +25725,7 @@
(uuid "180d8377-e1a9-4750-9f5b-14a15b74aa62") (uuid "180d8377-e1a9-4750-9f5b-14a15b74aa62")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "D21") (reference "D21")
(unit 1) (unit 1)
@@ -26022,7 +26064,7 @@
(uuid "990315c9-5f16-4bf2-bb81-c39fad8807b5") (uuid "990315c9-5f16-4bf2-bb81-c39fad8807b5")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "RV1") (reference "RV1")
(unit 1) (unit 1)
@@ -26156,7 +26198,7 @@
(uuid "c76ce31e-29e3-409e-9823-311438222fe5") (uuid "c76ce31e-29e3-409e-9823-311438222fe5")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "Y1") (reference "Y1")
(unit 1) (unit 1)
@@ -26242,7 +26284,7 @@
(uuid "7a60d95c-5991-445c-8c92-11a331604b5b") (uuid "7a60d95c-5991-445c-8c92-11a331604b5b")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U5") (reference "U5")
(unit 1) (unit 1)
@@ -26335,7 +26377,7 @@
) )
) )
) )
(property "Value" "M7" (property "Value" "1N4007"
(at 57.15 38.9198 0) (at 57.15 38.9198 0)
(effects (effects
(font (font
@@ -26607,7 +26649,7 @@
) )
) )
) )
(property "Value" "M7" (property "Value" "1N4007"
(at 381 26.2198 0) (at 381 26.2198 0)
(effects (effects
(font (font
@@ -27448,7 +27490,7 @@
(uuid "1a2b7a75-58d5-495e-a4f9-65a8ae25f997") (uuid "1a2b7a75-58d5-495e-a4f9-65a8ae25f997")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "#PWR01") (reference "#PWR01")
(unit 1) (unit 1)
@@ -27474,7 +27516,7 @@
(justify left) (justify left)
) )
) )
(property "Value" "schottky" (property "Value" "1N4148?"
(at 104.14 69.215 90) (at 104.14 69.215 90)
(effects (effects
(font (font
@@ -27742,7 +27784,7 @@
) )
) )
) )
(property "Value" "M7" (property "Value" "1N4007"
(at 64.77 38.9198 0) (at 64.77 38.9198 0)
(effects (effects
(font (font
@@ -27784,7 +27826,7 @@
(uuid "ed6571fa-752a-46bc-bd77-80ec20d042df") (uuid "ed6571fa-752a-46bc-bd77-80ec20d042df")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "D18") (reference "D18")
(unit 1) (unit 1)
@@ -28409,7 +28451,7 @@
(uuid "c4d21b79-4305-42a9-83fe-76b98cb21463") (uuid "c4d21b79-4305-42a9-83fe-76b98cb21463")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "J3") (reference "J3")
(unit 1) (unit 1)
@@ -28972,7 +29014,7 @@
(uuid "18b3be13-4d58-48b7-85be-95eabccc6c65") (uuid "18b3be13-4d58-48b7-85be-95eabccc6c65")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U21") (reference "U21")
(unit 1) (unit 1)
@@ -29688,7 +29730,7 @@
(uuid "1e4a4470-dba7-4ac1-8cf5-45e9bda93f15") (uuid "1e4a4470-dba7-4ac1-8cf5-45e9bda93f15")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "J6") (reference "J6")
(unit 1) (unit 1)
@@ -29902,7 +29944,7 @@
(uuid "9bc91ef6-4a21-4acc-ac3c-41392169ecb9") (uuid "9bc91ef6-4a21-4acc-ac3c-41392169ecb9")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "J1") (reference "J1")
(unit 1) (unit 1)
@@ -29972,7 +30014,7 @@
(uuid "5e048d7f-4acd-49d0-9128-a9f7dd4ae437") (uuid "5e048d7f-4acd-49d0-9128-a9f7dd4ae437")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "C26") (reference "C26")
(unit 1) (unit 1)
@@ -30452,7 +30494,7 @@
(uuid "9720353c-164d-46c0-a485-63d5154e4bd3") (uuid "9720353c-164d-46c0-a485-63d5154e4bd3")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U23") (reference "U23")
(unit 1) (unit 1)
@@ -30886,7 +30928,7 @@
(uuid "be06873d-2fea-44de-9184-81db1ae1b0d0") (uuid "be06873d-2fea-44de-9184-81db1ae1b0d0")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "U1") (reference "U1")
(unit 1) (unit 1)
@@ -31088,7 +31130,7 @@
(uuid "fb6031d5-43e5-4849-acdd-0279e14bc97a") (uuid "fb6031d5-43e5-4849-acdd-0279e14bc97a")
) )
(instances (instances
(project "" (project "fx3u_24mr"
(path "/b583aae5-8eb0-4221-b485-3f768bd7f89b" (path "/b583aae5-8eb0-4221-b485-3f768bd7f89b"
(reference "#PWR054") (reference "#PWR054")
(unit 1) (unit 1)

Binary file not shown.

View File

@@ -45,13 +45,12 @@ TRUE_INLINE void readcoil(modbus_request *r){
return; return;
} }
uint8_t bytes[OUTMAXBYTES] = {0}; uint8_t bytes[OUTMAXBYTES] = {0};
int curidx = OUTMAXBYTES;
int vals = get_relay(OUTMAX+1); int vals = get_relay(OUTMAX+1);
for(int i = 0; i < amount; ++i){ for(int i = 0; i < amount; ++i){
bytes[--curidx] = vals & 0xff; bytes[i] = vals & 0xff;
vals >>= 8; vals >>= 8;
} }
modbus_response resp = {.Fcode = r->Fcode, .ID = the_conf.modbusID, .data = bytes+curidx, .datalen = amount}; modbus_response resp = {.Fcode = r->Fcode, .ID = the_conf.modbusID, .data = bytes, .datalen = amount};
modbus_send_response(&resp); modbus_send_response(&resp);
} }
@@ -69,7 +68,7 @@ TRUE_INLINE void readdiscr(modbus_request *r){
} }
uint8_t bytes[INMAXBYTES] = {0}; uint8_t bytes[INMAXBYTES] = {0};
int vals = get_esw(INMAX+1); int vals = get_esw(INMAX+1);
for(int i = amount - 1; i > -1; --i){ for(int i = 0; i < amount; ++i){
bytes[i] = vals & 0xff; bytes[i] = vals & 0xff;
vals >>= 8; vals >>= 8;
} }
@@ -167,8 +166,7 @@ TRUE_INLINE void writecoils(modbus_request *r){
} }
uint32_t v = 0; uint32_t v = 0;
for(int i = 0; i < amount; ++i){ for(int i = 0; i < amount; ++i){
v <<= 8; v |= r->data[i] << (8 * i);
v |= r->data[i];
} }
if(set_relay(OUTMAX+1, v) < 0){ if(set_relay(OUTMAX+1, v) < 0){
senderr(r, ME_NACK); senderr(r, ME_NACK);

View File

@@ -47,7 +47,7 @@ static void us(){
static volatile int modbus_txrdy = 1; static volatile int modbus_txrdy = 1;
static volatile int modbus_rdy = 0 // received data ready static volatile int modbus_rdy = 0 // received data ready
,dlen = 0 // length of data (including '\n') in current buffer ,dlen = 0 // length of data in current buffer
,bufovr = 0 // input buffer overfull ,bufovr = 0 // input buffer overfull
; ;
@@ -83,6 +83,7 @@ static uint16_t getCRC(uint8_t *data, int l){
*/ */
int modbus_receive(uint8_t **packet){ int modbus_receive(uint8_t **packet){
if(!modbus_rdy) return 0; if(!modbus_rdy) return 0;
if(dlen < 4) return -1; // broken packet
if(bufovr){ if(bufovr){
DBG("Modbus buffer overflow\n"); DBG("Modbus buffer overflow\n");
bufovr = 0; bufovr = 0;
@@ -112,9 +113,9 @@ static int senddata(int l){
DMA2_Channel5->CCR &= ~DMA_CCR_EN; DMA2_Channel5->CCR &= ~DMA_CCR_EN;
DMA2_Channel5->CMAR = (uint32_t) tbuf[tbufno]; // mem DMA2_Channel5->CMAR = (uint32_t) tbuf[tbufno]; // mem
DMA2_Channel5->CNDTR = l + 2; // + CRC DMA2_Channel5->CNDTR = l + 2; // + CRC
_485_Tx();
DMA2_Channel5->CCR |= DMA_CCR_EN; DMA2_Channel5->CCR |= DMA_CCR_EN;
tbufno = !tbufno; tbufno = !tbufno;
_485_Tx();
return l; return l;
} }
@@ -139,7 +140,7 @@ int modbus_send_request(modbus_request *r){
*curbuf++ = (uint8_t) r->regno; // L *curbuf++ = (uint8_t) r->regno; // L
// if r->datalen == 0 - this is responce for request with fcode > 4 // if r->datalen == 0 - this is responce for request with fcode > 4
if((r->Fcode == MC_WRITE_MUL_COILS || r->Fcode == MC_WRITE_MUL_REGS) && r->datalen){ // request with data if((r->Fcode == MC_WRITE_MUL_COILS || r->Fcode == MC_WRITE_MUL_REGS) && r->datalen){ // request with data
if(r->datalen > MODBUSBUFSZO - 7) return -1; if(r->datalen > MODBUSBUFSZO - 9) return -1; // 6 previous + 1 for datalen + 2 for CRC
*curbuf++ = r->datalen; *curbuf++ = r->datalen;
memcpy(curbuf, r->data, r->datalen); memcpy(curbuf, r->data, r->datalen);
n += r->datalen + 1; // + data length byte n += r->datalen + 1; // + data length byte
@@ -164,7 +165,7 @@ int modbus_get_request(modbus_request* r){
if(l > 6){ // request with data if(l > 6){ // request with data
if(r->Fcode != MC_WRITE_MUL_COILS && r->Fcode != MC_WRITE_MUL_REGS) return -1; // bad request if(r->Fcode != MC_WRITE_MUL_COILS && r->Fcode != MC_WRITE_MUL_REGS) return -1; // bad request
r->datalen = pack[4]; r->datalen = pack[4];
if(r->datalen > l-6) r->datalen = l-6; // fix if data bytes less than field if(r->datalen > l - 7) r->datalen = l - 7; // fix if data bytes less than field
r->data = pack + 5; r->data = pack + 5;
}else{ }else{
r->datalen = 0; r->datalen = 0;
@@ -227,6 +228,7 @@ void modbus_setup(uint32_t speed){
NVIC_SetPriority(DMA2_Channel3_IRQn, 2); NVIC_SetPriority(DMA2_Channel3_IRQn, 2);
NVIC_EnableIRQ(DMA2_Channel3_IRQn); NVIC_EnableIRQ(DMA2_Channel3_IRQn);
// setup uart4 // setup uart4
if(speed < 1200) speed = 1200;
UART4->BRR = 36000000 / speed; // APB1 is 36MHz UART4->BRR = 36000000 / speed; // APB1 is 36MHz
UART4->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_UE; // 1start,8data,nstop; enable Rx,Tx,USART UART4->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_UE; // 1start,8data,nstop; enable Rx,Tx,USART
uint32_t tmout = 16000000; uint32_t tmout = 16000000;

View File

@@ -372,7 +372,7 @@ static errcodes modbussend(const char *txt, text_cmd _U_ cmd){
usart_send("Need amount of data for given fcode\n"); usart_send("Need amount of data for given fcode\n");
return ERR_WRONGLEN; return ERR_WRONGLEN;
} }
if(N == 0 || N > MODBUSBUFSZO - 7){ if(N == 0 || N > MODBUSBUFSZO - 9){
usart_send("Data length too big\n"); usart_send("Data length too big\n");
return ERR_BADVAL; return ERR_BADVAL;
} }

View File

@@ -1,2 +1,2 @@
#define BUILD_NUMBER "118" #define BUILD_NUMBER "121"
#define BUILD_DATE "2025-11-06" #define BUILD_DATE "2026-10-01"

View File

@@ -0,0 +1,9 @@
BINARY := panels
# MCU code
MCU ?= F103xB
# change this linking script depending on particular MCU model,
LDSCRIPT ?= stm32f103xB.ld
DEFINES := -DSTM32F10X_MD
include ../makefile.f1
include ../../makefile.stm32

View File

@@ -0,0 +1 @@
Developing code for work with two panels 64x32 pix.

View File

@@ -0,0 +1,94 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// random numbers generator based on ADC values of Tsens and Vref
#include "adcrandom.h"
#define ADC_CHANNELS_NO (2)
// 16-Tsens, 17-Vref
static uint8_t const ADCchno[ADC_CHANNELS_NO] = {16, 17};
uint16_t getADCval(uint8_t ch){
if(ch >= ADC_CHANNELS_NO) return 0;
ADC1->SQR3 = ADCchno[ch];
ADC1->SR = 0;
// turn ON ADC
ADC1->CR2 |= ADC_CR2_ADON;
while(!(ADC1->SR & ADC_SR_EOC)); // wait end of conversion
return ADC1->DR;
}
struct xorshift128_state {
uint32_t a, b, c, d;
} state = {0};
static uint32_t xorshift128(){
/* Algorithm "xor128" from p. 5 of Marsaglia, "Xorshift RNGs" */
uint32_t t = state.d;
uint32_t const s = state.a;
state.d = state.c;
state.c = state.b;
state.b = s;
t ^= t << 11;
t ^= t >> 8;
return state.a = t ^ s ^ (s >> 19);
}
static uint32_t rnd(){
uint32_t r = 0;
for(int i = 0; i < 32; ++i){
r <<= 1;
//r |= (getADCval(0) & 1) ^ (getADCval(1) & 1);
r |= getADCval(0) & 1;
}
return r;
}
uint32_t getRand(){
static uint8_t g = 0;
if(g++ == 0){
state.a = rnd();
state.b = rnd();
state.c = rnd();
state.d = rnd();
}
return xorshift128();
}
void adc_setup(){
//GPIOC->CRL |= CRL(0, CNF_ANALOG|MODE_INPUT);
uint32_t ctr = 0;
// Enable clocking
RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;
RCC->CFGR &= ~(RCC_CFGR_ADCPRE);
RCC->CFGR |= RCC_CFGR_ADCPRE_DIV2; // ADC clock = RCC / 2
// sampling time - 1.5 cycles for all chanels
//ADC1->SMPR1 = ADC_SMPR1_SMP10_0 | ADC_SMPR1_SMP16_0 | ADC_SMPR1_SMP17_0;//channels 10, 16 and 17
// single mode, enable vref & Tsens; wake up ADC
ADC1->CR2 |= ADC_CR2_TSVREFE | ADC_CR2_ADON;
// wait for Tstab - at least 1us
while(++ctr < 0xff) nop();
// calibration
ADC1->CR2 |= ADC_CR2_RSTCAL;
ctr = 0; while((ADC1->CR2 & ADC_CR2_RSTCAL) && ++ctr < 0xfffff);
ADC1->CR2 |= ADC_CR2_CAL;
ctr = 0; while((ADC1->CR2 & ADC_CR2_CAL) && ++ctr < 0xfffff);
}

View File

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

View File

@@ -0,0 +1,35 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef DEBUG_H__
#define DEBUG_H__
#ifdef EBUG
#include "usb.h"
#include "proto.h"
#define DBG(x) USB_send(x)
#define DBGU(x) USB_send(u2str(x))
#define NL() USB_send("\n")
#else // EBUG
#define DBG(x)
#define DBGU(x)
#define NL()
#endif // EBUG
#endif // DEBUG_H__

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,820 @@
/*
* This file is part of the TETRIS project.
* Copyright 2019 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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/>.
*/
// this file should be included JUST ONCE!
// only in fonts.c
#define FONTNUMB8BYTES 10
#define FONTNUMB8HEIGHT 10
#define FONTNUMB8BASELINE 2
/*
32 (0x20) - 64 (0x40) - @ 96 (0x60) - ` 128 (0x80) - € 160 (0xa0) -   192 (0xc0) - À 224 (0xe0) - à
33 (0x21) - ! 65 (0x41) - A 97 (0x61) - a 129 (0x81) - <20> 161 (0xa1) - ¡ 193 (0xc1) - Á 225 (0xe1) - á
34 (0x22) - " 66 (0x42) - B 98 (0x62) - b 130 (0x82) - ‚ 162 (0xa2) - ¢ 194 (0xc2) - Â 226 (0xe2) - â
35 (0x23) - # 67 (0x43) - C 99 (0x63) - c 131 (0x83) - ƒ 163 (0xa3) - £ 195 (0xc3) - Ã 227 (0xe3) - ã
36 (0x24) - $ 68 (0x44) - D 100 (0x64) - d 132 (0x84) - „ 164 (0xa4) - ¤ 196 (0xc4) - Ä 228 (0xe4) - ä
37 (0x25) - % 69 (0x45) - E 101 (0x65) - e 133 (0x85) - … 165 (0xa5) - ¥ 197 (0xc5) - Å 229 (0xe5) - å
38 (0x26) - & 70 (0x46) - F 102 (0x66) - f 134 (0x86) - † 166 (0xa6) - ¦ 198 (0xc6) - Æ 230 (0xe6) - æ
39 (0x27) - ' 71 (0x47) - G 103 (0x67) - g 135 (0x87) - ‡ 167 (0xa7) - § 199 (0xc7) - Ç 231 (0xe7) - ç
40 (0x28) - ( 72 (0x48) - H 104 (0x68) - h 136 (0x88) - ˆ 168 (0xa8) - ¨ 200 (0xc8) - È 232 (0xe8) - è
41 (0x29) - ) 73 (0x49) - I 105 (0x69) - i 137 (0x89) - ‰ 169 (0xa9) - © 201 (0xc9) - É 233 (0xe9) - é
42 (0x2a) - * 74 (0x4a) - J 106 (0x6a) - j 138 (0x8a) - Š 170 (0xaa) - ª 202 (0xca) - Ê 234 (0xea) - ê
43 (0x2b) - + 75 (0x4b) - K 107 (0x6b) - k 139 (0x8b) - ‹ 171 (0xab) - « 203 (0xcb) - Ë 235 (0xeb) - ë
44 (0x2c) - , 76 (0x4c) - L 108 (0x6c) - l 140 (0x8c) - Œ 172 (0xac) - ¬ 204 (0xcc) - Ì 236 (0xec) - ì
45 (0x2d) - - 77 (0x4d) - M 109 (0x6d) - m 141 (0x8d) - <20> 173 (0xad) - ­ 205 (0xcd) - Í 237 (0xed) - í
46 (0x2e) - . 78 (0x4e) - N 110 (0x6e) - n 142 (0x8e) - Ž 174 (0xae) - ® 206 (0xce) - Î 238 (0xee) - î
47 (0x2f) - / 79 (0x4f) - O 111 (0x6f) - o 143 (0x8f) - <20> 175 (0xaf) - ¯ 207 (0xcf) - Ï 239 (0xef) - ï
48 (0x30) - 0 80 (0x50) - P 112 (0x70) - p 144 (0x90) - <20> 176 (0xb0) - ° 208 (0xd0) - Ð 240 (0xf0) - ð
49 (0x31) - 1 81 (0x51) - Q 113 (0x71) - q 145 (0x91) - ‘ 177 (0xb1) - ± 209 (0xd1) - Ñ 241 (0xf1) - ñ
50 (0x32) - 2 82 (0x52) - R 114 (0x72) - r 146 (0x92) - ’ 178 (0xb2) - ² 210 (0xd2) - Ò 242 (0xf2) - ò
51 (0x33) - 3 83 (0x53) - S 115 (0x73) - s 147 (0x93) - “ 179 (0xb3) - ³ 211 (0xd3) - Ó 243 (0xf3) - ó
52 (0x34) - 4 84 (0x54) - T 116 (0x74) - t 148 (0x94) - ” 180 (0xb4) - ´ 212 (0xd4) - Ô 244 (0xf4) - ô
53 (0x35) - 5 85 (0x55) - U 117 (0x75) - u 149 (0x95) - • 181 (0xb5) - µ 213 (0xd5) - Õ 245 (0xf5) - õ
54 (0x36) - 6 86 (0x56) - V 118 (0x76) - v 150 (0x96) - – 182 (0xb6) - ¶ 214 (0xd6) - Ö 246 (0xf6) - ö
55 (0x37) - 7 87 (0x57) - W 119 (0x77) - w 151 (0x97) - — 183 (0xb7) - · 215 (0xd7) - × 247 (0xf7) - ÷
56 (0x38) - 8 88 (0x58) - X 120 (0x78) - x 152 (0x98) - ˜ 184 (0xb8) - ¸ 216 (0xd8) - Ø 248 (0xf8) - ø
57 (0x39) - 9 89 (0x59) - Y 121 (0x79) - y 153 (0x99) - ™ 185 (0xb9) - ¹ 217 (0xd9) - Ù 249 (0xf9) - ù
58 (0x3a) - : 90 (0x5a) - Z 122 (0x7a) - z 154 (0x9a) - 186 (0xba) - º 218 (0xda) - Ú 250 (0xfa) - ú
59 (0x3b) - ; 91 (0x5b) - [ 123 (0x7b) - { 155 (0x9b) - › 187 (0xbb) - » 219 (0xdb) - Û 251 (0xfb) - û
60 (0x3c) - < 92 (0x5c) - \ 124 (0x7c) - | 156 (0x9c) - œ 188 (0xbc) - ¼ 220 (0xdc) - Ü 252 (0xfc) - ü
61 (0x3d) - = 93 (0x5d) - ] 125 (0x7d) - } 157 (0x9d) - <20> 189 (0xbd) - ½ 221 (0xdd) - Ý 253 (0xfd) - ý
62 (0x3e) - > 94 (0x5e) - ^ 126 (0x7e) - ~ 158 (0x9e) - ž 190 (0xbe) - ¾ 222 (0xde) - Þ 254 (0xfe) - þ
63 (0x3f) - ? 95 (0x5f) - _ 127 (0x7f) - 159 (0x9f) - Ÿ 191 (0xbf) - ¿ 223 (0xdf) - ß 255 (0xff) - ÿ
*/
// this array shows position of every koi8-r symbol in font10_table
const uint8_t fontNumb8_encoding[256] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0..31
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
/*20*/1, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, // 47
/*30*/2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 29, 30, 31, 32, 33, 34, // 63
/*40*/35, 12, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 13, // 79
/*50*/49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 0, 0, 0, 0, 0, 0, // 95
/*60*/0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 111
/*70*/0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 127
/*80*/0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 143
/*90*/0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 159
/*A0*/0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 175
/*B0*/0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 191
/*C0*/0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 207
/*D0*/0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 223
/*E0*/0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 239
/*F0*/0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 255
};
const uint8_t fontNumb8_table[] = {
// 0 0x00 - empty
0,
________,
________,
________,
________,
________,
________,
________,
________,
________,
________,
// 1 0x20 - ' '
4,
________,
________,
________,
________,
________,
________,
________,
________,
________,
________,
// 2 0x30 - '0'
6,
_XXX____,
XX_XX___,
X___X___,
X___X___,
X___X___,
X___X___,
XX_XX___,
_XXX____,
________,
________,
// 3 0x31 - '1'
6,
_XX_____,
X_X_____,
__X_____,
__X_____,
__X_____,
__X_____,
__X_____,
XXXXX___,
________,
________,
// 4 0x32 - '2'
6,
_XXX____,
X___X___,
____X___,
____X___,
___X____,
__X_____,
_X______,
XXXXX___,
________,
________,
// 5 0x33 - '3'
6,
XXXX____,
____X___,
____X___,
_XXX____,
____X___,
____X___,
____X___,
XXXX____,
________,
________,
// 6 0x34 - '4'
7,
___XX___,
___XX___,
__X_X___,
_X__X___,
_X__X___,
XXXXXX__,
____X___,
____X___,
________,
________,
// 7 0x35 - '5'
5,
XXXX____,
X_______,
X_______,
XXX_____,
___X____,
___X____,
___X____,
XXX_____,
________,
________,
// 8 0x36 - '6'
6,
_XXX____,
X___X___,
X_______,
XXXX____,
X___X___,
X___X___,
X___X___,
_XXX____,
________,
________,
// 9 0x37 - '7'
5,
XXXX____,
___X____,
__X_____,
__X_____,
__X_____,
_X______,
_X______,
_X______,
________,
________,
// 10 0x38 - '8'
6,
_XXX____,
X___X___,
X___X___,
_XXX____,
X___X___,
X___X___,
X___X___,
_XXX____,
________,
________,
// 11 0x39 - '9'
6,
_XXX____,
X___X___,
X___X___,
X___X___,
_XXXX___,
____X___,
X___X___,
_XXX____,
________,
________,
// 12 0x41 - 'A'
6,
__X_____,
_X_X____,
_X_X____,
_X_X____,
X___X___,
XXXXX___,
X___X___,
X___X___,
________,
________,
// 13 0x4f - 'O'
7,
__XX____,
_X__X___,
X____X__,
X____X__,
X____X__,
X____X__,
_X__X___,
__XX____,
________,
________,
// 14 0x21 - '!'
2,
X_______,
X_______,
X_______,
X_______,
X_______,
X_______,
________,
X_______,
________,
________,
// 15 0x22 - '"'
4,
________,
X_X_____,
X_X_____,
X_X_____,
________,
________,
________,
________,
________,
________,
// 16 0x23 - '#'
7,
________,
____X_X_,
___X_X__,
XXXXXXX_,
__X_X___,
XXXXXXX_,
_X_X____,
X_X_____,
________,
________,
// 17 0x24 - '$'
6,
__X_____,
_XXX____,
X_X_X___,
X_X_____,
_XXX____,
__X_X___,
X_X_X___,
XXXX____,
__X_____,
________,
// 18 0x25 - '%'
8,
________,
_XX___X_,
X__X_X__,
_XX_X___,
___X____,
__X_XX__,
_X_X__X_,
X___XX__,
________,
________,
// 19 0x26 - '&'
7,
________,
_X______,
X_X_____,
X_X_____,
_X__XX__,
X_XXX___,
X__X____,
_XX_XX__,
________,
________,
// 20 0x27 - '''
2,
________,
X_______,
X_______,
X_______,
________,
________,
________,
________,
________,
________,
// 21 0x28 - '('
4,
__XX____,
_X______,
X_______,
X_______,
X_______,
X_______,
X_______,
_X______,
__XX____,
________,
// 22 0x29 - ')'
4,
XX______,
__X_____,
___X____,
___X____,
___X____,
___X____,
___X____,
__X_____,
XX______,
________,
// 23 0x2A - '*'
6,
________,
________,
__X_____,
XXXXX___,
_XXX____,
X___X___,
________,
________,
________,
________,
// 24 0x2B - '+'
6,
________,
________,
__X_____,
__X_____,
XXXXX___,
__X_____,
__X_____,
________,
________,
________,
// 25 0x2C - ','
3,
________,
________,
________,
________,
________,
________,
XX______,
_X______,
X_______,
________,
// 26 0x2D - '-'
6,
________,
________,
________,
________,
XXXXX___,
________,
________,
________,
________,
________,
// 27 0x2E - '.'
3,
________,
________,
________,
________,
________,
________,
XX______,
XX______,
________,
________,
// 28 0x2F - '/'
6,
____X___,
___X____,
___X____,
__X_____,
__X_____,
_X______,
_X______,
_X______,
X_______,
________,
// 29 0x3A - ':'
3,
________,
________,
XX______,
XX______,
________,
XX______,
XX______,
________,
________,
________,
// 30 0x3B - ';'
3,
________,
________,
________,
XX______,
XX______,
________,
XX______,
_X______,
X_______,
________,
// 31 0x3C - '<'
4,
________,
________,
__X_____,
_X______,
X_______,
_X______,
__X_____,
________,
________,
________,
// 32 0x3D - '='
5,
________,
________,
________,
XXXX____,
________,
XXXX____,
________,
________,
________,
________,
// 33 0x3E - '>'
4,
________,
________,
X_______,
_X______,
__X_____,
_X______,
X_______,
________,
________,
________,
// 34 0x3F - '?'
5,
_XX_____,
X__X____,
___X____,
__X_____,
_X______,
_X______,
________,
_X______,
________,
________,
// 35 0x40 - '@'
8,
___XXX__,
__X__X__,
_X_XXXX_,
X__X_XX_,
X_X_X_X_,
X_X_X_X_,
X__X_X__,
_X______,
__XXXX__,
________,
// 36 0x42 - 'B'
6,
XXX_____,
X__X____,
X_X_____,
XXXX____,
X___X___,
X___X___,
X___X___,
XXXX____,
________,
________,
// 37 0x43 - 'C'
7,
__XXX___,
_X___X__,
X_______,
X_______,
X_______,
X_______,
_X___X__,
__XXX___,
________,
________,
// 38 0x44 - 'D'
6,
XXX_____,
X__X____,
X___X___,
X___X___,
X___X___,
X___X___,
X__X____,
XXX_____,
________,
________,
// 39 0x45 - 'E'
6,
XXXXX___,
X_______,
X_______,
XXX_____,
X_______,
X_______,
X___X___,
XXXXX___,
________,
________,
// 40 0x46 - 'F'
6,
XXXXX___,
X___X___,
X_______,
X_______,
XXX_____,
X_______,
X_______,
X_______,
________,
________,
// 41 0x47 - 'G'
7,
__XXX___,
_X___X__,
X_______,
X_______,
X_______,
X__XXX__,
_X___X__,
__XXX___,
________,
________,
// 42 0x48 - 'H'
6,
X___X___,
X___X___,
X___X___,
XXXXX___,
X___X___,
X___X___,
X___X___,
X___X___,
________,
________,
// 43 0x49 - 'I'
4,
XXX_____,
_X______,
_X______,
_X______,
_X______,
_X______,
_X______,
XXX_____,
________,
________,
// 44 0x4A - 'J'
5,
XXXX____,
X__X____,
___X____,
___X____,
___X____,
___X____,
X_XX____,
_X______,
________,
________,
// 45 0x4B - 'K'
6,
X___X___,
X__X____,
X_X_____,
XXX_____,
X__X____,
X__X____,
X___X___,
X___X___,
________,
________,
// 46 0x4C - 'L'
6,
X_______,
X_______,
X_______,
X_______,
X_______,
X_______,
X___X___,
XXXXX___,
________,
________,
// 47 0x4D - 'M'
8,
X_____X_,
XX___XX_,
X_X_X_X_,
X_X_X_X_,
X__X__X_,
X_____X_,
X_____X_,
X_____X_,
________,
________,
// 48 0x4E - 'N'
6,
X___X___,
XX__X___,
XX__X___,
X_X_X___,
X_X_X___,
X__XX___,
X__XX___,
X___X___,
________,
________,
// 49 0x50 - 'P'
6,
XXXX____,
X__XX___,
X___X___,
X__XX___,
XXXX____,
X_______,
X_______,
X_______,
________,
________,
// 50 0x51 - 'Q'
7,
__XX____,
_X__X___,
X____X__,
X____X__,
X____X__,
X____X__,
_X_XX___,
__XX____,
___XXX__,
________,
// 51 0x52 - 'R'
6,
XXXX____,
X__XX___,
X___X___,
X__XX___,
XXXX____,
X_X_____,
X__X____,
X__XX___,
________,
________,
// 52 0x53 - 'S'
6,
_XX_____,
X__X____,
X_______,
_XX_____,
__XX____,
____X___,
XX_XX___,
_XXX____,
________,
________,
// 53 0x54 - 'T'
6,
XXXXX___,
__X_____,
__X_____,
__X_____,
__X_____,
__X_____,
__X_____,
__X_____,
________,
________,
// 54 0x55 - 'U'
7,
X____X__,
X____X__,
X____X__,
X____X__,
X____X__,
X____X__,
_X__X___,
__XX____,
________,
________,
// 55 0x56 - 'V'
6,
X___X___,
X___X___,
X___X___,
X___X___,
X___X___,
_X_X____,
_X_X____,
__X_____,
________,
________,
// 56 0x57 - 'W'
8,
X_____X_,
X_____X_,
X_____X_,
X__X__X_,
X__X__X_,
_X_X_X__,
_X_X_X__,
__X_X___,
________,
________,
// 57 0x58 - 'X'
6,
X___X___,
X___X___,
_X_X____,
_X_X____,
__X_____,
_X_X____,
X___X___,
X___X___,
________,
________,
// 58 0x59 - 'Y'
6,
X___X___,
X___X___,
X___X___,
_X_X____,
_XXX____,
__X_____,
__X_____,
__X_____,
________,
________,
// 59 0x5A - 'Z'
6,
XXXXX___,
____X___,
___X____,
__X_____,
__X_____,
_X______,
X_______,
XXXXX___,
________,
________,
};
#if 0
// 14 0x21 - '!'
0,
________,
________,
________,
________,
________,
________,
________,
________,
________,
________,
________,
#endif

View File

@@ -0,0 +1,329 @@
/*
* This file is part of the TETRIS project.
* Copyright 2019 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 <stddef.h>
#include "debug.h"
#include "fonts.h"
/* Bash-script to generate the symbols
#!/bin/bash
function bits(){
Ans=""
for x in $(seq 7 -1 0); do
B=$((1<<$x))
if [ $(($1&$B)) -ne 0 ]; then Ans="${Ans}X"
else Ans="${Ans}_"
fi
done
echo $Ans
}
for x in $(seq 0 255); do
printf "#define $(bits $x)\t0x%02x\n" $x
done
*/
#define ________ 0x00
#define _______X 0x01
#define ______X_ 0x02
#define ______XX 0x03
#define _____X__ 0x04
#define _____X_X 0x05
#define _____XX_ 0x06
#define _____XXX 0x07
#define ____X___ 0x08
#define ____X__X 0x09
#define ____X_X_ 0x0a
#define ____X_XX 0x0b
#define ____XX__ 0x0c
#define ____XX_X 0x0d
#define ____XXX_ 0x0e
#define ____XXXX 0x0f
#define ___X____ 0x10
#define ___X___X 0x11
#define ___X__X_ 0x12
#define ___X__XX 0x13
#define ___X_X__ 0x14
#define ___X_X_X 0x15
#define ___X_XX_ 0x16
#define ___X_XXX 0x17
#define ___XX___ 0x18
#define ___XX__X 0x19
#define ___XX_X_ 0x1a
#define ___XX_XX 0x1b
#define ___XXX__ 0x1c
#define ___XXX_X 0x1d
#define ___XXXX_ 0x1e
#define ___XXXXX 0x1f
#define __X_____ 0x20
#define __X____X 0x21
#define __X___X_ 0x22
#define __X___XX 0x23
#define __X__X__ 0x24
#define __X__X_X 0x25
#define __X__XX_ 0x26
#define __X__XXX 0x27
#define __X_X___ 0x28
#define __X_X__X 0x29
#define __X_X_X_ 0x2a
#define __X_X_XX 0x2b
#define __X_XX__ 0x2c
#define __X_XX_X 0x2d
#define __X_XXX_ 0x2e
#define __X_XXXX 0x2f
#define __XX____ 0x30
#define __XX___X 0x31
#define __XX__X_ 0x32
#define __XX__XX 0x33
#define __XX_X__ 0x34
#define __XX_X_X 0x35
#define __XX_XX_ 0x36
#define __XX_XXX 0x37
#define __XXX___ 0x38
#define __XXX__X 0x39
#define __XXX_X_ 0x3a
#define __XXX_XX 0x3b
#define __XXXX__ 0x3c
#define __XXXX_X 0x3d
#define __XXXXX_ 0x3e
#define __XXXXXX 0x3f
#define _X______ 0x40
#define _X_____X 0x41
#define _X____X_ 0x42
#define _X____XX 0x43
#define _X___X__ 0x44
#define _X___X_X 0x45
#define _X___XX_ 0x46
#define _X___XXX 0x47
#define _X__X___ 0x48
#define _X__X__X 0x49
#define _X__X_X_ 0x4a
#define _X__X_XX 0x4b
#define _X__XX__ 0x4c
#define _X__XX_X 0x4d
#define _X__XXX_ 0x4e
#define _X__XXXX 0x4f
#define _X_X____ 0x50
#define _X_X___X 0x51
#define _X_X__X_ 0x52
#define _X_X__XX 0x53
#define _X_X_X__ 0x54
#define _X_X_X_X 0x55
#define _X_X_XX_ 0x56
#define _X_X_XXX 0x57
#define _X_XX___ 0x58
#define _X_XX__X 0x59
#define _X_XX_X_ 0x5a
#define _X_XX_XX 0x5b
#define _X_XXX__ 0x5c
#define _X_XXX_X 0x5d
#define _X_XXXX_ 0x5e
#define _X_XXXXX 0x5f
#define _XX_____ 0x60
#define _XX____X 0x61
#define _XX___X_ 0x62
#define _XX___XX 0x63
#define _XX__X__ 0x64
#define _XX__X_X 0x65
#define _XX__XX_ 0x66
#define _XX__XXX 0x67
#define _XX_X___ 0x68
#define _XX_X__X 0x69
#define _XX_X_X_ 0x6a
#define _XX_X_XX 0x6b
#define _XX_XX__ 0x6c
#define _XX_XX_X 0x6d
#define _XX_XXX_ 0x6e
#define _XX_XXXX 0x6f
#define _XXX____ 0x70
#define _XXX___X 0x71
#define _XXX__X_ 0x72
#define _XXX__XX 0x73
#define _XXX_X__ 0x74
#define _XXX_X_X 0x75
#define _XXX_XX_ 0x76
#define _XXX_XXX 0x77
#define _XXXX___ 0x78
#define _XXXX__X 0x79
#define _XXXX_X_ 0x7a
#define _XXXX_XX 0x7b
#define _XXXXX__ 0x7c
#define _XXXXX_X 0x7d
#define _XXXXXX_ 0x7e
#define _XXXXXXX 0x7f
#define X_______ 0x80
#define X______X 0x81
#define X_____X_ 0x82
#define X_____XX 0x83
#define X____X__ 0x84
#define X____X_X 0x85
#define X____XX_ 0x86
#define X____XXX 0x87
#define X___X___ 0x88
#define X___X__X 0x89
#define X___X_X_ 0x8a
#define X___X_XX 0x8b
#define X___XX__ 0x8c
#define X___XX_X 0x8d
#define X___XXX_ 0x8e
#define X___XXXX 0x8f
#define X__X____ 0x90
#define X__X___X 0x91
#define X__X__X_ 0x92
#define X__X__XX 0x93
#define X__X_X__ 0x94
#define X__X_X_X 0x95
#define X__X_XX_ 0x96
#define X__X_XXX 0x97
#define X__XX___ 0x98
#define X__XX__X 0x99
#define X__XX_X_ 0x9a
#define X__XX_XX 0x9b
#define X__XXX__ 0x9c
#define X__XXX_X 0x9d
#define X__XXXX_ 0x9e
#define X__XXXXX 0x9f
#define X_X_____ 0xa0
#define X_X____X 0xa1
#define X_X___X_ 0xa2
#define X_X___XX 0xa3
#define X_X__X__ 0xa4
#define X_X__X_X 0xa5
#define X_X__XX_ 0xa6
#define X_X__XXX 0xa7
#define X_X_X___ 0xa8
#define X_X_X__X 0xa9
#define X_X_X_X_ 0xaa
#define X_X_X_XX 0xab
#define X_X_XX__ 0xac
#define X_X_XX_X 0xad
#define X_X_XXX_ 0xae
#define X_X_XXXX 0xaf
#define X_XX____ 0xb0
#define X_XX___X 0xb1
#define X_XX__X_ 0xb2
#define X_XX__XX 0xb3
#define X_XX_X__ 0xb4
#define X_XX_X_X 0xb5
#define X_XX_XX_ 0xb6
#define X_XX_XXX 0xb7
#define X_XXX___ 0xb8
#define X_XXX__X 0xb9
#define X_XXX_X_ 0xba
#define X_XXX_XX 0xbb
#define X_XXXX__ 0xbc
#define X_XXXX_X 0xbd
#define X_XXXXX_ 0xbe
#define X_XXXXXX 0xbf
#define XX______ 0xc0
#define XX_____X 0xc1
#define XX____X_ 0xc2
#define XX____XX 0xc3
#define XX___X__ 0xc4
#define XX___X_X 0xc5
#define XX___XX_ 0xc6
#define XX___XXX 0xc7
#define XX__X___ 0xc8
#define XX__X__X 0xc9
#define XX__X_X_ 0xca
#define XX__X_XX 0xcb
#define XX__XX__ 0xcc
#define XX__XX_X 0xcd
#define XX__XXX_ 0xce
#define XX__XXXX 0xcf
#define XX_X____ 0xd0
#define XX_X___X 0xd1
#define XX_X__X_ 0xd2
#define XX_X__XX 0xd3
#define XX_X_X__ 0xd4
#define XX_X_X_X 0xd5
#define XX_X_XX_ 0xd6
#define XX_X_XXX 0xd7
#define XX_XX___ 0xd8
#define XX_XX__X 0xd9
#define XX_XX_X_ 0xda
#define XX_XX_XX 0xdb
#define XX_XXX__ 0xdc
#define XX_XXX_X 0xdd
#define XX_XXXX_ 0xde
#define XX_XXXXX 0xdf
#define XXX_____ 0xe0
#define XXX____X 0xe1
#define XXX___X_ 0xe2
#define XXX___XX 0xe3
#define XXX__X__ 0xe4
#define XXX__X_X 0xe5
#define XXX__XX_ 0xe6
#define XXX__XXX 0xe7
#define XXX_X___ 0xe8
#define XXX_X__X 0xe9
#define XXX_X_X_ 0xea
#define XXX_X_XX 0xeb
#define XXX_XX__ 0xec
#define XXX_XX_X 0xed
#define XXX_XXX_ 0xee
#define XXX_XXXX 0xef
#define XXXX____ 0xf0
#define XXXX___X 0xf1
#define XXXX__X_ 0xf2
#define XXXX__XX 0xf3
#define XXXX_X__ 0xf4
#define XXXX_X_X 0xf5
#define XXXX_XX_ 0xf6
#define XXXX_XXX 0xf7
#define XXXXX___ 0xf8
#define XXXXX__X 0xf9
#define XXXXX_X_ 0xfa
#define XXXXX_XX 0xfb
#define XXXXXX__ 0xfc
#define XXXXXX_X 0xfd
#define XXXXXXX_ 0xfe
#define XXXXXXXX 0xff
// here are fonts themself
#include "font14.h"
//#include "fontNumb16.h"
//#include "fontNumb10.h"
#include "fontNumb8.h"
static const afont FONTS[] = {
[FONT14] = {font14_table, font14_encoding, FONT14HEIGHT, FONT14BYTES, FONT14BASELINE},
[FONTN8] = {fontNumb8_table, fontNumb8_encoding, FONTNUMB8HEIGHT, FONTNUMB8BYTES, FONTNUMB8BASELINE},
};
const afont *curfont = &FONTS[FONT14];
/**
* @brief choose_font - font selector
* @param newfont - font to choose
* @return 0 if all OK
*/
int choose_font(font_t newfont){
if(newfont >= FONT_T_MAX || newfont <= FONT_T_MIN) return 1;
curfont = &FONTS[newfont];
return 0;
}
const uint8_t *font_char(uint8_t Char){
uint8_t idx = curfont->enctable[Char];
//DBG("font_char("); DBGU(Char); DBG(")="); DBGU(idx); NL();
if(!idx) return NULL; // no this character in font
return &(curfont->font[idx*(curfont->bytes+1)]);
}

View File

@@ -0,0 +1,48 @@
/*
* This file is part of the TETRIS project.
* Copyright 2019 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef FONTS_H__
#define FONTS_H__
#include <stdint.h>
// type for font choosing
typedef enum{
FONT_T_MIN = -1, // no fonts <= this
FONT14, // 16x16, font height near 14px
// FONTN16, // numbers 16x8, font height 16px
// FONTN10, // numbers 10x8, font height 10px
FONTN8, // numbers and 'A'/'O', height 8px
FONT_T_MAX // no fonts >= this
} font_t;
int choose_font(font_t newfont);
const uint8_t *font_char(uint8_t Char);
typedef struct{
const uint8_t *font; // font inself
const uint8_t *enctable; // font encoding table
uint8_t height; // full font matrix height
uint8_t bytes; // amount of bytes in font matrix
uint8_t baseline; // baseline position (coordinate from bottom line)
} afont;
extern const afont *curfont;
#endif // FONTS_H__

View File

@@ -0,0 +1,175 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hardware.h"
#include "usb.h"
uint8_t transfer_done = 0; // ==1 when DMA transfer ready
// buffer for DMA
static uint32_t dmabuf[SCREEN_WIDTH];
void iwdg_setup(){
uint32_t tmout = 16000000;
/* Enable the peripheral clock RTC */
/* (1) Enable the LSI (40kHz) */
/* (2) Wait while it is not ready */
RCC->CSR |= RCC_CSR_LSION; /* (1) */
while((RCC->CSR & RCC_CSR_LSIRDY) != RCC_CSR_LSIRDY){if(--tmout == 0) break;} /* (2) */
/* Configure IWDG */
/* (1) Activate IWDG (not needed if done in option bytes) */
/* (2) Enable write access to IWDG registers */
/* (3) Set prescaler by 64 (1.6ms for each tick) */
/* (4) Set reload value to have a rollover each 2s */
/* (5) Check if flags are reset */
/* (6) Refresh counter */
IWDG->KR = IWDG_START; /* (1) */
IWDG->KR = IWDG_WRITE_ACCESS; /* (2) */
IWDG->PR = IWDG_PR_PR_1; /* (3) */
IWDG->RLR = 1250; /* (4) */
tmout = 16000000;
while(IWDG->SR){if(--tmout == 0) break;} /* (5) */
IWDG->KR = IWDG_REFRESH; /* (6) */
}
static inline void gpio_setup(){
// Enable clocks to the GPIO subsystems, turn on AFIO clocking to disable SWD/JTAG
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPBEN | RCC_APB2ENR_IOPCEN | RCC_APB2ENR_AFIOEN;
// turn off JTAG (PB3/4 is in use)
AFIO->MAPR = AFIO_MAPR_SWJ_CFG_JTAGDISABLE;
// turn off USB pullup
USBPU_OFF();
// Set led as opendrain output
GPIOC->CRH = CRH(13, CNF_ODOUTPUT|MODE_SLOW);
// SCREEN color PINs: PA0..PA5
GPIOA->CRL = CRL(0, CNF_PPOUTPUT|MODE_FAST) | CRL(1, CNF_PPOUTPUT|MODE_FAST) | CRL(2, CNF_PPOUTPUT|MODE_FAST) |
CRL(3, CNF_PPOUTPUT|MODE_FAST) | CRL(4, CNF_PPOUTPUT|MODE_FAST) | CRL(5, CNF_PPOUTPUT|MODE_FAST);
// USB pullup - opendrain output
GPIOA->CRH = CRH(15, CNF_PPOUTPUT|MODE_SLOW);
// A..D, LAT
GPIOB->CRL = CRL(4, CNF_PPOUTPUT|MODE_FAST) | CRL(5, CNF_PPOUTPUT|MODE_FAST) | CRL(6, CNF_PPOUTPUT|MODE_FAST) | CRL(7, CNF_PPOUTPUT|MODE_FAST);
// nOE: PB4..PB9; Joystick: PB10..PB15 (pullup input)
GPIOB->ODR = 0b111111 << 10; // pullup
GPIOB->CRH = CRH(8, CNF_PPOUTPUT|MODE_FAST) | CRH(9, CNF_PPOUTPUT|MODE_FAST) |
CRH(10, CNF_PUDINPUT|MODE_INPUT) | CRH(11, CNF_PUDINPUT|MODE_INPUT) | CRH(12, CNF_PUDINPUT|MODE_INPUT) |
CRH(13, CNF_PUDINPUT|MODE_INPUT) | CRH(14, CNF_PUDINPUT|MODE_INPUT) | CRH(15, CNF_PUDINPUT|MODE_INPUT);
}
// setup timer3 for DMA transfers & SCK @ TIM3_CH1 (PA6)
static inline void tim_setup(){
SCRN_DISBL(); // turn off output
GPIOA->CRL |= CRL(6, CNF_AFPP|MODE_FAST);
RCC->APB1ENR |= RCC_APB1ENR_TIM3EN;
// PCS=1 don't work;
TIM3->PSC = 4; // 7.2MHz
TIM3->ARR = 7;
TIM3->CCMR1 = TIM_CCMR1_OC1M; // PWM mode 2 (inactive->active)
//TIM3->CCMR1 = TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1; // PWM mode 1 (active->inactive)
TIM3->CCER = TIM_CCER_CC1E; // output 1 enable
TIM3->DIER = TIM_DIER_UDE; // enable DMA requests
RCC->AHBENR |= RCC_AHBENR_DMA1EN;
// memsize 32bit, periphsize 32bit, memincr, mem2periph, full transfer interrupt
DMA1_Channel3->CCR = DMA_CCR_PSIZE_1 | DMA_CCR_MSIZE_1 | DMA_CCR_MINC | DMA_CCR_DIR | DMA_CCR_TCIE;
DMA1_Channel3->CMAR = (uint32_t)dmabuf;
DMA1_Channel3->CPAR = (uint32_t)&GPIOA->BSRR;
NVIC_EnableIRQ(DMA1_Channel3_IRQn);
}
void hw_setup(){
gpio_setup();
tim_setup();
}
void stopTIMDMA(){
DMA1_Channel3->CCR &= ~DMA_CCR_EN; // stop DMA
TIM3->CR1 = 0; // turn off timer
}
static inline uint8_t getcolrvals(uint8_t colr, uint8_t Ntick){
uint8_t result = 0; // bits: 0-R, 1-G, 2-B
#ifdef SCREEN_IS_NEGATIVE
if(colr >> 5 <= Ntick) result = 1;
colr &= 0x1f;
if(colr >> 2 <= Ntick) result |= 2;
colr &= 3;
if(colr) colr = (colr << 1) + 1;
if(colr <= Ntick) result |= 4;
#else
if(colr >> 5 > Ntick) result = 1;
colr &= 0x1f;
if(colr >> 2 > Ntick) result |= 2;
colr &= 3;
if(colr) colr = (colr << 1) + 1;
if(colr > Ntick) result |= 4;
#endif
return result;
}
/**
* @brief ConvertScreenBuf - convert creen buffer into DMA buffer
* @param sbuf - screen buffer
* @param Nrow - current row number
* @param Ntick - tick number (0..7) for quasi-PWM colors
*/
void ConvertScreenBuf(uint8_t *sbuf, uint8_t Nrow, uint8_t Ntick){ // __attribute__((unused))
//USB_send("ConvertScreenBuf\n");
uint8_t *_1st = &sbuf[SCREEN_WIDTH*Nrow], *_2nd = _1st + SCREEN_WIDTH*NBLOCKS; // first and second lines
for(int i = 0; i < SCREEN_WIDTH; ++i){ // ~50us for 64 pixels
uint8_t pinsset = getcolrvals(_1st[i], Ntick);
pinsset |= getcolrvals(_2nd[i], Ntick) << 3;
//dmabuf[i] = (i%2) ? ((COLR_pin<<16) | i) : (0b100010);
dmabuf[i] = (COLR_pin << 16) | pinsset; // All BR are 1, BS depending on color
}
}
static uint8_t blknum_curr = 0;
/**
* @brief TIM_DMA_transfer - start DMA transfer
* @param buf - buffer with data for GPIOA->BSRR
* @param blknum - number of active block
*/
void TIM_DMA_transfer(uint8_t blknum){
//USB_send("TIM_DMA_transfer\n");
TIM3->CR1 = 0; // turn off timer
transfer_done = 0;
// set first pixel color
//COLR_port->BSRR = dmabuf[0];
DMA1_Channel3->CNDTR = SCREEN_WIDTH;
DMA1_Channel3->CCR |= DMA_CCR_EN; // start DMA
TIM3->CCR1 = 4; // 50% PWM
TIM3->CR1 = TIM_CR1_CEN; // turn on timer
blknum_curr = blknum;
}
// DMA transfer complete - stop transfer
void dma1_channel3_isr(){
//TIM3->CR1 |= TIM_CR1_OPM; // set one pulse mode to turn off timer after last CLK pulse
//TIM3->SR = 0;
TIM3->CR1 = 0;
DMA1_Channel3->CCR &= ~DMA_CCR_EN; // stop DMA
//while(!(TIM3->SR & TIM_SR_UIF)); // wait for last pulse
SCRN_DISBL(); // clear main output
ADDR_port->ODR = (ADDR_port->ODR & ~(ADDR_pin)) | (blknum_curr << ADDR_roll); // set address
SET(LAT); // activate latch
DMA1->IFCR = DMA_IFCR_CGIF3;
transfer_done = 1;
CLEAR(LAT);
SCRN_ENBL(); // activate main output
process_screen();
//USB_send("transfer done\n");
}

View File

@@ -0,0 +1,100 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __HARDWARE_H__
#define __HARDWARE_H__
#include "stm32f1.h"
#include "screen.h"
// define this if screen colors are negative
// #define SCREEN_IS_NEGATIVE
// define if nOE is negative
#define NOE_IS_NEGATIVE
// LED0 - PC13 (bluepill), blinking each second
#define LED0_port GPIOC
#define LED0_pin (1<<13)
// USB pullup (not present in bluepill) - PA15
#define USBPU_port GPIOA
#define USBPU_pin (1<<15)
#define USBPU_ON() pin_set(USBPU_port, USBPU_pin)
#define USBPU_OFF() pin_clear(USBPU_port, USBPU_pin)
#define LED_blink(x) pin_toggle(x ## _port, x ## _pin)
#define LED_on(x) pin_clear(x ## _port, x ## _pin)
#define LED_off(x) pin_set(x ## _port, x ## _pin)
// SPI DMA channel
#define DMA_SPI_Channel DMA1_Channel3
// SCREEN PINs: A,B,C,D - PB6-PB9; LAT - PB5; nOE - PB4
// CLK - PA6 (TIM3_CH1)
// colors: PA0..PA5
#define COLR_port GPIOA
#define COLR_pin (0x3f)
#define ADDR_port GPIOB
#define ADDR_roll (6)
#define ADDR_pin (0xf<<ADDR_roll)
#define LAT_port GPIOB
#define LAT_pin (1<<5)
#define nOE_port GPIOB
#define nOE_pin (1<<4)
#define SET(x) pin_set(x ## _port, x ## _pin)
#define CLEAR(x) pin_clear(x ## _port, x ## _pin)
#define TOGGLE(x) pin_toggle(x ## _port, x ## _pin)
// #define BUTTONS_NEGATIVE to negate buttons (pressed @1, not @0)
// joystick: PB10..PB15
#define JDOWN_port GPIOB
#define JDOWN_pin (1<<10)
#define JUP_port GPIOB
#define JUP_pin (1<<11)
#define JRIGHT_port GPIOB
#define JRIGHT_pin (1<<12)
#define JLEFT_port GPIOB
#define JLEFT_pin (1<<13)
#define JMENU_port GPIOB
#define JMENU_pin (1<<14)
#define JENTER_port GPIOB
#define JENTER_pin (1<<15)
#ifdef BUTTONS_NEGATIVE
#define PRESSED(port, pin) ((port->IDR & pin) == pin)
#else
#define PRESSED(port, pin) ((port->IDR & pin) == 0)
#endif
#ifdef NOE_IS_NEGATIVE
#define SCRN_ENBL() SET(nOE)
#define SCRN_DISBL() CLEAR(nOE)
#else
#define SCRN_ENBL() CLEAR(nOE)
#define SCRN_DISBL() SET(nOE)
#endif
void iwdg_setup();
void hw_setup();
void TIM_DMA_transfer(uint8_t blknum);
void stopTIMDMA();
void ConvertScreenBuf(uint8_t *sbuf, uint8_t Nrow, uint8_t Ntick);
extern uint8_t transfer_done;
#endif // __HARDWARE_H__

View File

@@ -0,0 +1,68 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "adcrandom.h"
#include "fonts.h"
#include "hardware.h"
#include "proto.h"
#include "screen.h"
#include "usb.h"
#include "usb_lib.h"
volatile uint32_t Tms = 0;
/* Called when systick fires */
void sys_tick_handler(){
++Tms;
}
int main(){
uint32_t lastT = 0;
sysreset();
StartHSE();
SysTick_Config(72000);
RCC->CSR |= RCC_CSR_RMVF; // remove reset flags
hw_setup();
USBPU_OFF();
adc_setup();
USB_setup();
//iwdg_setup();
USBPU_ON();
setBGcolor(COLOR_BLACK);
setFGcolor(COLOR_WHITE);
choose_font(FONTN8);
ClearScreen();
ScreenON();
while(1){
if(Tms - lastT > 499){
LED_blink(LED0);
lastT = Tms;
}
IWDG->KR = IWDG_REFRESH;
usb_proc();
proto_process();
IWDG->KR = IWDG_REFRESH;
}
return 0;
}

BIN
F1:F103/TwoPanelScreen/panels.bin Executable file

Binary file not shown.

View File

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

View File

@@ -0,0 +1,2 @@
// Add predefined macros for your project here. For example:
// #define THE_ANSWER 42

View File

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

View File

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

View File

@@ -0,0 +1,19 @@
adcrandom.c
adcrandom.h
debug.h
font14.h
fontNumb8.h
fonts.c
fonts.h
hardware.c
hardware.h
main.c
proto.c
proto.h
screen.c
screen.h
usb.c
usb.h
usb_defs.h
usb_lib.c
usb_lib.h

View File

View File

@@ -0,0 +1,441 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include "adcrandom.h"
#include "fonts.h"
#include "proto.h"
#include "screen.h"
#include "usb.h"
#include "version.inc"
#define USBBUFSZ (127)
#define SCROLL_STEP_MS (50) // ÍÓ ÍÅÖÄÕ ÓÄ×ÉÇÁÍÉ ÎÁ 1 ÐÉËÓÅÌØ
#define TEXTBUF_SZ (256)
extern uint32_t Tms;
// scrolling/still
static char text_buf[TEXTBUF_SZ] = {0};
static uint16_t text_scroll = 0; // scrolling amount in pixels
static uint8_t text_mode = 0; // 0 - one string, 1 - two strings
static uint8_t display_mode = 0; // 0 - text, 1 - pixels blob
static uint8_t text_fg = COLOR_WHITE;
static uint8_t text_bg = COLOR_BLACK;
static uint32_t Tlast_scroll = 0;
static uint8_t text_needs_redraw = 1;
// blob receiving
static int32_t blob_remaining = 0;
static uint8_t *blob_ptr = NULL;
// received string
static char usb_line[USBBUFSZ + 1];
static int usb_line_len = 0;
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;
}
// split long text into two lines in two-line display mode
static void split_two_lines(char *l1, uint32_t n1, char *l2, uint32_t n2){
int len = strlen(text_buf);
int split = len / 2;
for(int i = 0; i < len; ++i){
if(text_buf[i] == ' '){
char tmp[TEXTBUF_SZ];
int tlen = i;
if(tlen > (int)sizeof(tmp)-1) tlen = sizeof(tmp)-1;
memcpy(tmp, text_buf, tlen);
tmp[tlen] = 0;
if(strpixlen(tmp) <= SCREEN_WIDTH) split = i;
else break;
}
}
int n = split;
if(n > (int)n1 - 1) n = n1 - 1;
memcpy(l1, text_buf, n);
l1[n] = 0;
const char *rest = text_buf + split;
while(*rest == ' ') ++rest;
strncpy(l2, rest, n2 - 1);
l2[n2 - 1] = 0;
}
static int max_line_width(){
if(text_mode == 0) return strpixlen(text_buf);
char l1[TEXTBUF_SZ], l2[TEXTBUF_SZ];
split_two_lines(l1, sizeof(l1), l2, sizeof(l2));
int w1 = strpixlen(l1), w2 = strpixlen(l2);
return (w1 > w2) ? w1 : w2;
}
static void render_text(){
if(display_mode != 0) return;
if(!text_buf[0]) return;
for(int i = 0; i < SCREENBUF_SZ; ++i) screenbuf[i] = text_bg;
setFGcolor(text_fg);
int charH = curfont->height;
int base_off = charH - curfont->baseline - 1; // Y-ËÏÏÒÄÉÎÁÔÁ ÂÁÚÏ×ÏÊ ÌÉÎÉÉ ÐÒÉ top=0
if(text_mode == 0){
int top = (SCREEN_HEIGHT - charH) / 2;
if(top < 0) top = 0;
PutStringAt(-(int)text_scroll, top + base_off, text_buf);
}else{
char l1[TEXTBUF_SZ], l2[TEXTBUF_SZ];
split_two_lines(l1, sizeof(l1), l2, sizeof(l2));
int total = charH * 2;
int top = (SCREEN_HEIGHT - total) / 2;
if(top < 0) top = 0;
PutStringAt(-(int)text_scroll, top + base_off, l1);
PutStringAt(-(int)text_scroll, top + charH + base_off, l2);
}
}
static void update_scroll(void){
if(display_mode != 0) return;
if(!text_buf[0]) return;
int tw = max_line_width();
if(tw <= SCREEN_WIDTH){
if(text_scroll){
text_scroll = 0;
text_needs_redraw = 1;
}
return;
}
if(Tms - Tlast_scroll < SCROLL_STEP_MS) return;
Tlast_scroll = Tms;
if(++text_scroll > (uint16_t)tw) text_scroll = 0;
text_needs_redraw = 1;
}
const char* helpmsg =
"https://github.com/eddyem/stm32samples/tree/master/F1:F103/TwoPanelScreen "
#ifdef EBUG
"debug "
#else
"release "
#endif
"build #" BUILD_NUMBER " @ " BUILD_DATE
"'0/1' - screen off/on\n"
"'A' - get ADC values\n"
"'B <color>' - set background color\n"
"'C <color>' - clear screen with given color\n"
"'F <color>' - set text color\n"
"'f' - get FPS\n"
"'G' - get 100 random numbers\n"
"'L <0|1>' - single/double line text mode\n"
"'P' - receive 128x32 pixel blob (4096 bytes RRRGGGBB)\n"
"'R' - software reset\n"
"'S <0|1>' - font size: 0=small(10px), 1=big(16px)\n"
"'T <text>' - set display text\n"
;
static const char *parse_cmd(const char *buf){
uint32_t N;
char cmd = buf[0];
const char *arg = buf + 1;
while(*arg == ' ') ++arg;
switch(cmd){
case '0':
ScreenOFF();
return "OFF\n";
case '1':
ScreenON();
if(display_mode == 0) text_needs_redraw = 1;
return "ON\n";
case 'A':
USB_send("Tsens="); USB_send(u2str(getADCval(0)));
USB_send("\nVref="); USB_send(u2str(getADCval(1)));
USB_send("\nRand="); USB_send(u2str(getRand()));
USB_send("\n");
return NULL;
case 'B':
if(getnum(arg, &N) && N <= 0xff){
text_bg = N & 0xff;
setBGcolor(text_bg);
text_needs_redraw = 1;
return "BG color set\n";
}
return "Wrong color\n";
case 'C':
if(getnum(arg, &N)){
ScreenOFF();
setBGcolor(N & 0xff);
ClearScreen();
ScreenON();
display_mode = 0;
text_needs_redraw = 0;
return "Screen cleared\n";
}
return "Wrong color\n";
case 'F':
if(getnum(arg, &N)){
text_fg = N & 0xff;
setFGcolor(text_fg);
text_needs_redraw = 1;
return "FG color set\n";
}
return "Wrong color\n";
case 'f':
if(SCREEN_RELAX == getScreenState()) return "Screen is inactive\n";
USB_send("FPS="); USB_send(u2str(getFPS())); USB_send("\n");
return NULL;
case 'G':
for(int i = 0; i < 100; ++i){
USB_send(u2str(getRand()));
USB_send("\n");
}
return NULL;
case 'L':
if(getnum(arg, &N) && N <= 1){
text_mode = N & 1;
text_scroll = 0;
Tlast_scroll = Tms;
text_needs_redraw = 1;
return "Line mode set\n";
}
return "Wrong mode\n";
case 'P':
// start receiving of blob
display_mode = 1;
blob_remaining = SCREENBUF_SZ;
blob_ptr = screenbuf;
return "Send blob\n";
case 'R':
USB_send("Soft reset\n");
NVIC_SystemReset();
break;
case 'S':
if(getnum(arg, &N) && N <= 1){
choose_font(N ? FONT14 : FONTN8);
text_scroll = 0;
Tlast_scroll = Tms;
text_needs_redraw = 1;
return "Font set\n";
}
return "Wrong font\n";
case 'T':{
int i;
for(i = 0; i < TEXTBUF_SZ - 1 && *arg && *arg != '\n'; ++i)
text_buf[i] = *arg++;
text_buf[i] = 0;
text_scroll = 0;
Tlast_scroll = Tms;
display_mode = 0;
text_needs_redraw = 1;
return "Text set\n";
}
default:
return helpmsg;
}
return NULL;
}
// process blob receiving
void proto_process(){
if(blob_remaining > 0){
uint8_t tmp[64];
int x = USB_receive((char*)tmp);
if(x > 0){
int n = (x < blob_remaining) ? x : (int)blob_remaining;
memcpy(blob_ptr, tmp, n);
blob_ptr += n;
blob_remaining -= n;
}
return;
}
// read commands
if(usb_line_len < USBBUFSZ){
int x = USB_receive(usb_line + usb_line_len);
if(x > 0){
usb_line_len += x;
int start = 0;
for(int i = 0; i < usb_line_len; ++i){
if(usb_line[i] == '\n'){
usb_line[i + 1] = 0;
const char *ans = parse_cmd(usb_line + start);
if(ans) USB_send(ans);
start = i + 1;
}
}
if(start){
int rest = usb_line_len - start;
if(rest > 0) memmove(usb_line, usb_line + start, rest);
usb_line_len = rest;
}
}
}
// 3. refresh/scroll text
update_scroll();
if(text_needs_redraw && display_mode == 0){
text_needs_redraw = 0;
render_text();
}
}
// 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;
}

View File

@@ -0,0 +1,32 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef PROTO_H__
#define PROTO_H__
#include <stm32f1.h>
void proto_process();
void printu(uint32_t val);
void printuhex(uint32_t val);
char *omit_spaces(const char *buf);
char *getnum(const char *buf, uint32_t *N);
char *u2str(uint32_t val);
#endif // PROTO_H__

View File

@@ -0,0 +1,219 @@
/*
* This file is part of the TETRIS project.
* Copyright 2019 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 <string.h> // memset, memcpy
#include <stdio.h>
#include "debug.h"
#include "fonts.h"
#include "hardware.h"
#include "screen.h"
// !!!FOR LITTLE-ENDIAN!!!
uint32_t score = 0; // current game's score
uint32_t StepMS, Tlast, incSpd = 0; // common for all games timer values
// X coordinate - from left to right!
// Y coordinate - from top to bottom!
// (0,0) is top left corner
// all-screen buffer
uint8_t screenbuf[SCREENBUF_SZ];
extern volatile uint32_t Tms; // time for FPS count
static uint32_t FPS = 0, Tfps = 0; // approx FPS
uint32_t getFPS(){return FPS;}
static uint8_t fgColor = 0xff, bgColor = 0; // foreground and background colors
void setBGcolor(uint8_t c){bgColor = c;}
void setFGcolor(uint8_t c){fgColor = c;}
/**
* @brief FillScreen - fill screen buffer with current bgColor
*/
void ClearScreen(){
for(int i = 0; i < SCREENBUF_SZ; ++i)
screenbuf[i] = bgColor;
}
/**
* @brief DrawPix - set or clear pixel
* @param X, Y - pixel coordinates (could be outside of screen)
* @param pix - == pixel color (RRRGGGBB)
*/
void DrawPix(int16_t X, int16_t Y, uint8_t pix){
if(X < 0 || X > SCREEN_WIDTH-1 || Y < 0 || Y > SCREEN_HEIGHT-1) return; // outside of screen
// now calculate coordinate of pixel
screenbuf[Y*SCREEN_WIDTH + X] = pix;
}
void InvertPix(int16_t X, int16_t Y){
if(X < 0 || X > SCREEN_WIDTH-1 || Y < 0 || Y > SCREEN_HEIGHT-1) return; // outside of screen
screenbuf[Y*SCREEN_WIDTH + X] = ~screenbuf[Y*SCREEN_WIDTH + X];
}
void XORPix(int16_t X, int16_t Y, uint8_t pix){
if(X < 0 || X > SCREEN_WIDTH-1 || Y < 0 || Y > SCREEN_HEIGHT-1) return; // outside of screen
screenbuf[Y*SCREEN_WIDTH + X] ^= pix;
}
uint8_t GetPix(int16_t X, int16_t Y){
if(X < 0 || X > SCREEN_WIDTH-1 || Y < 0 || Y > SCREEN_HEIGHT-1) return 0;
return screenbuf[Y*SCREEN_WIDTH + X];
}
/**
* @brief DrawCharAt - draws character @ position X,Y (this point is left baseline corner of char!)
* character will be drawn with current fg and bg colors
* @param X, Y - started point
* @param Char - char to draw
* @return char width
*/
uint8_t DrawCharAt(int16_t X, int16_t Y, uint8_t Char){
const uint8_t *curchar = font_char(Char);
if(!curchar) return 0;
// now change Y coordinate to left upper corner of font
Y += curfont->baseline - curfont->height + 1;
// height and width of letter in pixels
uint8_t h = curfont->height, w = *curchar++; // now curchar is pointer to bits array
uint8_t lw = curfont->bytes / h; // width of letter in bytes
for(uint8_t row = 0; row < h; ++row){
for(uint8_t col = 0; col < w; ++col){
if(curchar[row*lw + (col/8)] & (1 << (7 - (col%8))))
DrawPix(X + col, Y + row, fgColor);
else
DrawPix(X + col, Y + row, bgColor);
}
}
return w;
}
/**
* @brief PutStringAt - draw text string @ screen
* @param X, Y - base coordinates
* @param str - string to draw
* @return - text width in pixels
*/
uint8_t PutStringAt(int16_t X, int16_t Y, const char *str){
if(!str) return 0;
int16_t Xold = X;
while(*str){
X += DrawCharAt(X, Y, (uint8_t)*str++);
}
return X - Xold;
}
/**
* @brief CenterStringAt - draw string @ center line
* @param Y - y coordinate
* @param str - string
* @return - text width in pixels
*/
uint8_t CenterStringAt(int16_t Y, const char *str){
int l = strpixlen(str);
return PutStringAt((SCREEN_WIDTH - l)/2, Y, str);
}
// full string length in pixels
int strpixlen(const char *str){
int l = 0;
while(*str){
const uint8_t *c = font_char(*str++);
if(c) l += *c;
}
return l;
}
static screen_state ScrnState = SCREEN_RELAX;
screen_state getScreenState(){return ScrnState;}
static uint8_t currentB = 0; // current block number
static uint8_t Ntick = 0; // tick number (0..7) for PWM color
/**
* @brief process_screen - screen state machine processing
*/
void process_screen(){
static uint32_t framecnt = 0;
switch(ScrnState){
case SCREEN_ACTIVE: // transmission active
if(transfer_done){
ScrnState = SCREEN_UPDATENXT;
}else return;
// fallthrough
case SCREEN_UPDATENXT:
ConvertScreenBuf(screenbuf, currentB, Ntick); // convert data
TIM_DMA_transfer(currentB); // start transfer
ScrnState = SCREEN_ACTIVE;
if(++Ntick >= 7 + NBLACK_FRAMES){
Ntick = 0;
if(++currentB >= NBLOCKS){
currentB = 0; // start again
++framecnt;
if(Tms - Tfps > 999){
FPS = framecnt;
Tfps = Tms;
framecnt = 0;
}
}
}
break;
default:
return;
}
}
/**
* @brief ShowScreen - turn on data transmission
*/
void ScreenON(){
ScrnState = SCREEN_UPDATENXT;
Tfps = Tms;
process_screen();
}
void ScreenOFF(){
stopTIMDMA();
SCRN_DISBL();
ScrnState = SCREEN_RELAX;
currentB = 0;
Ntick = 0;
}
/**
* @brief RGB2pack - convert RGB color to packed RRRGGGBB
* @param RGB - color (each in range 0..8)
* @return packed color
*/
uint8_t RGB2pack(const uint8_t *RGB){
uint8_t b = RGB[2] & 7;
if(b) b = (b - 1) >> 1;
return ((RGB[0] & 7)<<5 | (RGB[1] & 7) << 2 | b);
}
/**
* @brief pack2RGB - convert packed color to array of RGB (0..8)
* @param pack - packed color
* @return RGB array
*/
uint8_t *pack2RGB(uint8_t pack){
static uint8_t RGB[3];
RGB[0] = pack >> 5;
RGB[1] = (pack & 0x1c) >> 2;
pack &= 3;
if(pack) RGB[2] = (pack<<1) + 1;
else RGB[2] = 0;
return RGB;
}

View File

@@ -0,0 +1,93 @@
/*
* This file is part of the TETRIS project.
* Copyright 2019 Edward V. Emelianov <eddy@sao.ru, edward.emelianoff@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef SCREEN_H__
#define SCREEN_H__
#include <stdint.h>
// additional black frames for display won't be so bright
#define NBLACK_FRAMES (7)
// display size in px
// PANEL_WIDTH is width of one panel
//#define PANEL_WIDTH (64)
// SCREEN_WIDTH is total screen width
#define SCREEN_WIDTH (128)
#define SCREEN_HEIGHT (32)
#define SCREENBUF_SZ (SCREEN_WIDTH*SCREEN_HEIGHT)
#define SCREEN_HW (SCREEN_WIDTH/2)
#define SCREEN_HH (SCREEN_HEIGHT/2)
// amount of blocks @ screen
#define NBLOCKS (16)
// pause to show a quater of screen - 10ms (25Hz framerate)
#define SCREEN_PAUSE (3)
typedef enum{ // screen states
SCREEN_RELAX, // nothing to do (screen is off)
SCREEN_ACTIVE, // transmission active
SCREEN_UPDATENXT // update next quarter
} screen_state;
// colors
#define COLOR_BLACK (0b00000000)
#define COLOR_WHITE (0b11111111)
#define COLOR_GRAY (0b01101101)
#define COLOR_LGRAY (0b10110110)
#define COLOR_BLUE (0b00000011)
#define COLOR_LBLUE (0b00000001)
#define COLOR_GREEN (0b00011100)
#define COLOR_LGREEN (0b00001100)
#define COLOR_RED (0b11100000)
#define COLOR_LRED (0b01100000)
#define COLOR_CYAN (0b00011111)
#define COLOR_LCYAN (0b00000101)
#define COLOR_PURPLE (0b11100011)
#define COLOR_LPURPLE (0b01100001)
#define COLOR_YELLOW (0b11111100)
#define COLOR_LYELLOW (0b00100100)
extern uint32_t score; // current game score
extern uint8_t screenbuf[SCREENBUF_SZ];
extern uint32_t StepMS, Tlast, incSpd; // common for all games timer values
screen_state getScreenState();
void ClearScreen();
void setBGcolor(uint8_t c);
void setFGcolor(uint8_t c);
void DrawPix(int16_t X, int16_t Y, uint8_t pix);
void InvertPix(int16_t X, int16_t Y);
void XORPix(int16_t X, int16_t Y, uint8_t pix);
uint8_t GetPix(int16_t X, int16_t Y);
uint8_t DrawCharAt(int16_t X, int16_t Y, uint8_t Char);
uint8_t PutStringAt(int16_t X, int16_t Y, const char *str);
uint8_t CenterStringAt(int16_t Y, const char *str);
int strpixlen(const char *str);
uint8_t *getScreenBuf();
void process_screen();
void ScreenON();
void ScreenOFF();
uint32_t getFPS();
uint8_t RGB2pack(const uint8_t *RGB);
uint8_t *pack2RGB(uint8_t pack);
#endif // SCREEN_H__

View File

@@ -0,0 +1,167 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "usb.h"
#include "usb_lib.h"
static volatile uint8_t tx_succesfull = 1;
static volatile uint8_t rxNE = 0;
static int sstrlen(const char *s){
if(!s) return 0;
int l = 0;
while(*s++) ++l;
return l;
}
// interrupt IN handler (never used?)
static void EP1_Handler(){
uint16_t epstatus = KEEP_DTOG(USB->EPnR[1]);
if(RX_FLAG(epstatus)) epstatus = (epstatus & ~USB_EPnR_STAT_TX) ^ USB_EPnR_STAT_RX; // set valid RX
else epstatus = epstatus & ~(USB_EPnR_STAT_TX|USB_EPnR_STAT_RX);
// clear CTR
epstatus = (epstatus & ~(USB_EPnR_CTR_RX|USB_EPnR_CTR_TX));
USB->EPnR[1] = epstatus;
}
// data IN/OUT handlers
static void transmit_Handler(){ // EP3IN
tx_succesfull = 1;
uint16_t epstatus = KEEP_DTOG_STAT(USB->EPnR[3]);
// clear CTR keep DTOGs & STATs
USB->EPnR[3] = (epstatus & ~(USB_EPnR_CTR_TX)); // clear TX ctr
}
static void receive_Handler(){ // EP2OUT
rxNE = 1;
uint16_t epstatus = KEEP_DTOG_STAT(USB->EPnR[2]);
USB->EPnR[2] = (epstatus & ~(USB_EPnR_CTR_RX)); // clear RX ctr
}
void USB_setup(){
NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
NVIC_DisableIRQ(USB_HP_CAN1_TX_IRQn);
RCC->APB1ENR |= RCC_APB1ENR_USBEN;
USB->CNTR = USB_CNTR_FRES; // Force USB Reset
for(uint32_t ctr = 0; ctr < 72000; ++ctr) nop(); // wait >1ms
//uint32_t ctr = 0;
USB->CNTR = 0;
USB->BTABLE = 0;
USB->DADDR = 0;
USB->ISTR = 0;
USB->CNTR = USB_CNTR_RESETM | USB_CNTR_WKUPM; // allow only wakeup & reset interrupts
NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
}
static int usbwr(const char *buf, int l){
uint32_t ctra = 1000000;
while(--ctra && tx_succesfull == 0){
IWDG->KR = IWDG_REFRESH;
}
tx_succesfull = 0;
EP_Write(3, (uint8_t*)buf, l);
ctra = 1000000;
while(--ctra && tx_succesfull == 0){
IWDG->KR = IWDG_REFRESH;
}
if(tx_succesfull == 0){usbON = 0; return 1;} // usb is OFF?
return 0;
}
static char usbbuff[USB_TXBUFSZ-1]; // temporary buffer (63 - to prevent need of ZLP)
static int buflen = 0; // amount of symbols in usbbuff
// send next up to 63 bytes of data in usbbuff
static void send_next(){
if(!buflen || !tx_succesfull) return;
tx_succesfull = 0;
EP_Write(3, (uint8_t*)usbbuff, buflen);
buflen = 0;
}
// unblocking sending - just fill a buffer
void USB_send(const char *buf){
int len = sstrlen(buf);
if(!usbON || !len) return;
if(len > USB_TXBUFSZ-1 - buflen){
usbwr(usbbuff, buflen);
buflen = 0;
}
if(len > USB_TXBUFSZ-1){
USB_send_blk(buf, len);
return;
}
while(len--) usbbuff[buflen++] = *buf++;
}
// blocking sending
void USB_send_blk(const char *buf, int len){
if(!usbON || !len) return; // USB disconnected
if(buflen){
usbwr(usbbuff, buflen);
buflen = 0;
}
int needzlp = 0;
while(len){
if(len == USB_TXBUFSZ) needzlp = 1;
int s = (len > USB_TXBUFSZ) ? USB_TXBUFSZ : len;
if(usbwr(buf, s)) return;
len -= s;
buf += s;
}
if(needzlp){
usbwr(NULL, 0);
}
}
void usb_proc(){
switch(USB_Dev.USB_Status){
case USB_STATE_CONFIGURED:
// make new BULK endpoint
// Buffer have 1024 bytes, but last 256 we use for CAN bus (30.2 of RM: USB main features)
EP_Init(1, EP_TYPE_INTERRUPT, USB_EP1BUFSZ, 0, EP1_Handler); // IN1 - transmit
EP_Init(2, EP_TYPE_BULK, 0, USB_RXBUFSZ, receive_Handler); // OUT2 - receive data
EP_Init(3, EP_TYPE_BULK, USB_TXBUFSZ, 0, transmit_Handler); // IN3 - transmit data
USB_Dev.USB_Status = USB_STATE_CONNECTED;
break;
case USB_STATE_DEFAULT:
case USB_STATE_ADDRESSED:
if(usbON){
usbON = 0;
}
break;
default: // USB_STATE_CONNECTED - send next data portion
if(!usbON) return;
send_next();
}
}
/**
* @brief USB_receive
* @param buf (i) - buffer[64] for received data
* @return amount of received bytes
*/
int USB_receive(char *buf){
if(!usbON || !rxNE) return 0;
int sz = EP_Read(2, (uint16_t*)buf);
uint16_t epstatus = KEEP_DTOG(USB->EPnR[2]);
// keep stat_tx & set ACK rx
USB->EPnR[2] = (epstatus & ~(USB_EPnR_STAT_TX)) ^ USB_EPnR_STAT_RX;
rxNE = 0;
return sz;
}

View File

@@ -0,0 +1,33 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __USB_H__
#define __USB_H__
#include "hardware.h"
#define BUFFSIZE (64)
void USB_setup();
void usb_proc();
void USB_send(const char *buf);
void USB_send_blk(const char *buf, int len);
int USB_receive(char *buf);
#endif // __USB_H__

View File

@@ -0,0 +1,102 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __USB_DEFS_H__
#define __USB_DEFS_H__
#include <stm32f1.h>
// max endpoints number
#define STM32ENDPOINTS 8
/**
* Buffers size definition
**/
#define USB_BTABLE_SIZE 512
// first 64 bytes of USB_BTABLE are registers!
//#define USB_EP0_BASEADDR 64
// for USB FS EP0 buffers are from 8 to 64 bytes long (64 for PL2303)
#define USB_EP0_BUFSZ 64
// USB transmit buffer size (64 for PL2303)
#define USB_TXBUFSZ 64
// USB receive buffer size (64 for PL2303)
#define USB_RXBUFSZ 64
// EP1 - interrupt - buffer size
#define USB_EP1BUFSZ 8
#define USB_BTABLE_BASE 0x40006000
#define USB_BASE ((uint32_t)0x40005C00)
#define USB ((USB_TypeDef *) USB_BASE)
#ifdef USB_BTABLE
#undef USB_BTABLE
#endif
#define USB_BTABLE ((USB_BtableDef *)(USB_BTABLE_BASE))
#define USB_ISTR_EPID 0x0000000F
#define USB_FNR_LSOF_0 0x00000800
#define USB_FNR_lSOF_1 0x00001000
#define USB_LPMCSR_BESL_0 0x00000010
#define USB_LPMCSR_BESL_1 0x00000020
#define USB_LPMCSR_BESL_2 0x00000040
#define USB_LPMCSR_BESL_3 0x00000080
#define USB_EPnR_CTR_RX 0x00008000
#define USB_EPnR_DTOG_RX 0x00004000
#define USB_EPnR_STAT_RX 0x00003000
#define USB_EPnR_STAT_RX_0 0x00001000
#define USB_EPnR_STAT_RX_1 0x00002000
#define USB_EPnR_SETUP 0x00000800
#define USB_EPnR_EP_TYPE 0x00000600
#define USB_EPnR_EP_TYPE_0 0x00000200
#define USB_EPnR_EP_TYPE_1 0x00000400
#define USB_EPnR_EP_KIND 0x00000100
#define USB_EPnR_CTR_TX 0x00000080
#define USB_EPnR_DTOG_TX 0x00000040
#define USB_EPnR_STAT_TX 0x00000030
#define USB_EPnR_STAT_TX_0 0x00000010
#define USB_EPnR_STAT_TX_1 0x00000020
#define USB_EPnR_EA 0x0000000F
#define USB_COUNTn_RX_BLSIZE 0x00008000
#define USB_COUNTn_NUM_BLOCK 0x00007C00
#define USB_COUNTn_RX 0x0000003F
#ifdef USB_TypeDef
#define USB_TypeDef USB_TypeDef_custom
#endif
typedef struct {
__IO uint32_t EPnR[STM32ENDPOINTS];
__IO uint32_t RESERVED[STM32ENDPOINTS];
__IO uint32_t CNTR;
__IO uint32_t ISTR;
__IO uint32_t FNR;
__IO uint32_t DADDR;
__IO uint32_t BTABLE;
} USB_TypeDef;
typedef struct{
__IO uint32_t USB_ADDR_TX;
__IO uint32_t USB_COUNT_TX;
__IO uint32_t USB_ADDR_RX;
__IO uint32_t USB_COUNT_RX;
} USB_EPDATA_TypeDef;
typedef struct{
__IO USB_EPDATA_TypeDef EP[STM32ENDPOINTS];
} USB_BtableDef;
#endif // __USB_DEFS_H__

View File

@@ -0,0 +1,476 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include "usb_lib.h"
ep_t endpoints[STM32ENDPOINTS];
usb_dev_t USB_Dev;
static usb_LineCoding lineCoding = {115200, 0, 0, 8};
static config_pack_t setup_packet;
static uint8_t ep0databuf[EP0DATABUF_SIZE];
static uint8_t ep0dbuflen = 0;
usb_LineCoding getLineCoding(){return lineCoding;}
uint8_t usbON = 0; // device disconnected from terminal
// definition of parts common for USB_DeviceDescriptor & USB_DeviceQualifierDescriptor
#define bcdUSB_L 0x10
#define bcdUSB_H 0x01
#define bDeviceClass 0
#define bDeviceSubClass 0
#define bDeviceProtocol 0
#define bNumConfigurations 1
static const uint8_t USB_DeviceDescriptor[] = {
18, // bLength
0x01, // bDescriptorType - Device descriptor
bcdUSB_L, // bcdUSB_L - 1.10
bcdUSB_H, // bcdUSB_H
bDeviceClass, // bDeviceClass - USB_COMM
bDeviceSubClass, // bDeviceSubClass
bDeviceProtocol, // bDeviceProtocol
USB_EP0_BUFSZ, // bMaxPacketSize
0x7b, // idVendor_L PL2303: VID=0x067b, PID=0x2303
0x06, // idVendor_H
0x03, // idProduct_L
0x23, // idProduct_H
0x00, // bcdDevice_Ver_L
0x03, // bcdDevice_Ver_H
0x01, // iManufacturer
0x02, // iProduct
0x00, // iSerialNumber
bNumConfigurations // bNumConfigurations
};
static const uint8_t USB_DeviceQualifierDescriptor[] = {
10, //bLength
0x06, // bDescriptorType - Device qualifier
bcdUSB_L, // bcdUSB_L
bcdUSB_H, // bcdUSB_H
bDeviceClass, // bDeviceClass
bDeviceSubClass, // bDeviceSubClass
bDeviceProtocol, // bDeviceProtocol
USB_EP0_BUFSZ, // bMaxPacketSize0
bNumConfigurations, // bNumConfigurations
0x00 // Reserved
};
static const uint8_t USB_ConfigDescriptor[] = {
/*Configuration Descriptor*/
0x09, /* bLength: Configuration Descriptor size */
0x02, /* bDescriptorType: Configuration */
39, /* wTotalLength:no of returned bytes */
0x00,
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor describing the configuration */
0xa0, /* bmAttributes - Bus powered, Remote wakeup */
0x32, /* MaxPower 100 mA */
/*---------------------------------------------------------------------------*/
/*Interface Descriptor */
0x09, /* bLength: Interface Descriptor size */
0x04, /* bDescriptorType: Interface */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x03, /* bNumEndpoints: 3 endpoints used */
0xff, /* bInterfaceClass */
0x00, /* bInterfaceSubClass */
0x00, /* bInterfaceProtocol */
0x00, /* iInterface: */
///////////////////////////////////////////////////
/*Endpoint 1 Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
0x05, /* bDescriptorType: Endpoint */
0x81, /* bEndpointAddress IN1 */
0x03, /* bmAttributes: Interrupt */
0x0a, /* wMaxPacketSize LO: */
0x00, /* wMaxPacketSize HI: */
0x01, /* bInterval: */
/*Endpoint OUT2 Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
0x05, /* bDescriptorType: Endpoint */
0x02, /* bEndpointAddress: OUT2 */
0x02, /* bmAttributes: Bulk */
(USB_RXBUFSZ & 0xff), /* wMaxPacketSize: 64 */
(USB_RXBUFSZ >> 8),
0x00, /* bInterval: ignore for Bulk transfer */
/*Endpoint IN3 Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
0x05, /* bDescriptorType: Endpoint */
0x83, /* bEndpointAddress IN3 */
0x02, /* bmAttributes: Bulk */
(USB_TXBUFSZ & 0xff), /* wMaxPacketSize: 64 */
(USB_TXBUFSZ >> 8),
0x00, /* bInterval: ignore for Bulk transfer */
};
_USB_LANG_ID_(USB_StringLangDescriptor, LANG_US);
// these descriptors are not used in PL2303 emulator!
_USB_STRING_(USB_StringSerialDescriptor, u"0");
_USB_STRING_(USB_StringManufacturingDescriptor, u"Prolific Technology Inc.");
_USB_STRING_(USB_StringProdDescriptor, u"USB-Serial Controller");
/*
* default handlers
*/
// SET_LINE_CODING
void WEAK linecoding_handler(usb_LineCoding __attribute__((unused)) *lc){
}
// SET_CONTROL_LINE_STATE
void WEAK clstate_handler(uint16_t __attribute__((unused)) val){
}
// SEND_BREAK
void WEAK break_handler(){
}
// handler of vendor requests
void WEAK vendor_handler(config_pack_t *packet){
if(packet->bmRequestType & 0x80){ // read
uint8_t c;
switch(packet->wValue){
case 0x8484:
c = 2;
break;
case 0x0080:
c = 1;
break;
case 0x8686:
c = 0xaa;
break;
default:
c = 0;
}
EP_WriteIRQ(0, &c, 1);
}else{ // write ZLP
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
}
static void wr0(const uint8_t *buf, uint16_t size){
if(setup_packet.wLength < size) size = setup_packet.wLength; // shortened request
if(size < endpoints[0].txbufsz){
EP_WriteIRQ(0, buf, size);
return;
}
while(size){
uint16_t l = size;
if(l > endpoints[0].txbufsz) l = endpoints[0].txbufsz;
EP_WriteIRQ(0, buf, l);
buf += l;
size -= l;
uint8_t needzlp = (l == endpoints[0].txbufsz) ? 1 : 0;
if(size || needzlp){ // send last data buffer
uint16_t status = KEEP_DTOG(USB->EPnR[0]);
// keep DTOGs, clear CTR_RX,TX, set TX VALID, leave stat_Rx
USB->EPnR[0] = (status & ~(USB_EPnR_CTR_RX|USB_EPnR_CTR_TX|USB_EPnR_STAT_RX))
^ USB_EPnR_STAT_TX;
uint32_t ctr = 1000000;
while(--ctr && (USB->ISTR & USB_ISTR_CTR) == 0){IWDG->KR = IWDG_REFRESH;};
if((USB->ISTR & USB_ISTR_CTR) == 0){
return;
}
if(needzlp) EP_WriteIRQ(0, (uint8_t*)0, 0);
}
}
}
static inline void get_descriptor(){
switch(setup_packet.wValue){
case DEVICE_DESCRIPTOR:
wr0(USB_DeviceDescriptor, sizeof(USB_DeviceDescriptor));
break;
case CONFIGURATION_DESCRIPTOR:
wr0(USB_ConfigDescriptor, sizeof(USB_ConfigDescriptor));
break;
case STRING_LANG_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringLangDescriptor, STRING_LANG_DESCRIPTOR_SIZE_BYTE);
break;
case STRING_MAN_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringManufacturingDescriptor, USB_StringManufacturingDescriptor.bLength);
break;
case STRING_PROD_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringProdDescriptor, USB_StringProdDescriptor.bLength);
break;
case STRING_SN_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringSerialDescriptor, USB_StringSerialDescriptor.bLength);
break;
case DEVICE_QUALIFIER_DESCRIPTOR:
wr0(USB_DeviceQualifierDescriptor, USB_DeviceQualifierDescriptor[0]);
break;
default:
break;
}
}
static uint8_t configuration = 0; // reply for GET_CONFIGURATION (==1 if configured)
static inline void std_d2h_req(){
uint16_t status = 0; // bus powered
switch(setup_packet.bRequest){
case GET_DESCRIPTOR:
get_descriptor();
break;
case GET_STATUS:
EP_WriteIRQ(0, (uint8_t *)&status, 2); // send status: Bus Powered
break;
case GET_CONFIGURATION:
EP_WriteIRQ(0, &configuration, 1);
break;
default:
break;
}
}
static inline void std_h2d_req(){
switch(setup_packet.bRequest){
case SET_ADDRESS:
// new address will be assigned later - after acknowlegement or request to host
USB_Dev.USB_Addr = setup_packet.wValue;
break;
case SET_CONFIGURATION:
// Now device configured
USB_Dev.USB_Status = USB_STATE_CONFIGURED;
configuration = setup_packet.wValue;
break;
default:
break;
}
}
/*
bmRequestType: 76543210
7 direction: 0 - host->device, 1 - device->host
65 type: 0 - standard, 1 - class, 2 - vendor
4..0 getter: 0 - device, 1 - interface, 2 - endpoint, 3 - other
*/
/**
* Endpoint0 (control) handler
*/
static void EP0_Handler(){
uint16_t epstatus = USB->EPnR[0]; // EP0R on input -> return this value after modifications
uint8_t reqtype = setup_packet.bmRequestType & 0x7f;
uint8_t dev2host = (setup_packet.bmRequestType & 0x80) ? 1 : 0;
int rxflag = RX_FLAG(epstatus);
if(rxflag && SETUP_FLAG(epstatus)){
switch(reqtype){
case STANDARD_DEVICE_REQUEST_TYPE: // standard device request
if(dev2host){
std_d2h_req();
}else{
std_h2d_req();
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
break;
case STANDARD_ENDPOINT_REQUEST_TYPE: // standard endpoint request
if(setup_packet.bRequest == CLEAR_FEATURE){
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
break;
case VENDOR_REQUEST_TYPE:
vendor_handler(&setup_packet);
break;
case CONTROL_REQUEST_TYPE:
switch(setup_packet.bRequest){
case GET_LINE_CODING:
EP_WriteIRQ(0, (uint8_t*)&lineCoding, sizeof(lineCoding));
break;
case SET_LINE_CODING: // omit this for next stage, when data will come
break;
case SET_CONTROL_LINE_STATE:
usbON = 1;
clstate_handler(setup_packet.wValue);
break;
case SEND_BREAK:
usbON = 0;
break_handler();
break;
default:
break;
}
if(setup_packet.bRequest != GET_LINE_CODING) EP_WriteIRQ(0, (uint8_t *)0, 0); // write acknowledgement
break;
default:
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
}else if(rxflag){ // got data over EP0 or host acknowlegement
if(endpoints[0].rx_cnt){
if(setup_packet.bRequest == SET_LINE_CODING){
linecoding_handler((usb_LineCoding*)ep0databuf);
}
}
} else if(TX_FLAG(epstatus)){ // package transmitted
// now we can change address after enumeration
if ((USB->DADDR & USB_DADDR_ADD) != USB_Dev.USB_Addr){
USB->DADDR = USB_DADDR_EF | USB_Dev.USB_Addr;
// change state to ADRESSED
USB_Dev.USB_Status = USB_STATE_ADDRESSED;
}
}
epstatus = KEEP_DTOG(USB->EPnR[0]);
if(rxflag) epstatus ^= USB_EPnR_STAT_TX; // start ZLP/data transmission
else epstatus &= ~USB_EPnR_STAT_TX; // or leave unchanged
// keep DTOGs, clear CTR_RX,TX, set RX VALID
USB->EPnR[0] = (epstatus & ~(USB_EPnR_CTR_RX|USB_EPnR_CTR_TX)) ^ USB_EPnR_STAT_RX;
}
static uint16_t lastaddr = LASTADDR_DEFAULT;
/**
* Endpoint initialisation
* @param number - EP num (0...7)
* @param type - EP type (EP_TYPE_BULK, EP_TYPE_CONTROL, EP_TYPE_ISO, EP_TYPE_INTERRUPT)
* @param txsz - transmission buffer size @ USB/CAN buffer
* @param rxsz - reception buffer size @ USB/CAN buffer
* @param uint16_t (*func)(ep_t *ep) - EP handler function
* @return 0 if all OK
*/
int EP_Init(uint8_t number, uint8_t type, uint16_t txsz, uint16_t rxsz, void (*func)(ep_t ep)){
if(number >= STM32ENDPOINTS) return 4; // out of configured amount
if(txsz > USB_BTABLE_SIZE || rxsz > USB_BTABLE_SIZE) return 1; // buffer too large
if(lastaddr + txsz + rxsz >= USB_BTABLE_SIZE) return 2; // out of btable
USB->EPnR[number] = (type << 9) | (number & USB_EPnR_EA);
USB->EPnR[number] ^= USB_EPnR_STAT_RX | USB_EPnR_STAT_TX_1;
if(rxsz & 1 || rxsz > 512) return 3; // wrong rx buffer size
uint16_t countrx = 0;
if(rxsz < 64) countrx = rxsz / 2;
else{
if(rxsz & 0x1f) return 3; // should be multiple of 32
countrx = 31 + rxsz / 32;
}
USB_BTABLE->EP[number].USB_ADDR_TX = lastaddr;
endpoints[number].tx_buf = (uint16_t *)(USB_BTABLE_BASE + lastaddr*2);
endpoints[number].txbufsz = txsz;
lastaddr += txsz;
USB_BTABLE->EP[number].USB_COUNT_TX = 0;
USB_BTABLE->EP[number].USB_ADDR_RX = lastaddr;
endpoints[number].rx_buf = (uint16_t *)(USB_BTABLE_BASE + lastaddr*2);
lastaddr += rxsz;
USB_BTABLE->EP[number].USB_COUNT_RX = countrx << 10;
endpoints[number].func = func;
return 0;
}
// standard IRQ handler
void usb_lp_can_rx0_isr(){
if(USB->ISTR & USB_ISTR_RESET){
usbON = 0;
// Reinit registers
USB->CNTR = USB_CNTR_RESETM | USB_CNTR_CTRM | USB_CNTR_SUSPM | USB_CNTR_WKUPM;
USB->ISTR = 0;
// Endpoint 0 - CONTROL
// ON USB LS size of EP0 may be 8 bytes, but on FS it should be 64 bytes!
lastaddr = LASTADDR_DEFAULT;
// clear address, leave only enable bit
USB->DADDR = USB_DADDR_EF;
USB_Dev.USB_Status = USB_STATE_DEFAULT;
USB->ISTR = ~USB_ISTR_RESET;
if(EP_Init(0, EP_TYPE_CONTROL, USB_EP0_BUFSZ, USB_EP0_BUFSZ, EP0_Handler)){
return;
}
}
if(USB->ISTR & USB_ISTR_CTR){
// EP number
uint8_t n = USB->ISTR & USB_ISTR_EPID;
// copy status register
uint16_t epstatus = USB->EPnR[n];
// copy received bytes amount
endpoints[n].rx_cnt = USB_BTABLE->EP[n].USB_COUNT_RX & 0x3FF; // low 10 bits is counter
// check direction
if(USB->ISTR & USB_ISTR_DIR){ // OUT interrupt - receive data, CTR_RX==1 (if CTR_TX == 1 - two pending transactions: receive following by transmit)
if(n == 0){ // control endpoint
if(epstatus & USB_EPnR_SETUP){ // setup packet -> copy data to conf_pack
EP_Read(0, (uint16_t*)&setup_packet);
ep0dbuflen = 0;
// interrupt handler will be called later
}else if(epstatus & USB_EPnR_CTR_RX){ // data packet -> push received data to ep0databuf
ep0dbuflen = endpoints[0].rx_cnt;
EP_Read(0, (uint16_t*)&ep0databuf);
}
}
}
// call EP handler
if(endpoints[n].func) endpoints[n].func(endpoints[n]);
}
if(USB->ISTR & USB_ISTR_SUSP){ // suspend -> still no connection, may sleep
usbON = 0;
USB->CNTR |= USB_CNTR_FSUSP | USB_CNTR_LP_MODE;
USB->ISTR = ~USB_ISTR_SUSP;
}
if(USB->ISTR & USB_ISTR_WKUP){ // wakeup
USB->CNTR &= ~(USB_CNTR_FSUSP | USB_CNTR_LP_MODE); // clear suspend flags
USB->ISTR = ~USB_ISTR_WKUP;
}
}
/**
* Write data to EP buffer (called from IRQ handler)
* @param number - EP number
* @param *buf - array with data
* @param size - its size
*/
void EP_WriteIRQ(uint8_t number, const uint8_t *buf, uint16_t size){
uint8_t i;
if(size > endpoints[number].txbufsz) size = endpoints[number].txbufsz;
uint16_t N2 = (size + 1) >> 1;
// the buffer is 16-bit, so we should copy data as it would be uint16_t
uint16_t *buf16 = (uint16_t *)buf;
uint32_t *out = (uint32_t *)endpoints[number].tx_buf;
for(i = 0; i < N2; ++i, ++out){
*out = buf16[i];
}
USB_BTABLE->EP[number].USB_COUNT_TX = size;
}
/**
* Write data to EP buffer (called outside IRQ handler)
* @param number - EP number
* @param *buf - array with data
* @param size - its size
*/
void EP_Write(uint8_t number, const uint8_t *buf, uint16_t size){
EP_WriteIRQ(number, buf, size);
uint16_t status = KEEP_DTOG(USB->EPnR[number]);
// keep DTOGs, clear CTR_TX & set TX VALID to start transmission
USB->EPnR[number] = (status & ~(USB_EPnR_CTR_TX)) ^ USB_EPnR_STAT_TX;
}
/*
* Copy data from EP buffer into user buffer area
* @param *buf - user array for data
* @return amount of data read
*/
int EP_Read(uint8_t number, uint16_t *buf){
int sz = endpoints[number].rx_cnt;
if(!sz) return 0;
endpoints[number].rx_cnt = 0;
int n = (sz + 1) >> 1;
uint32_t *in = (uint32_t *)endpoints[number].rx_buf;
if(n){
for(int i = 0; i < n; ++i, ++in)
buf[i] = *(uint16_t*)in;
}
return sz;
}

View File

@@ -0,0 +1,184 @@
/*
* This file is part of the TETRIS project.
* Copyright 2021 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __USB_LIB_H__
#define __USB_LIB_H__
#include <wchar.h>
#include "usb_defs.h"
#define EP0DATABUF_SIZE (64)
#define LASTADDR_DEFAULT (STM32ENDPOINTS * 8)
// bmRequestType & 0x7f
#define STANDARD_DEVICE_REQUEST_TYPE 0
#define STANDARD_ENDPOINT_REQUEST_TYPE 2
#define VENDOR_REQUEST_TYPE 0x40
#define CONTROL_REQUEST_TYPE 0x21
// bRequest, standard; for bmRequestType == 0x80
#define GET_STATUS 0x00
#define GET_DESCRIPTOR 0x06
#define GET_CONFIGURATION 0x08
// for bmRequestType == 0
#define CLEAR_FEATURE 0x01
#define SET_FEATURE 0x03 // unused
#define SET_ADDRESS 0x05
#define SET_DESCRIPTOR 0x07 // unused
#define SET_CONFIGURATION 0x09
// for bmRequestType == 0x81, 1 or 0xB2
#define GET_INTERFACE 0x0A // unused
#define SET_INTERFACE 0x0B // unused
#define SYNC_FRAME 0x0C // unused
#define VENDOR_REQUEST 0x01 // unused
// Class-Specific Control Requests
#define SEND_ENCAPSULATED_COMMAND 0x00 // unused
#define GET_ENCAPSULATED_RESPONSE 0x01 // unused
#define SET_COMM_FEATURE 0x02 // unused
#define GET_COMM_FEATURE 0x03 // unused
#define CLEAR_COMM_FEATURE 0x04 // unused
#define SET_LINE_CODING 0x20
#define GET_LINE_CODING 0x21
#define SET_CONTROL_LINE_STATE 0x22
#define SEND_BREAK 0x23
// control line states
#define CONTROL_DTR 0x01
#define CONTROL_RTS 0x02
// wValue
#define DEVICE_DESCRIPTOR 0x100
#define CONFIGURATION_DESCRIPTOR 0x200
#define STRING_LANG_DESCRIPTOR 0x300
#define STRING_MAN_DESCRIPTOR 0x301
#define STRING_PROD_DESCRIPTOR 0x302
#define STRING_SN_DESCRIPTOR 0x303
#define DEVICE_QUALIFIER_DESCRIPTOR 0x600
#define RX_FLAG(epstat) (epstat & USB_EPnR_CTR_RX)
#define TX_FLAG(epstat) (epstat & USB_EPnR_CTR_TX)
#define SETUP_FLAG(epstat) (epstat & USB_EPnR_SETUP)
// EPnR bits manipulation
#define KEEP_DTOG_STAT(EPnR) (EPnR & ~(USB_EPnR_STAT_RX|USB_EPnR_STAT_TX|USB_EPnR_DTOG_RX|USB_EPnR_DTOG_TX))
#define KEEP_DTOG(EPnR) (EPnR & ~(USB_EPnR_DTOG_RX|USB_EPnR_DTOG_TX))
// USB state: uninitialized, addressed, ready for use
typedef enum{
USB_STATE_DEFAULT,
USB_STATE_ADDRESSED,
USB_STATE_CONFIGURED,
USB_STATE_CONNECTED
} USB_state;
// EP types
#define EP_TYPE_BULK 0x00
#define EP_TYPE_CONTROL 0x01
#define EP_TYPE_ISO 0x02
#define EP_TYPE_INTERRUPT 0x03
#define LANG_US (uint16_t)0x0409
#define _USB_STRING_(name, str) \
static const struct name \
{ \
uint8_t bLength; \
uint8_t bDescriptorType; \
uint16_t bString[(sizeof(str) - 2) / 2]; \
\
} \
name = {sizeof(name), 0x03, str}
#define _USB_LANG_ID_(name, lng_id) \
\
static const struct name \
{ \
uint8_t bLength; \
uint8_t bDescriptorType; \
uint16_t bString; \
\
} \
name = {0x04, 0x03, lng_id}
#define STRING_LANG_DESCRIPTOR_SIZE_BYTE (4)
// EP0 configuration packet
typedef struct {
uint8_t bmRequestType;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} config_pack_t;
// endpoints state
typedef struct{
uint16_t *tx_buf; // transmission buffer address
uint16_t txbufsz; // transmission buffer size
uint16_t *rx_buf; // reception buffer address
void (*func)(); // endpoint action function
unsigned rx_cnt : 10; // received data counter
} ep_t;
// USB status & its address
typedef struct {
uint8_t USB_Status;
uint16_t USB_Addr;
}usb_dev_t;
typedef struct {
uint32_t dwDTERate;
uint8_t bCharFormat;
#define USB_CDC_1_STOP_BITS 0
#define USB_CDC_1_5_STOP_BITS 1
#define USB_CDC_2_STOP_BITS 2
uint8_t bParityType;
#define USB_CDC_NO_PARITY 0
#define USB_CDC_ODD_PARITY 1
#define USB_CDC_EVEN_PARITY 2
#define USB_CDC_MARK_PARITY 3
#define USB_CDC_SPACE_PARITY 4
uint8_t bDataBits;
} __attribute__ ((packed)) usb_LineCoding;
typedef struct {
uint8_t bmRequestType;
uint8_t bNotificationType;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} __attribute__ ((packed)) usb_cdc_notification;
extern ep_t endpoints[];
extern usb_dev_t USB_Dev;
extern uint8_t usbON;
void USB_Init();
void USB_ResetState();
int EP_Init(uint8_t number, uint8_t type, uint16_t txsz, uint16_t rxsz, void (*func)());
void EP_WriteIRQ(uint8_t number, const uint8_t *buf, uint16_t size);
void EP_Write(uint8_t number, const uint8_t *buf, uint16_t size);
int EP_Read(uint8_t number, uint16_t *buf);
usb_LineCoding getLineCoding();
void linecoding_handler(usb_LineCoding *lc);
void clstate_handler(uint16_t val);
void break_handler();
void vendor_handler(config_pack_t *packet);
#endif // __USB_LIB_H__

View File

@@ -0,0 +1,2 @@
#define BUILD_NUMBER "6"
#define BUILD_DATE "2026-10-10"