This commit is contained in:
Angel Maldonado 2019-09-15 20:01:10 +02:00
parent 389a3ae817
commit c4f360455b
26 changed files with 2964 additions and 0 deletions

7
.gitignore vendored Normal file
View file

@ -0,0 +1,7 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
\.vscode/

View file

@ -0,0 +1,387 @@
# Serial Protocol (OLRBoard←→Host)
- - -
**Revisions:**
-
- - -
-
In the present doc the terms Board and Host indicate:
- ***Board***: OLR Board - The microcontroller managing the led strip (Arduino)
- ***Host***: The Host running the OpenLedRace COnfiguration software (PC, RPI, etc)
The Board is currently connected to the Host via Serial interface (USB)
## Implementation characteristic
1. Local Communication between Board and Host use plain ASCII (not binary).
2. Messages are kept very short (lightweight protocol for “speed” and low resources.)
## Message formats
- Messages are composed by 2 parts: **Command**, **Parameters**.
- Messages with multiple parameters, the char **'.'** is used as **"Parameters Separator"**
- Messages sending back command confirmation uses "**<i>command</i>OK**" and "**<i>command</i>NOK**"
- Example: **CNOK** is the 'error' answer sent for a C command
- Telemetry Messages (see below) have fixed lenght parameters, and no
message terminator.
- Any other message ends with the "EOC" (End Of Command) char:
- [LF] - Line Feed = ASCII 10/0x0A = new line = \n
- The following command, for example, is used by a OLR Device (Arduino)
to send the “Setup OK - Configuration Complete” message:
- `R0[LF] `
* * *
## Commands list
Command | Description | Notes
--------|---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
\# | Protocol Handshaking | Host-Board handshake on startup
@ | Reset | Host send a Reset to the Board
$ | Get UID | Get Board Unique Id
% | Get Version | Get Board Software version
: | Set Unique ID | Set Board Unique ID
! | Send log/error msg | Send a log/error message to peer
**C** | **C**onfiguration Race | Set basic race configuration
**Q** | Query board cfg | Host request the current situation of the Config Parameters Set
**R** | Race phase | Command used to notify current Race phase
**T** | Track configuration | Command used to configure a new track setup.
**A** | Ramp configuration | Command used to configure a ramp in the track.
**D** | Load Track and ramp defult | Command used to set default parameter for ramp and track
**p** | Car current position in OLR | Current position of the car in the OLR
**w** | Car Win the Race | A car just win the current race
* * *
## Commands Description
In the following sections the column "**Initiate**" contains the id of the board sending the message.
- ***B*** - ***Board***: OLR Board (Arduino Nano)
- ***H*** - ***Host***: Host where the OpenLedRace Manger program is running (RPI, PC, ...).
Same rule applies to the "***From***" column in "***Response***"
Some commands may be originated by both peers (ex: Handshake command)
The string **_[LF]_** indicates the EOC (End of Command) char = "line feed / new line", (ASCII 10/0A)
- - -
### [#] - Protocol Handshaking [Implmented]
|initiate| Syntax | Description
|------|--------|------------
|B, H|**#**_[LF]_ | **Protocol Handshaking**
|| | Sent to initialize a connection (Board and Host) |
|**Response**| **From** | **Notes**
|**#**_[LF]_ |H, B | The connection opens succesfully when a “**#**” is received 'back' from the peer
||| **Please Note:**
||| Board and Host send back only one ACK (send back a '#' just once)
- - -
### [@] - Reset [To be implemented]
|initiate| Syntax | Description
|------|--------|------------
|H |**@**_[LF]_|**OLR Board Reset request**
| | | Sent from Host to Reset the OLR Board to the initial state (before handshake)
|**Response**| **From** | **Notes**
| | | No response expected from Board
- - -
### [$] - Get Board UID [Implemented]
| initiate | Syntax | Description |
|----------|-------------|------------------------------------|
| H | **$**_[LF]_ | **OLR Board UID request** |
| | | Sent from Host to get Board's UID |
|**Response**| **From** | **Notes**
|------|--------|------------
|**$**Id[LF] | B | Send the UID strings
#### UID String format
-- to be defined
#### Examples
|Origin|Command||
|---|----|----|
|H|**$[LF]**| Host send a **get info** request
|B|**?3179c3ec6e28a[LF]**|The message from the Board contains Id="3179c3ec6e28a"
|Origin|Command||
|---|----|----|
|H|**?[LF]**| Host send a **get info** request
|B|**?[LF]**|The message from the Board indicates ID not set.
- - -
### [%] - Get Software Version [Implemented]
Used to check software compatibility between Board and Host program's versions
| initiate | Syntax | Description |
|----------|-------------|------------------------------------|
| H | **%** [LF] | **OLR Board software version request** |
|**Response**| **From** | **Notes**
|------|--------|------------
|**%**Ver[LF] | B | String representing the Software Version
#### Software Version String format
-- to be defined
#### Examples
|Origin|Command||
|---|----|----|
|H|**%[LF]**| Host send a **get info** request
|B|**%1.0[LF]**|The message from the Board indicates Version="1.0.1"
- - -
### [:] - Set board Unique Id [Implemented]
The software running on the Board contains a routine to write an ID to EEPROM.<br>
The first time a Board is connected to a OLRNetwork the Unique Id may be empty (not every Board comes with the ID preloaded in EEPROM).<br>
The Host calculates an ID and send this **Set Id** command to the Board that will store
it in EEPROM.<br>
From now on this is the ID the board will send back when receiving a **Get Info '$'** command.
|initiate| Syntax | Description
|------|--------|------------
|H |**:**id[LF]|**OLR Board Set UniqueId request**
|| | Sent from Host to Set Board's Unique Id
|Parameters | | |
|----------------|---|---|
| |id: | String representing the Unique Id. The string contains 16 characters max.
|Response| |
|---|---
|**OK**[LF] | Board sends "OK" string (ACK)
|**NOK**[LF] | Board indicates that something went wrong
- - -
### [!] - Send log/error message [Work in progress]
The software running on the Board use this command to send messages to be written into the Host logfile.<br>
The Host will log the message and decide what to do with the relay race according to the "Severity" parameter (nothing, stop it, etc.)
|initiate| Syntax | Description
|------|--------|------------
|B |**!**Severity,Message[LF]|**OLR Board Sends an error message to Host**
|Parameters | | |
|----------------|---|---|
| Severity:[0-3] | single char|
| | 1| **Log only** - Board want to log a message into the Host Message LogFile,<br> Sent usually in development/debug phase to trace the dialog between Board and Host |
| | 2| **Warning** - Board send back a "warning" message<br>Sent by board on 'not blocking' errors like, for example, unknown commands or parameters |
| | 3| **Blocking Error** - The boards have a Severe error condition and cannot proceed.<br> The Host will log the message into the Host Message LogFile and decide what to do (if the Host is running a RelayRace it will Stop the Race)<br>
| | | |
| Message:String |ASCII| The ASCII String containing the message.
|**Response**| **From** | **Notes**
|------|--------|------------
| | H | No answer sent from Host
#### Examples
|Origin|Command||
|---|----|----|
|B|**\!1,invalid Car=[3] in [t] command**| Board send a warning message about a previously received command
- - -
### [**C**] - Set basic race configuration [Implemented]
|initiate| Syntax | Description
|------|--------|------------
|H |**C**start.nlap.repeat.finish[LF] |**Host Set basic race configuration**
#### Parameters
| Parameter |Format| Description
|--------|---|---------
| **start** | [0-1] |**Start Line** of the race is in this Board (Y/N) (0=No, 1=Yes)
| **nlap** | [1-9][0-9]? |Number of consecutive laps in each **section** of the Relay Race
| | | max 2 chars (range 1-99)<br>Number of consecutive laps the cars will “run” before race finish **or** car get trough the OutTunnel
| **repeat** |[1-9][0-9]?| Number of times to **repeat the configured section** of nlap laps.
| | | max 2 chars (range 1-99)<br>How many times the section of L laps will be repeated
| **finish** |[0-1] |**Finish Line** of the race is in this Board (Y/N) (0=No, 1=Yes)
|Response| |
|---|---
|**OK**[LF] | Board sends "OK" string (ACK)
|**NOK**[LF] |Board indicates that something went wrong
#### Examples
|Origin|Command||
|---|----|----|
|H|**C0,5,2,1**|**start=0**: The Race starts in another OLR The Board will be waiting for messages like “Race Started”, “Car 1 Leaving”, Car 1 Leaved”, etc...
|||**laps=5**: Each car will need to complete 5 laps before it can cross the Finish Line **or** get to the next OLR through the OutTunne.<br>(see 'repeat' param)
|||**repeat=2**: Each car will need to repoeat 2 times the section of nlap laps.<br>This means well expect each car will be sent back here (through the InTunnel) after we previously sent it out to another Racetrack.
|||**finish=1**: The Race ends here.This OLR will manage the Finsh Line Procedure.
|B|**OK[LF]**| This is the Response from the Board to the previous example(ACK)
|||The message from the Board indicates that the value for Position,laps, repeat and finish line has been set correctly as requested by the host.
| | | |
|H|**C1,2,3,0[LF]**| Position in Race is “1” The Race starts here
|||The Board will be managing the Start Race phase (Semaphore, etc.) |
|||Each car will need to complete 2 loops here before can get to the next Racetrack (through the OutTunne) .
|||Each car will need to repoeat 3 times the section of nlap laps.
|||The Race ends in another OLR.
|B|**NOK[LF]**| This is a Response from the Board (ACK)
|||The [NOK] value from the Board indicates that something went wrong (the board received some invalid paramenter value). |
- - -
### [T] - **T**rack configuration [ Implemented ]
This configuration is stored in non-volatile memory.
|initiate| Syntax | Description
|------|--------|------------
|H |**T**box.tbd[LF] |**Host Set basic race configuration**
#### Parameters
| Parameter |Format| Description
|--------|---|---------
| **box** | [0-MAXLED] | Number of the led where the box starts. Set 0 to remove box.
| **tbd** | [TBD] | Not used yet, set to 0.
|Response| |
|---|---
|**TOK**[LF] | Board sends "OK" string (ACK)
|**TNOK**[LF] |Board indicates that something went wrong
|Origin|Command||
|---|----|----|
|H|**T260,0**|: Set the box line in led number 260.
- - -
### [A] - r**A**ramp configuration [ Implemented ]
This configuration is stored in non-volatile memory.
|initiate| Syntax | Description
|------|--------|------------
|H |**A**center.high[LF] |**Host Set basic race configuration**
#### Parameters
| Parameter |Format| Description
|--------|---|---------
| **center** | [0-MAXLED] | Number of the led where ramp is centered. Set 0 to remove box.
| **height** | [ 0 - 1023] | Ramp elevation
|Response| |
|---|---
|**AOK**[LF] | Board sends "OK" string (ACK)
|**ANOK**[LF] |Board indicates that something went wrong
|Origin|Command||
|---|----|----|
|H|**A150,12**|: Set the ramp centered in led 150.
- - -
### [D] - **D**efault configuration [ Implemented ]
Set default configuration to track and ramp settings.
|initiate| Syntax | Description
|------|--------|------------
|H |**D**[LF] |**Host Set basic race configuration**
- - -
### [**p**] - Current Car **p**osition in Race [Implemented]
|initiate| Syntax | Description
|------|--------|------------
|B|**p**NumTrackNlapRpos[LF]|**Position for each car in the race**
|||Sent during race for each car currently in this Board.
|Parameters | | |
|--------------|---|---|
| Num [1-9] | | One char representing Car Number.
| Track [A-Z] | | One char representing the Track where the car is.
| | M | Main Track |
| | B | Box Track |
| | U | Not Track |
| | . | .... |
| Nlap [1-99] | | Number of the Current Lap.
| Rpos [00-99] | | Relative position in a track in percent.
|Response| From | |
|---|--- |---
| | H | No response from host
#### Examples
|Origin|Command||
|---|----|----|
|B|**p**1B1.95**p**2M5.45[LF]| Two cars are currentry "running" in the Board. Car "1" is in Track "B" in Lap number "1" Relative Lap Position 95%. Car "2" is in Track "M" in Lap number "5" Relative Lap Position 45%
- - -
### [w] - Car Win te Race [Implemented]
|initiate| Syntax | Description
|------|--------|------------
|B|**w**Num[LF]|**Car 'Num' just win the race**
|||Sent by the circuit managing the "Finish Line" when a car cross it.
|Parameters | | |
|----------------|---|---|
| Num [1-9] | |One char representing Car Number
|Response| From | |
|---|--- |---
| | H | No response from host
#### Examples
|Origin|Command||
|---|----|----|
|B|**w**1| Car "1" win the race
30_Network_Protocol_Serial.md
Mostrando 30_Network_Protocol_Serial.md.

39
include/README Normal file
View file

@ -0,0 +1,39 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,392 @@
# Librería Arduino AsyncSerial
La librería AsyncSerial implementa funciones para recibir y enviar un Stream de forma no bloqueante. En general, está diseñada para recibir datos por puerto serie sin interferir excesivamente el Loop principal.
La librería AsyncSerial trabaja con un buffer externo, que hay que proporcionar a la librería. Tras la recepción, los datos quedan almacenados en este buffer. La librería está diseñada para emplearse junto a la librería Parser, aunque cualquier otro medio de interpretación es posible.
Más información https://www.luisllamas.es/libreria-arduino-AsyncSerial/
## Instrucciones de uso
La librería AsyncSerial realiza la recepción o envío de un Stream de forma no bloqueante. Para ello emplea un buffer de bytes, que no es generado por la librería para evitar duplicar el espacio. En su lugar, este buffer debe ser facilitado a la librería en el constructor, aunque puede modificarse con la función 'Init(...).
Durante su funcionamiento, AsyncSerial modifica el contenido del buffer. Por tanto, no hay que almacenar ningún otro dato en el mismo, ni realizar su lectura mientras se esté emplando AsyncSerial. Por defecto, AsyncSerial emplea Serial para lectura y envío de datos, aunque puede ser modificado por cualquier otro Stream (otro Serial, SoftwareSerial, lectura de archivos, otra sistema de comunicación, etc...).
La función principal es AsyncRecieve(...), que recibe y almacena datos en el buffer hasta recibir un caracter delimitador. Por defecto, este caracter es '\r', ya que la mayoría de software envían este caracter como finalizador de línea junto a '\n', pero algunos software prescinden de '\n' (curiosamente) por lo que resulta más apropiado emplear '\r'. Por el mismo motivo, AsyncSerial ignora los caracteres '\n'. No obstante, puede cambiarse estos delimitadores cambiando los campos 'FinishChar e 'IgnoreChar.
La forma de realizar acciones de AsyncSerial es a través de funciones de callback, que reciben el AsyncSerial emisor como parámetro por referencia. Cuando AsyncSerial recibe el delimitador 'FinishChar se ejecuta la función de callback 'OnRecieveOk. Si el tiempo de Timeout expira, se ejecuta la función 'OnTimeout. Finalmente, si en algún momento se sobre pasa la longitud máxima buffer se ejecuta el método OnOverflow.
Con la variable 'AllowOverflow puede activarse o desactivarse el comportamiento ante desbordamiento del buffer. Por defecto es false, por lo que no el buffer se reinicia en caso de Overflow. En caso de activar 'AllowOverflow, se activa el comportamiento circular del buffer por lo que el buffer preserva los últimos elementos recibidos.
En caso de Overflow el buffer se comporta como un buffer circular. Es decir, el indice del buffer se desplaza, de forma que en cada momento se dispone de los últimos N elementos recibidos en el buffer. Cuando finaliza la recepción, AsyncSerial emplea un algoritmo de movimiento de bloques para ordenar de forma eficiente el buffer.
Por otro lado, se dispone de un Timeout. Si durante la recepción se excede el tiempo de Timeout se ejecuta la función de callback correspondiente, y se finaliza el proceso de recepción. Para desactivar el Timeout simplemente fijarlo a cero.
Tras una recepción válida, se debe emplear los métodos 'GetContent() y 'GetContentLength() para acceder a la información recibida por AsyncSerial. Es importante no exceder la longitud proporcionada por 'GetContentLength() dado que el resto del buffer contendrá información inválida de anteriores recepciones.
Pese a ser el método principal no bloqueantes, en algunas ocasiones resulta necesario esperar a que finalice la recepción, y no seguir ejecutando el código del programa hasta que esta finalice. Por ello se dispone del método 'Recieve, que dispone de una lógica similar a AsyncSerial pero bloquea la ejecución del programa durante la recepción.
También se dispone de los métodos 'AsyncSend(...) y 'Send(...), que realizan el envío de los datos del buffer. Ambos métodos permiten esperar un caracter de ACK, siendo la diferencia entre ambos si esta espera es bloqueante o no.
Adicionalmente, podemos elegir si queremos que el funcionamiento de AsyncSerial sea contínuo, o simple. En caso contínuo, AsyncSerial se reinicia al finalizar una recepción. En caso contrario, podemos controlarlo con las funciones 'Start() y 'Stop(). El modo de funcionamiento se controla con la variable 'AutoReset.
El estado de AsyncSerial está almacenado en la variable 'Status, que puede tomar los valores IDDLE, RECIEVING_DATA, RECIEVING_DATA_OVERFLOW, MESSAGE_RECIEVED, MESSAGE_RECIEVED_OVERFLOW, TIMEOUT, SENDING_DATA, WAITING_ACK, MESSAGE_SENDED. Dependiendo de la configuración (autoreset, waitACK) y método que usemos (recepción, envío), AsyncSerial pasará por unos u otros estados.
Por último, disponemos de la función de callback 'OnByteProcessed, que se dispara cada vez que AsyncSerial procesa un nuevo byte. Además disponemos de la función 'ProcessByte(...) que introduce manualmente un byte en AsyncSerial, sin tener que leer del Stream. Combinados, podemos combinar dos o más AsyncSerial para conseguir comportamientos avanzados.
### Constructor
La clase AsyncSerial se instancia a través de su constructor, que requiere un puntero al buffer externo, su longitud máxima, y la función 'OnRecieveOK. Opcionalmente podemos añadir las otras funciones de callback.
```c++
AsyncSerial(byte *buffer, size_t bufferLength, AsyncSerialCallback OnRecievedOk, AsyncSerialCallback OnOverflow = nullptr, AsyncSerialCallback OnTimeout = nullptr );
```
No obstante, el origen y longitud del buffer, así como el Stream para las operaciones de lectura y escritura, pueden cambiarse con la función 'Init(...)
```c++
void Init(byte *buffer, size_t bufferLength, Stream* stream = NULL);
```
### Uso de AsyncSerial
El método principal de AsyncSerial es AsyncRecieve que, opcionalmente, admite un valor para el tiempo de Timeout (que también podemos fijar a través de una variable). Estas funciones devuelven el estado de AsyncSerial.
```c++
Status AsyncRecieve();
Status AsyncRecieve(int timeOut);
```
Por otro lado, podemos hacer una recepción bloqueante. En este caso es obligatorio especificar el tiempo de Timeout.
```c++
Status Recieve(int timeOut);
```
Cuando se finaliza la recepción, podemos obtener el contenido recibido a través de las funciones 'GetContent() y 'GetContentLength(). También es posible consultar el índice del último elemento respecto al buffer, y el último valor recibido.
```c++
byte* GetContent();
uint8_t GetContentLength();
uint8_t GetLastIndex();
uint8_t GetLastData();
```
Por otro lado, tenemos las funciones para enviar y recibir datos. Opcionalmente, se puede indicar si se desea esperar a que el recepto envíe un ACK. La diferencia entra 'AsyncSend(...) y 'Send(...) es si la espera del ACK es o no bloqueante.
```c++
void AsyncSend(bool waitAck = false);
void AsyncSend(byte* data, size_t dataLength, bool waitAck = false);
void Send(bool waitAck = false);
void Send(byte* data, size_t dataLength, bool waitAck = false);
```
Otras funciones y métodos que configurar el comportamiento de AsyncSerial son
```c++
void Start(); // Activa el AsyncSerial (si AutoReset == false)
void Stop(); // Pone el AsyncSerial en IDDLE (si AutoReset == false)
inline bool IsExpired(); // Devuelve True si AsyncSerial ha excedido el tiempo de Timeout
unsigned long Timeout = 0; // Establece el tiempo de Timeout. Fijar a 0 para desactivar Timeout
bool AutoReset = true; // Si es true, AsyncSerial se reiniciará tras recibir un mensaje válido
bool AllowOverflow = false; // Controla el comportamiento ante desbordamiento
bool SendAck; // Controla el envío y recepción de ACK
char FinishChar = CARRIAGE_RETURN; // Caracter que finaliza el mensaje
char IgnoreChar = NEW_LINE; // Caracter ignorado durante la recepción
char AckChar = ACK; // Caracter de ACK enviado o recibido
```
## Ejemplos
La librería AsyncSerial incluye los siguientes ejemplos para ilustrar su uso.
* Simple: Muestra un ejemplo sencillo de uso de AsyncSerial.
```c++
#include "AsyncSerialLib.h"
const int dataLength = 10;
byte data[dataLength];
AsyncSerial asyncSerial(data, dataLength,
[](AsyncSerial& sender) { Serial.write(sender.GetContent(), asyncSerial.GetContentLength());
Serial.println(); });
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
}
void loop()
{
asyncSerial.AsyncRecieve();
}
```
* AsyncRecieveContinuous: Muestra la recepción no bloqueante contínua.
```c++
#include "AsyncSerialLib.h"
const int dataLength = 5;
byte data[dataLength];
void debug(String type)
{
Serial.print(type);
Serial.print("\t at: ");
Serial.print(millis());
Serial.print(" ms ");
}
void debugContent(AsyncSerial &serial)
{
Serial.print("\t Length: ");
Serial.print(serial.GetContentLength());
Serial.print(" Content: ");
Serial.write(serial.GetContent(), serial.GetContentLength());
}
AsyncSerial asyncSerial(data, dataLength,
[](AsyncSerial& sender) { debug(String("Recieved")); debugContent(sender); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Timeout")); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Overflow")); Serial.println(); }
);
unsigned long start;
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
asyncSerial.Timeout = 5000;
asyncSerial.AllowOverflow = true;
}
void loop()
{
asyncSerial.AsyncRecieve();
}
```
* AsyncRecieveSimple: Muestra la recepción no bloqueante sin AutoReset. Usa una función auxiliar para simular la activación y desactivación.
```c++
#include "AsyncSerialLib.h"
const int dataLength = 5;
byte data[dataLength];
void debug(String type)
{
Serial.print(type);
Serial.print("\t at: ");
Serial.print(millis());
Serial.print(" ms ");
}
void debugContent(AsyncSerial &serial)
{
Serial.print("\t Length: ");
Serial.print(serial.GetContentLength());
Serial.print(" Content: ");
Serial.write(serial.GetContent(), serial.GetContentLength());
}
AsyncSerial asyncSerial(data, dataLength,
[](AsyncSerial& sender) { debug(String("Recieved")); debugContent(sender); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Timeout")); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Overflow")); Serial.println(); }
);
unsigned long start;
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
asyncSerial.Timeout = 5000;
asyncSerial.AutoReset = false;
asyncSerial.AllowOverflow = true;
start = millis();
}
void loop()
{
asyncSerial.AsyncRecieve();
// Restart the AsyncSerial for example purposes
if ((unsigned long)(millis() - start > 10000))
Restart();
}
void Restart()
{
Serial.print("-- Restarting example at ");
while (Serial.available()) Serial.read(); //empty buffer
Serial.print(millis());
Serial.println("ms -- ");
start = millis();
asyncSerial.Start();
}
```
* Recieve: Muestra la recepción bloqueante de AsyncSerial.
```c++
#include "AsyncSerialLib.h"
const int dataLength = 5;
byte data[dataLength];
void debug(String type)
{
Serial.print(type);
Serial.print("\t at: ");
Serial.print(millis());
Serial.print(" ms ");
}
void debugContent(AsyncSerial &serial)
{
Serial.print("\t Length: ");
Serial.print(serial.GetContentLength());
Serial.print(" Content: ");
Serial.write(serial.GetContent(), serial.GetContentLength());
}
AsyncSerial asyncSerial(data, dataLength,
[](AsyncSerial& sender) { debug(String("Recieved")); debugContent(sender); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Timeout")); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Overflow")); Serial.println(); }
);
unsigned long start;
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
asyncSerial.Timeout = 5000;
asyncSerial.AutoReset = false;
start = millis();
}
void loop()
{
debug("Start recieving"); Serial.println();
asyncSerial.Recieve(5000);
debug("End recieving"); Serial.println();
}
```
* AsyncSend: Muestra el envío de datos con recepción no bloqueante del ACK.
```c++
#include "AsyncSerialLib.h"
const int dataLength = 5;
byte data[dataLength] = { 65, 65, 65, 65, 65 };
void debug(String type)
{
Serial.print(type);
Serial.print("\t at: ");
Serial.print(millis());
Serial.print(" ms ");
}
AsyncSerial asyncSerial(data, dataLength,
[](AsyncSerial& sender) { Serial.println(); debug(String("Recieved")); Serial.println(); },
[](AsyncSerial& sender) { Serial.println(); debug(String("Timeout")); Serial.println(); }
);
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
asyncSerial.AutoReset = true;
asyncSerial.Timeout = 5000;
asyncSerial.AckChar = 'B';
}
// Open serial monitor. When recieve 'AAAAA', send 'B' as ACK, or do nothing to Timeout
void loop()
{
asyncSerial.AsyncSend(true);
}
```
* Multichain: Muestra el uso combinado de varios AsyncSerial, en este ejemplo para procesar un array separado por comas (no necesariamente la forma más eficiente, pero útil para un ejemplo).
```c++
#include "AsyncSerialLib.h"
const int dataLength1 = 5;
byte data1[dataLength1];
const int dataLength2 = 5;
byte data2[dataLength2];
void complete2(AsyncSerial& sender)
{
Serial.print(" Token from AsyncSerial2: ");
Serial.write(sender.GetContent(), sender.GetContentLength());
Serial.println();
}
AsyncSerial asyncSerial2(data2, dataLength2, complete2);
void complete1(AsyncSerial& sender)
{
asyncSerial2.ProcessByte(',');
Serial.println("--- Line end from AsyncSerial1 ---");
}
AsyncSerial asyncSerial1(data1, dataLength2, complete1);
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
asyncSerial1.OnByteProcessed = [](AsyncSerial& sender) {asyncSerial2.ProcessByte(sender.LastByte); };
asyncSerial2.FinishChar = ',';
}
// Write 1,2,3 in Serial port monitor
void loop()
{
asyncSerial1.AsyncRecieve();
}
```
* UserWithParser: Muestra el uso combinado con ArduinoParser para procesar los datos recibidos de forma no bloqueante.
```c++
#include "AsyncSerialLib.h"
#include <ParserLib.h>
void parse(Parser& par, AsyncSerial& aSerial)
{
par.Init(aSerial.GetContent(), aSerial.GetContentLength());
Serial.println(par.Read_Uint16());
par.SkipWhile(Parser::IsSeparator);
Serial.println(par.Read_Uint16());
par.Reset();
}
const int dataLength = 10;
byte data[dataLength];
Parser parser(data, dataLength);
AsyncSerial asyncSerial(data, dataLength, [](AsyncSerial& sender) { parse(parser, sender); });
// Open Serial port and write two numbers separated by . , ; - _ # = ?
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
}
void loop()
{
asyncSerial.AsyncRecieve();
}
```

View file

@ -0,0 +1,52 @@
/***************************************************
Copyright (c) 2018 Luis Llamas
(www.luisllamas.es)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
****************************************************/
#include "AsyncSerialLib.h"
const int dataLength = 5;
byte data[dataLength];
void debug(String type)
{
Serial.print(type);
Serial.print("\t at: ");
Serial.print(millis());
Serial.print(" ms ");
}
void debugContent(AsyncSerial &serial)
{
Serial.print("\t Length: ");
Serial.print(serial.GetContentLength());
Serial.print(" Content: ");
Serial.write(serial.GetContent(), serial.GetContentLength());
}
AsyncSerial asyncSerial(data, dataLength,
[](AsyncSerial& sender) { debug(String("Recieved")); debugContent(sender); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Timeout")); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Overflow")); Serial.println(); }
);
unsigned long start;
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
asyncSerial.Timeout = 5000;
asyncSerial.AllowOverflow = true;
}
void loop()
{
asyncSerial.AsyncRecieve();
}

View file

@ -0,0 +1,72 @@
/***************************************************
Copyright (c) 2018 Luis Llamas
(www.luisllamas.es)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
****************************************************/
#include "AsyncSerialLib.h"
const int dataLength = 5;
byte data[dataLength];
void debug(String type)
{
Serial.print(type);
Serial.print("\t at: ");
Serial.print(millis());
Serial.print(" ms ");
}
void debugContent(AsyncSerial &serial)
{
Serial.print("\t Length: ");
Serial.print(serial.GetContentLength());
Serial.print(" Content: ");
Serial.write(serial.GetContent(), serial.GetContentLength());
}
AsyncSerial asyncSerial(data, dataLength,
[](AsyncSerial& sender) { debug(String("Recieved")); debugContent(sender); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Timeout")); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Overflow")); Serial.println(); }
);
unsigned long start;
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
asyncSerial.Timeout = 5000;
asyncSerial.AutoReset = false;
asyncSerial.AllowOverflow = true;
start = millis();
}
void loop()
{
asyncSerial.AsyncRecieve();
// Restart the AsyncSerial for example purposes
if ((unsigned long)(millis() - start > 10000))
{
Restart();
}
}
void Restart()
{
Serial.print("-- Restarting example at ");
while (Serial.available()) Serial.read(); //empty buffer
Serial.print(millis());
Serial.println("ms -- ");
start = millis();
asyncSerial.Start();
}

View file

@ -0,0 +1,43 @@
/***************************************************
Copyright (c) 2018 Luis Llamas
(www.luisllamas.es)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
****************************************************/
#include "AsyncSerialLib.h"
const int dataLength = 5;
byte data[dataLength] = { 65, 65, 65, 65, 65 };
void debug(String type)
{
Serial.print(type);
Serial.print("\t at: ");
Serial.print(millis());
Serial.print(" ms ");
}
AsyncSerial asyncSerial(data, dataLength,
[](AsyncSerial& sender) { Serial.println(); debug(String("Recieved")); Serial.println(); },
[](AsyncSerial& sender) { Serial.println(); debug(String("Timeout")); Serial.println(); }
);
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
asyncSerial.AutoReset = true;
asyncSerial.Timeout = 5000;
asyncSerial.AckChar = 'B';
}
// Open serial monitor. When recieve 'AAAAA', send 'B' as ACK, or do nothing to Timeout
void loop()
{
asyncSerial.AsyncSend(true);
}

View file

@ -0,0 +1,55 @@
/***************************************************
Copyright (c) 2018 Luis Llamas
(www.luisllamas.es)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
****************************************************/
#include "AsyncSerialLib.h"
const int dataLength = 5;
byte data[dataLength];
void debug(String type)
{
Serial.print(type);
Serial.print("\t at: ");
Serial.print(millis());
Serial.print(" ms ");
}
void debugContent(AsyncSerial &serial)
{
Serial.print("\t Length: ");
Serial.print(serial.GetContentLength());
Serial.print(" Content: ");
Serial.write(serial.GetContent(), serial.GetContentLength());
}
AsyncSerial asyncSerial(data, dataLength,
[](AsyncSerial& sender) { debug(String("Recieved")); debugContent(sender); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Timeout")); Serial.println(); },
[](AsyncSerial& sender) { debug(String("Overflow")); Serial.println(); }
);
unsigned long start;
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
asyncSerial.Timeout = 5000;
asyncSerial.AutoReset = false;
start = millis();
}
void loop()
{
debug("Start recieving"); Serial.println();
asyncSerial.Recieve(5000);
debug("End recieving"); Serial.println();
}

View file

@ -0,0 +1,48 @@
/***************************************************
Copyright (c) 2018 Luis Llamas
(www.luisllamas.es)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
****************************************************/
#include "AsyncSerialLib.h"
const int dataLength1 = 5;
byte data1[dataLength1];
const int dataLength2 = 5;
byte data2[dataLength2];
void complete2(AsyncSerial& sender)
{
Serial.print(" Token from AsyncSerial2: ");
Serial.write(sender.GetContent(), sender.GetContentLength());
Serial.println();
}
AsyncSerial asyncSerial2(data2, dataLength2, complete2);
void complete1(AsyncSerial& sender)
{
asyncSerial2.ProcessByte(',');
Serial.println("--- Line end from AsyncSerial1 ---");
}
AsyncSerial asyncSerial1(data1, dataLength2, complete1);
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
asyncSerial1.OnByteProcessed = [](AsyncSerial& sender) {asyncSerial2.ProcessByte(sender.LastByte); };
asyncSerial2.FinishChar = ',';
}
// Write 1,2,3 in Serial port monitor
void loop()
{
asyncSerial1.AsyncRecieve();
}

View file

@ -0,0 +1,29 @@
/***************************************************
Copyright (c) 2018 Luis Llamas
(www.luisllamas.es)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
****************************************************/
#include "AsyncSerialLib.h"
const int dataLength = 10;
byte data[dataLength];
AsyncSerial asyncSerial(data, dataLength,
[](AsyncSerial& sender) { Serial.write(sender.GetContent(), asyncSerial.GetContentLength());
Serial.println(); });
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
}
void loop()
{
asyncSerial.AsyncRecieve();
}

View file

@ -0,0 +1,38 @@
/***************************************************
Copyright (c) 2018 Luis Llamas
(www.luisllamas.es)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
****************************************************/
#include "AsyncSerialLib.h"
#include <ParserLib.h>
void parse(Parser& par, AsyncSerial& aSerial)
{
par.Init(aSerial.GetContent(), aSerial.GetContentLength());
Serial.println(par.Read_Uint16());
par.SkipWhile(Parser::IsSeparator);
Serial.println(par.Read_Uint16());
par.Reset();
}
const int dataLength = 10;
byte data[dataLength];
Parser parser(data, dataLength);
AsyncSerial asyncSerial(data, dataLength, [](AsyncSerial& sender) { parse(parser, sender); });
// Open Serial port and write two numbers separated by . , ; - _ # = ?
void setup()
{
while (!Serial) { ; }
Serial.begin(9600);
Serial.println("Starting");
}
void loop()
{
asyncSerial.AsyncRecieve();
}

View file

@ -0,0 +1,30 @@
#######################################
# Syntax Coloring Map MyName
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
AsyncSerial KEYWORD1
AsyncSerialCallback KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
AsyncRecieve KEYWORD2
Recieve KEYWORD2
AsyncSend KEYWORD2
ProcessByte KEYWORD2
Send KEYWORD2
GetLastIndex KEYWORD2
GetLastData KEYWORD2
GetContent KEYWORD2
GetContentLength KEYWORD2
OrderBuffer KEYWORD2
Start KEYWORD2
Stop KEYWORD2
IsExpired KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################

View file

@ -0,0 +1,9 @@
name=AsyncSerial
version=1.0.0
author=Luis Llamas
maintainer=Luis Llamas
sentence=AsyncSerial Library
paragraph=Librería de Arduino que permite recibir un stream de forma no bloqueante
category=Other
url=https://www.luisllamas.es
architectures=*

View file

@ -0,0 +1,339 @@
/***************************************************
Copyright (c) 2018 Luis Llamas
(www.luisllamas.es)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
****************************************************/
#include "AsyncSerialLib.h"
AsyncSerial::AsyncSerial(byte* buffer, size_t bufferLength,
AsyncSerialCallback onRecievedOk, AsyncSerialCallback onTimeout = nullptr, AsyncSerialCallback onOverflow = nullptr)
{
Init(buffer, bufferLength, &Serial);
OnRecievedOk = onRecievedOk;
OnTimeout = onTimeout;
OnOverflow = onOverflow;
_startTime = millis();
}
void AsyncSerial::Init(byte *buffer, size_t bufferLength, Stream* stream)
{
_status = RECIEVING_DATA;
_startTime = millis();
_stream = stream == NULL ? &Serial : stream;
_buffer = buffer;
_bufferLength = bufferLength;
_bufferIndex = 0;
}
AsyncSerial::Status AsyncSerial::AsyncRecieve()
{
if (_status == IDDLE) { return; }
if (IsExpired())
{
if (OnTimeout != nullptr) OnTimeout(*this);
_status = TIMEOUT;
}
if (_status >= MESSAGE_RECIEVED)
{
_startTime = millis();
_status = AutoReset ? RECIEVING_DATA : IDDLE;
}
if (_status == RECIEVING_DATA || _status == RECIEVING_DATA_OVERFLOW)
{
asyncRecieve();
}
return _status;
}
AsyncSerial::Status AsyncSerial::AsyncRecieve(int timeOut)
{
Timeout = timeOut;
AsyncRecieve();
return _status;
}
AsyncSerial::Status AsyncSerial::Recieve(int timeOut)
{
_startTime = millis();
_status = RECIEVING_DATA;
bool expired = false;
while (!expired && _status < MESSAGE_RECIEVED)
{
AsyncRecieve();
expired = ((unsigned long)(millis() - _startTime) >= Timeout);
}
if (expired)
{
_status = TIMEOUT;
if (OnTimeout != nullptr) OnTimeout(*this);
}
return _status;
}
void AsyncSerial::AsyncSend(bool waitAck)
{
AsyncSend(_buffer, _bufferLength, waitAck);
}
void AsyncSerial::AsyncSend(byte* data, size_t dataLength, bool waitAck)
{
if (_status == IDDLE) return;
if (_status == TIMEOUT)
{
_status = AutoReset ? SENDING_DATA : IDDLE;
return;
}
if (_status != WAITING_ACK)
{
_stream->write(data, dataLength);
if (waitAck)
{
_status = WAITING_ACK;
_startTime = millis();
}
else
{
_status = AutoReset ? MESSAGE_SENDED : IDDLE;
if (OnRecievedOk != nullptr) OnRecievedOk(*this);
}
}
if (_status == WAITING_ACK)
{
if (IsExpired())
{
_status = TIMEOUT;
_startTime = millis();
if (OnTimeout != nullptr) OnTimeout(*this);
}
else
{
if (_stream->read() == AckChar)
{
_status = AutoReset ? MESSAGE_SENDED : IDDLE;
if (OnRecievedOk != nullptr) OnRecievedOk(*this);
}
}
}
}
void AsyncSerial::ProcessByte(byte data)
{
LastByte = data;
if (data == (byte)FinishChar) finishRecieve();
else processNewData();
}
void AsyncSerial::Send(bool waitAck)
{
Send(_buffer, _bufferLength, waitAck);
}
void AsyncSerial::Send(byte* data, size_t dataLength, bool waitAck)
{
_stream->write(data, dataLength);
if (waitAck)
{
_startTime = millis();
while (!IsExpired())
{
if (_stream->read() == AckChar)
{
_status = AutoReset ? MESSAGE_SENDED : IDDLE;
if (OnRecievedOk != nullptr) OnRecievedOk(*this);
return;
}
}
_status = TIMEOUT;
if (OnTimeout != nullptr) OnTimeout(*this);
}
else
{
_status = AutoReset ? MESSAGE_SENDED : IDDLE;
if (OnRecievedOk != nullptr) OnRecievedOk(*this);
}
}
uint8_t AsyncSerial::GetLastIndex()
{
return (_bufferIndex - 1 + _bufferLength) % _bufferLength;
}
byte AsyncSerial::GetLastData()
{
return _buffer[GetLastIndex()];
}
byte * AsyncSerial::GetContent()
{
return _buffer;
}
uint8_t AsyncSerial::GetContentLength()
{
return _status == MESSAGE_RECIEVED_OVERFLOW ? _bufferLength : _bufferIndex;
}
void AsyncSerial::OrderBuffer()
{
orderBuffer(_buffer, 0, _bufferLength - 1, GetLastIndex());
}
void AsyncSerial::Start()
{
_status = RECIEVING_DATA;
_bufferIndex = 0;
_startTime = millis();
}
void AsyncSerial::Stop()
{
_status = IDDLE;
}
inline bool AsyncSerial::IsExpired()
{
if (Timeout == 0) return false;
return ((unsigned long)(millis() - _startTime) > Timeout);
}
void AsyncSerial::asyncRecieve()
{
while (_stream->available())
{
byte newData = _stream->read();
ProcessByte(newData);
}
}
void AsyncSerial::processNewData()
{
if (LastByte != (byte)IgnoreChar)
{
if (OnByteProcessed != nullptr) OnByteProcessed(*this);
if (_bufferIndex >= _bufferLength)
{
_bufferIndex %= _bufferLength;
if (_status != RECIEVING_DATA_OVERFLOW)
{
if (OnOverflow != nullptr) OnOverflow(*this);
}
_status = RECIEVING_DATA_OVERFLOW;
}
_buffer[_bufferIndex] = LastByte;
_bufferIndex++;
}
}
void AsyncSerial::finishRecieve()
{
_status = (_status == RECIEVING_DATA_OVERFLOW ? MESSAGE_RECIEVED_OVERFLOW : MESSAGE_RECIEVED);
if (_status == MESSAGE_RECIEVED)
{
if (OnRecievedOk != nullptr) OnRecievedOk(*this);
}
else
{
if (AllowOverflow)
{
OrderBuffer();
if (OnRecievedOk != nullptr) OnRecievedOk(*this);
if (SendAck) _stream->write(AckChar);
}
}
_bufferIndex = 0;
}
void AsyncSerial::orderBuffer(byte buffer[], size_t start, size_t end, size_t index)
{
size_t leftBlockLength = index - start + 1;
size_t rigthBlockLength = end - index;
while (leftBlockLength != 0 && rigthBlockLength != 0)
{
if (leftBlockLength <= rigthBlockLength)
{
// RIGHT BLOCK SHIFT
swapBufferBlock(buffer, start, leftBlockLength);
start += leftBlockLength;
index += leftBlockLength;
}
else
{
// LEFT BLOCK SHIFT
swapBufferBlock(buffer, index - rigthBlockLength + 1, rigthBlockLength);
end -= rigthBlockLength;
index -= rigthBlockLength;
}
leftBlockLength = index - start + 1;
rigthBlockLength = end - index;
}
}
void AsyncSerial::swapBufferBlock(byte buffer[], size_t start, size_t length)
{
byte temp;
for (size_t i = 0; i < length; i++)
{
temp = buffer[start + i];
buffer[start + i] = buffer[start + i + length];
buffer[start + i + length] = temp;
}
}
void AsyncSerial::debugStatus()
{
switch (_status)
{
IDDLE: _stream->println("IDDLE"); break;
RECIEVING_DATA: _stream->println("RECIEVING_DATA"); break;
RECIEVING_DATA_OVERFLOW: _stream->println("RECIEVING_DATA_OVERFLOW"); break;
MESSAGE_RECIEVED: _stream->println("MESSAGE_RECIEVED"); break;
MESSAGE_RECIEVED_OVERFLOW: _stream->println("MESSAGE_RECIEVED_OVERFLOW"); break;
TIMEOUT: _stream->println("TIMEOUT"); break;
WAITING_ACK: _stream->println("WAITING_ACK"); break;
MESSAGE_SENDED: _stream->println(" "); break;
default: break;
}
}
void AsyncSerial::debugBuffer()
{
for (int i = 0; i < _bufferLength; i++)
{
_stream->print((char)_buffer[i]);
_stream->print("\t");
}
_stream->println();
for (int i = 0; i < _bufferLength; i++)
_stream->print(i == GetLastIndex() ? "^" : "\t");
_stream->println();
}

View file

@ -0,0 +1,101 @@
/***************************************************
Copyright (c) 2018 Luis Llamas
(www.luisllamas.es)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
****************************************************/
#ifndef _ASYNCSERIALLIB_h
#define _ASYNCSERIALLIB_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
const char CARRIAGE_RETURN = '\r';
const char NEW_LINE = '\n';
const char ACK = 0x06;
class AsyncSerial
{
typedef void(*AsyncSerialCallback)(AsyncSerial& sender);
public:
typedef enum
{
IDDLE,
RECIEVING_DATA,
RECIEVING_DATA_OVERFLOW,
MESSAGE_RECIEVED,
MESSAGE_RECIEVED_OVERFLOW,
TIMEOUT,
SENDING_DATA,
WAITING_ACK,
MESSAGE_SENDED
} Status;
AsyncSerial(byte *buffer, size_t bufferLength,
AsyncSerialCallback OnRecievedOk, AsyncSerialCallback OnOverflow = nullptr, AsyncSerialCallback OnTimeout = nullptr );
void Init(byte *buffer, size_t bufferLength, Stream* stream = NULL);
Status AsyncRecieve();
AsyncSerial::Status AsyncRecieve(int timeOut);
AsyncSerial::Status Recieve(int timeOut);
void AsyncSend(bool waitAck = false);
void AsyncSend(byte* data, size_t dataLength, bool waitAck = false);
void ProcessByte(byte data);
void Send(bool waitAck = false);
void Send(byte* data, size_t dataLength, bool waitAck = false);
uint8_t GetLastIndex();
uint8_t GetLastData();
byte* GetContent();
uint8_t GetContentLength();
void OrderBuffer();
void Start();
void Stop();
inline bool IsExpired();
AsyncSerialCallback OnRecievedOk;
AsyncSerialCallback OnOverflow;
AsyncSerialCallback OnTimeout;
AsyncSerialCallback OnByteProcessed;
unsigned long Timeout = 0;
bool AutoReset = true;
bool AllowOverflow = false;
bool SendAck;
byte LastByte;
char FinishChar = NEW_LINE;
char IgnoreChar = CARRIAGE_RETURN;
char AckChar = ACK;
protected:
Stream* _stream;
byte *_buffer;
size_t _bufferIndex;
size_t _bufferLength;
unsigned long _startTime;
bool _sendAck = false;
Status _status;
void asyncRecieve();
void processNewData();
void finishRecieve();
static void orderBuffer(byte buffer[], size_t start, size_t end, size_t index);
static void swapBufferBlock(byte buffer[], size_t start, size_t length);
void debugBuffer();
void debugStatus();
};
#endif

View file

@ -0,0 +1,74 @@
#include "olr-controller.h"
enum {
DELTA_ANALOG = 5,
};
static float const ACEL = 0.2;
void setup_controller( void ) {
if( DIGITAL_MODE == false ){
pinMode(PIN_VCC_ADC1, OUTPUT);
pinMode(PIN_VCC_ADC2, OUTPUT);
digitalWrite(PIN_VCC_ADC1, HIGH);
digitalWrite(PIN_VCC_ADC2, HIGH);
}
else{
pinMode(PIN_P1, INPUT_PULLUP);
pinMode(PIN_P2, INPUT_PULLUP);
}
pinMode(PIN_P1, INPUT_PULLUP); //pull up in adc
pinMode(PIN_P2, INPUT_PULLUP);
}
void init_controller( controller_t* ct, enum ctr_type mode, int pin ) {
ct->mode = mode;
ct->pin = pin;
ct->delta_analog = DELTA_ANALOG;
}
byte get_controllerStatus( controller_t* ct ) {
if( ct->mode == DIGITAL_MODE ){
return digitalRead( ct->pin );
}
else if( ct->mode == ANALOG_MODE ){
ct->adc = analogRead( ct->pin );
if( abs( ct->badc - ct->adc ) > ct->delta_analog ){
ct->badc = ct->adc;
return 1;
}
ct->badc = ct->adc;
}
else if( ct->mode == DEBUG_MODE ){
ct->adc++;
if( ct->adc >= 60){
ct->adc = 0;
return 1;
}
}
return 0;
}
float get_controller( controller_t* ct) {
float speed = 0.0;
if ( (ct->flag_sw == 1 ) && (get_controllerStatus( ct ) == 0) ) {
ct->flag_sw = 0;
speed = ACEL;
}
if ( (ct->flag_sw == 0 ) && (get_controllerStatus( ct ) == 1 ) ) {
ct->flag_sw = 1;
}
return speed;
}
float get_accel ( void ) {
return ACEL;
}

View file

@ -0,0 +1,52 @@
#ifndef _OLR_CONTROLLER_LIB_h
#define _OLR_CONTROLLER_LIB_h
#ifdef __cplusplus
extern "C"{
#endif
#include "Arduino.h"
#include <stdint.h>
#include <stdbool.h>
#define PIN_P1 A2 // switch player 1 to PIN and GND
#define PIN_P2 A3 // switch player 2 to PIN and GND
#define PIN_VCC_ADC1 6 // switch player 1 to PIN and GND
#define PIN_VCC_ADC2 7 // switch player 2 to PIN and GND
enum ctr_type{
NOT_DEFINED = 0,
DIGITAL_MODE,
ANALOG_MODE,
DEBUG_MODE,
};
typedef struct{
enum ctr_type mode;
int pin;
int adc;
int badc;
int delta_analog;
byte flag_sw;
}controller_t;
void setup_controller( void );
void init_controller( controller_t* ct, enum ctr_type mode, int pin );
byte get_controllerStatus( controller_t* ct );
float get_controller( controller_t* ct );
float get_accel ( void );
#ifdef __cplusplus
} // extern "C"
#endif
#endif

View file

@ -0,0 +1,130 @@
#include "Arduino.h"
#include "olr-lib.h"
static int T_SPEED_COIN = 0;
void process_main_track( track_t* tck, car_t* car );
void process_aux_track( track_t* tck, car_t* car );
void init_car( car_t* car, controller_t* ct, uint32_t color ) {
car->ct = ct;
car->color = color;
car->trackID = TRACK_MAIN;
car->speed=0;
car->dist=0;
car->dist_aux=0;
}
void update_controller( car_t* car ) {
car->speed += get_controller( car->ct );
}
void update_track( track_t* tck, car_t* car ) {
controller_t* ct = car->ct;
struct cfgtrack const* cfg = &tck->cfg.track;
if ( car->trackID == TRACK_MAIN
&& (int)car->dist % cfg->nled_main == cfg->init_aux
&& get_controllerStatus( ct ) == 0 ) {
car->trackID = TRACK_AUX;
car->dist_aux = 0;
}
else if( car->trackID == TRACK_AUX
&& car->dist_aux > cfg->nled_aux ) {
car->trackID = TRACK_MAIN;
car->dist += cfg->nled_aux;
}
/* Update car position in the current track */
if ( car->trackID == TRACK_AUX ) process_aux_track( tck, car );
else if ( car->trackID == TRACK_MAIN ) process_main_track( tck, car );
/* Update car lap */
if ( car->dist > cfg->nled_main*car->nlap ) car->nlap++;
}
void process_aux_track( track_t* tck, car_t* car ){
controller_t* ct = car->ct;
struct cfgtrack const* cfg = &tck->cfg.track;
if ( (int)car->dist_aux == tck->led_speed
&& car->speed <= get_accel ( )
&& ct->flag_sw == 0 ) {
car->speed = get_accel ()*10;
tck->led_speed = 0;
//T_SPEED_COIN = millis() + random(5000,30000);
};
car->speed -= car->speed * cfg->kf;
car->dist_aux += car->speed;
}
void process_main_track( track_t* tck, car_t* car ) {
struct cfgtrack const* cfg = &tck->cfg.track;
const int nled = cfg->nled_main;
const byte* gmap = tck->gmap;
if ( gmap[(word)car->dist % nled] < 127 )
car->speed -= cfg->kg*(127-( gmap[(word)car->dist % nled]) );
if ( gmap[(word)car->dist % nled] > 127 )
car->speed += cfg->kg*(( gmap[(word)car->dist % nled])-127 );
car->speed -= car->speed * cfg->kf;
car->dist += car->speed;
}
void init_ramp( track_t* tck ) {
struct cfgtrack const* cfg = &tck->cfg.track;
byte* gmap = tck->gmap;
for( int i=0; i<cfg->nled_main; i++ ) {
gmap[i] = 127;
}
}
void set_ramp( track_t* tck ) {
struct cfgramp const* r = &tck->cfg.ramp;
for( int i=0; i<(r->center - r->init); i++ )
tck->gmap[r->init+i] = 127-i*((float)r->high/(r->center - r->init));
tck->gmap[r->center] = 127;
for( int i=0; i<(r->end - r->center); i++ )
tck->gmap[r->center+i+1] = 127+r->high-i*((float)r->high/(r->end-r->center));
}
void reset_carPosition( car_t* car) {
car->trackID = TRACK_MAIN;
car->speed = 0;
car->dist = 0;
car->dist_aux = 0;
car->nlap = 1;
car->leaving = false;
}
int track_configure( track_t* tck, int init_box ) {
struct cfgtrack* cfg = &tck->cfg.track;
if( init_box >= cfg->nled_main ) return -1;
cfg->nled_main = ( init_box == 0 ) ? cfg->nled_total : init_box;
cfg->nled_aux = ( init_box == 0 ) ? 0 : cfg->nled_total - init_box;
cfg->init_aux = init_box - 1;
return 0;
}
int track_cfgramp( track_t* tck, int center, int high ) {
struct cfgramp* ramp = &tck->cfg.ramp;
if ( center >= tck->cfg.track.nled_main || center <= 0 ) return -1;
ramp->center = center;
ramp->high = high;
return 0;
}

View file

@ -0,0 +1,80 @@
#ifndef _OLR_LIB_h
#define _OLR_LIB_h
#ifdef __cplusplus
extern "C"{
#endif
#include <Arduino.h>
#include <stdint.h>
#include <stdbool.h>
#include "olr-controller.h"
#include "olr-param.h"
enum{
NOT_TRACK = 0,
TRACK_MAIN,
TRACK_AUX,
TRACK_IN,
TRACK_OUT,
NUM_TRACKS,
};
enum status{
CAR_WAITING = 0,
CAR_COMING,
CAR_ENTER,
CAR_RACING,
CAR_LEAVING,
CAR_GO_OUT,
CAR_FINISH
};
typedef struct{
controller_t* ct;
float speed;
float dist;
float dist_aux;
byte nlap;
byte repeats;
uint32_t color;
int trackID;
enum status st;
bool leaving;
}car_t;
typedef struct {
struct cfgparam cfg;
int led_speed; //LED_SPEED_COIN
byte* gmap; //pointer to gravity map
}track_t;
void init_ramp( track_t* tck );
void set_ramp( track_t* tck );
void init_car( car_t* car, controller_t* ct, uint32_t color );
void update_track( track_t* tck, car_t* car );
void update_controller( car_t* car );
void reset_carPosition( car_t* car);
int track_configure( track_t* tck, int init_box );
int track_cfgramp( track_t* tck, int center, int high );
#ifdef __cplusplus
} // extern "C"
#endif
#endif

View file

@ -0,0 +1,21 @@
#include "olr-param.h"
void param_setdefault( struct cfgparam* cfg ) {
cfg->setted = true;
cfg->ramp.init = 90;
cfg->ramp.center = 100;
cfg->ramp.end = 110;
cfg->ramp.high = 12;
cfg->track.nled_total = MAXLED;
cfg->track.nled_main = 300; //240
cfg->track.nled_aux = 0; //60
cfg->track.init_aux = -1; //239
cfg->track.kf = 0.015; //friction constant
cfg->track.kg = 0.003; //gravity constant
}

View file

@ -0,0 +1,59 @@
#ifndef _OLR_SERIAL_LIB_h
#define _OLR_SERIAL_LIB_h
#ifdef __cplusplus
extern "C"{
#endif
#include "Arduino.h"
#include <stdint.h>
#include <stdbool.h>
#define MAXLED 240+60 // 466 MAX LEDs actives on strip
enum{
LEN_UID = 16,
CFG_VER = 2,
};
// ramp centred in LED 100 with 10 led fordward and 10 backguard
struct cfgtrack {
int nled_total;
int nled_main;
int nled_aux;
int init_aux;
float kf;
float kg;
};
// ramp centred in LED 100 with 10 led fordward and 10 backguard
struct cfgramp {
int init;
int center;
int end;
int high;
};
struct brdinfo {
char uid[LEN_UID + 1];
};
struct cfgparam {
bool setted;
struct cfgtrack track;
struct cfgramp ramp;
struct brdinfo info;
};
void param_setdefault( struct cfgparam* cfg );
#ifdef __cplusplus
} // extern "C"
#endif
#endif

46
lib/README Normal file
View file

@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html

18
platformio.ini Normal file
View file

@ -0,0 +1,18 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:nanoatmega328]
platform = atmelavr
board = nanoatmega328
framework = arduino
;library options
lib_deps =
Adafruit NeoPixel@>=1.2.3

631
src/open-led-race.ino Normal file
View file

@ -0,0 +1,631 @@
/*
* ____ _ ______ _____ _____
/ __ \ | | | ____| __ \ | __ \
| | | |_ __ ___ _ __ | | | |__ | | | | | |__) |__ _ ___ ___
| | | | '_ \ / _ \ '_ \ | | | __| | | | | | _ // _` |/ __/ _ \
| |__| | |_) | __/ | | | | |____| |____| |__| | | | \ \ (_| | (_| __/
\____/| .__/ \___|_| |_| |______|______|_____/ |_| \_\__,_|\___\___|
| |
|_|
Open LED Race
An minimalist cars race for LED strip
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.
by gbarbarov@singulardevices.com for Arduino day Seville 2019
Code made dirty and fast, next improvements in:
https://github.com/gbarbarov/led-race
*/
#include <Adafruit_NeoPixel.h>
#include <EEPROM.h>
#include "AsyncSerialLib.h"
#include "olr-lib.h"
#include "olr-param.h"
#define PIN_LED A0 // R 500 ohms to DI pin for WS2812 and WS2813, for WS2813 BI pin of first LED to GND , CAP 1000 uF to VCC 5v/GND,power supplie 5V 2A
#define PIN_AUDIO 3 // through CAP 2uf to speaker 8 ohms
#define EOL '\n'
#define COLOR1 track.Color(255,0,0)
#define COLOR2 track.Color(0,255,0)
//int LED_SPEED_COIN =-1;
enum{
NUM_CARS = 2,
};
enum loglevel{
ECHO = 0,
DISABLE = 0,
DEBUG,
WARNING,
ERROR
};
enum resp{
NOK = -1,
NOTHING = 0,
OK = 1
};
typedef struct ack{
enum resp rp;
char type;
}ack_t;
struct cfgrace{
bool startline;
int nlap;
int nrepeat;
bool finishline;
};
struct cfgcircuit{
int outtunnel;
};
enum phases{
IDLE = 0,
CONFIG,
CONFIG_OK,
READY,
COUNTDOWN,
RACING,
PAUSE,
RESUME,
COMPLETE,
RACE_PHASES
};
struct race{
struct cfgrace cfg;
struct cfgcircuit circ;
bool newcfg;
enum phases phase;
};
/*------------------------------------------------------*/
enum loglevel verbose = DEBUG;
static struct race race;
static car_t cars[ NUM_CARS ];
static controller_t switchs[ NUM_CARS ];
static byte gravity_map[ MAXLED ];
static track_t tck;
static int const eeadrInfo = 0;
char cmd[32];
char txbuff[64];
const int dataLength = 32;
byte data[dataLength];
unsigned long int T_SPEED_COIN;
static unsigned long lastmillis = 0;
int win_music[] = {
2637, 2637, 0, 2637,
0, 2093, 2637, 0,
3136
};
int TBEEP=3;
char const version[] = "0.9";
char tracksID[ NUM_TRACKS ][2] ={"U","M","B","I","O"};
/* ----------- Function prototypes ------------------- */
void sendresponse( ack_t *ack);
ack_t parseCommands(AsyncSerial &serial);
void printdebug( const char * msg, int errlevel );
void print_cars_positions( car_t* cars);
void run_racecycle( void );
AsyncSerial asyncSerial(data, dataLength,
[](AsyncSerial& sender) { ack_t ack = parseCommands( sender ); sendresponse( &ack ); }
);
Adafruit_NeoPixel track = Adafruit_NeoPixel( MAXLED, PIN_LED, NEO_GRB + NEO_KHZ800 );
void init_track( track_t* tck ){
param_load( &tck->cfg );
tck->gmap = gravity_map;
init_ramp( tck );
tck->led_speed = -1;
}
void setup() {
Serial.begin(115200);
setup_controller( );
init_track( &tck );
init_car( &cars[0], &switchs[0], COLOR1 );
init_car( &cars[1], &switchs[1], COLOR2 );
init_controller( &switchs[0], DEBUG_MODE, PIN_P1 );
init_controller( &switchs[1], DEBUG_MODE, PIN_P2 );
track.begin();
if ( digitalRead(PIN_P1) == 0 ) { //push switch 1 on reset for activate physic
set_ramp( &tck );
draw_ramp( &tck );
track.show();
}
race.phase = READY;
race.cfg.startline = true;
race.cfg.nlap = 5;
race.cfg.nrepeat = 1;
race.cfg.finishline = true;
}
void loop() {
asyncSerial.AsyncRecieve();
if ( race.phase == CONFIG ) {
if( race.newcfg ) {
race.newcfg = false;
race.phase = READY;
send_phase( race.phase );
}
}
else if ( race.phase == READY ) {
for( int i = 0; i < NUM_CARS; ++i) {
reset_carPosition( &cars[i] );
cars[i].repeats = 0;
}
race.phase = COUNTDOWN;
send_phase( race.phase );
}
else if( race.phase == COUNTDOWN ) {
if( race.cfg.startline ){
start_race( &tck );
T_SPEED_COIN = millis() + random(5000,30000);
for( int i = 0; i < NUM_CARS; ++i ) {
cars[i].st = CAR_ENTER;
}
race.phase = RACING;
send_phase( race.phase );
}
}
else if( race.phase == RACING ) {
strip_clear( &tck );
if( tck.led_speed > 0 )
draw_coin( &tck );
else if( millis() > T_SPEED_COIN )
tck.led_speed = random( 20, tck.cfg.track.nled_aux - 20 );
for( int i = 0; i < NUM_CARS; ++i ) {
run_racecycle( &cars[i], i );
if( cars[i].st == CAR_FINISH ) {
race.phase = COMPLETE;
send_phase( race.phase );
}
}
track.show();
/* Print p command!!! */
unsigned long nowmillis = millis();
if( abs( nowmillis - lastmillis ) > 100 ){
lastmillis = nowmillis;
print_cars_positions( cars );
}
/* ---------------- */
}
else if( race.phase == COMPLETE ) {
if ( race.cfg.finishline )
winner_fx( );
race.phase = READY;
}
}
void send_phase( int phase ) {
Serial.print( "R" );
Serial.print( phase );
Serial.print( EOL );
}
void run_racecycle( car_t *car, int i ) {
struct cfgtrack const* cfg = &tck.cfg.track;
if( car->st == CAR_ENTER ) {
reset_carPosition( car );
if( car->repeats < race.cfg.nrepeat )
car->st = CAR_RACING;
else
car->st = CAR_GO_OUT;
}
if( car->st == CAR_RACING ) {
update_track( &tck, car );
update_controller( car );
draw_car( &tck, car );
if( car->nlap == race.cfg.nlap
&& !car->leaving
&& car->dist > ( cfg->nled_main*car->nlap - race.circ.outtunnel ) ) {
car->leaving = true;
car->st = CAR_LEAVING;
}
if( car->nlap > race.cfg.nlap ) {
++car->repeats;
car->st = CAR_GO_OUT;
}
if( car->repeats >= race.cfg.nrepeat
&& race.cfg.finishline ) {
car->st = CAR_FINISH;
}
}
if ( car->st == CAR_FINISH ){
car->trackID = NOT_TRACK;
sprintf( txbuff, "w%d%c", i + 1, EOL );
Serial.print( txbuff );init_ramp( &tck );
}
}
int get_relative_position( car_t* car ) {
enum{
MIN_RPOS = 0,
MAX_RPOS = 99,
};
struct cfgtrack const* cfg = &tck.cfg.track;
int trackdist = 0;
int pos = 0;
switch ( car->trackID ){
case TRACK_MAIN:
trackdist = (int)car->dist % cfg->nled_main;
pos = map(trackdist, 0, cfg->nled_main -1, MIN_RPOS, MAX_RPOS);
break;
case TRACK_AUX:
trackdist = (int)car->dist_aux;
pos = map(trackdist, 0, cfg->nled_aux -1, MIN_RPOS, MAX_RPOS);
break;
}
return pos;
}
void print_cars_positions( car_t* cars ) {
bool outallcar = true;
for( int i = 0; i < NUM_CARS; ++i)
outallcar &= cars[i].st == CAR_WAITING;
if ( outallcar ) return;
for( int i = 0; i < NUM_CARS; ++i ) {
int const rpos = get_relative_position( &cars[i] );
sprintf( txbuff, "p%d%s%d,%d%c", i + 1, tracksID[cars[i].trackID], cars[i].nlap, rpos, EOL );
Serial.print( txbuff );
}
}
void start_race( track_t* tck ) {
struct cfgtrack const* cfg = &tck->cfg.track;
for(int i=0; i < cfg->nled_main; i++)
track.setPixelColor(i,0);
track.show();
delay(2000);
track.setPixelColor(12, track.Color(0,255,0));
track.setPixelColor(11, track.Color(0,255,0));
track.show();
tone(PIN_AUDIO,400);
delay(2000);
noTone(PIN_AUDIO);
track.setPixelColor(12, track.Color(0,0,0));
track.setPixelColor(11, track.Color(0,0,0));
track.setPixelColor(10, track.Color(255,255,0));
track.setPixelColor(9, track.Color(255,255,0));
track.show();
tone(PIN_AUDIO,600);
delay(2000);
noTone(PIN_AUDIO);
track.setPixelColor(9, track.Color(0,0,0));
track.setPixelColor(10, track.Color(0,0,0));
track.setPixelColor(8, track.Color(255,0,0));
track.setPixelColor(7, track.Color(255,0,0));
track.show();
tone(PIN_AUDIO,1200);
delay(2000);
noTone(PIN_AUDIO);
}
void winner_fx() {
int const msize = sizeof(win_music) / sizeof(int);
for (int note = 0; note < msize; note++) {
tone(PIN_AUDIO, win_music[note],200);
delay(230);
noTone(PIN_AUDIO);
}
}
void strip_clear( track_t* tck ) {
struct cfgtrack const* cfg = &tck->cfg.track;
for( int i=0; i < cfg->nled_main; i++)
track.setPixelColor( i, track.Color(0,0,0) );
for( int i=0; i < cfg->nled_aux; i++)
track.setPixelColor( cfg->nled_main+i, track.Color(0,0,0) );
}
void draw_coin( track_t* tck ) {
struct cfgtrack const* cfg = &tck->cfg.track;
track.setPixelColor( 1 + cfg->nled_main + tck->led_speed, track.Color(0,0,250) );
}
void draw_car( track_t* tck, car_t* car ) {
struct cfgtrack const* cfg = &tck->cfg.track;
switch ( car->trackID ){
case TRACK_MAIN:
track.setPixelColor( ((word)car->dist % cfg->nled_main),car->color );
track.setPixelColor( ((word)car->dist % cfg->nled_main)+1, car->color);
break;
case TRACK_AUX:
track.setPixelColor( (word)(cfg->nled_main + car->dist_aux), car->color);
track.setPixelColor( (word)(cfg->nled_main + car->dist_aux)+1, car->color);
break;
}
}
void draw_ramp( track_t* tck ) {
struct cfgtrack const* cfg = &tck->cfg.track;
for(int i=0; i< cfg->nled_main; i++)
track.setPixelColor(i, track.Color(0,0,(127-tck->gmap[i])/8) );
}
void printdebug( const char * msg, int errlevel ) {
char header[4];
sprintf( header, "!%d,", errlevel );
Serial.print( header );
Serial.print( msg );
Serial.print( EOL );
}
ack_t parseCommands(AsyncSerial &serial) {
ack_t ack = { .rp = NOK, .type = '\0' };
memcpy(&cmd, serial.GetContent(), serial.GetContentLength());
if ( ECHO ) //VERBOSE ECHO
printdebug( cmd, DEBUG );
if( cmd[0] == '#' ) {
ack.type = cmd[0];
Serial.print("#");
Serial.print( EOL );
ack.rp = NOTHING;
}
else if( cmd[0] == 'R' ) {
ack.type = cmd[0];
const int phase = atoi( cmd + 1);
if( 0 > phase || RACE_PHASES <= phase) return ack;
race.phase = (enum phases) phase;
ack.rp = OK;
if ( verbose >= DEBUG ) { //VERBOSE
sprintf( txbuff, "%s %d", "RACE PHASE: ", race.phase);
printdebug( txbuff, DEBUG );
}
}
else if( cmd[0] == 'C' ) { //Parse race configuration -> C1.2.3.0
struct cfgrace cfg;
ack.type = cmd[0];
char * pch = strtok (cmd,"C");
if( !pch ) return ack;
pch = strtok (pch, "," );
if( !pch ) return ack;
cfg.startline = atoi( pch );
pch = strtok (NULL, ",");
if( !pch ) return ack;
cfg.nlap = atoi( pch );
pch = strtok (NULL, ",");
if( !pch ) return ack;
cfg.nrepeat = atoi( pch );
pch = strtok (NULL, ",");
if( !pch ) return ack;
cfg.finishline = atoi( pch );
race.cfg = cfg;
race.newcfg = true;
ack.rp = OK;
if ( verbose >= DEBUG ) { //VERBOSE
sprintf( txbuff, "%s %d, %d, %d, %d", "RACE CONFIG: ",
race.cfg.startline,
race.cfg.nlap,
race.cfg.nrepeat,
race.cfg.finishline );
printdebug( txbuff, DEBUG );
}
}
else if( cmd[0] == 'T' ) { //Parse track configuration -> T1,2
ack.type = cmd[0];
char * pch = strtok (cmd,"T");
if( !pch ) return ack;
pch = strtok (pch, "," );
if( !pch ) return ack;
int init_aux = atoi( pch );
pch = strtok (NULL, ",");
if( !pch ) return ack;
int none = atoi( pch );
int err = track_configure( &tck, init_aux );
if( err ) return ack;
EEPROM.put( eeadrInfo, tck.cfg );
ack.rp = OK;
if ( verbose >= DEBUG ) { //VERBOSE
struct cfgtrack const* cfg = &tck.cfg.track;
sprintf( txbuff, "%s %d, %d, %d, %d", "TRACK CONFIG: ",
cfg->nled_total,
cfg->nled_main,
cfg->nled_aux,
cfg->init_aux );
printdebug( txbuff, DEBUG );
}
}
else if( cmd[0] == 'P' ) { //Parse ramp configuration -> T1,2
ack.type = cmd[0];
char * pch = strtok (cmd,"R");
if( !pch ) return ack;
pch = strtok (pch, "," );
if( !pch ) return ack;
int center = atoi( pch );
pch = strtok (NULL, ",");
if( !pch ) return ack;
int high = atoi( pch );
int err = track_cfgramp( &tck, center, high );
if( err ) return ack;
EEPROM.put( eeadrInfo, tck.cfg );
set_ramp( &tck );
ack.rp = OK;
if ( verbose >= DEBUG ) { //VERBOSE
struct cfgramp const* cfg = &tck.cfg.ramp;
sprintf( txbuff, "%s %d, %d, %d, %d", "RAMP CONFIG: ",
cfg->init,
cfg->center,
cfg->end,
cfg->high );
printdebug( txbuff, DEBUG );
}
}
else if( cmd[0] == 'D') {
ack.type = cmd[0];
param_setdefault( &tck.cfg );
EEPROM.put( eeadrInfo, tck.cfg );
sprintf( txbuff, "%s", "Load default" );
printdebug( txbuff, DEBUG );
ack.rp = OK;
}
else if( cmd[0] == ':' ) { // Set board Unique Id
struct brdinfo* info = &tck.cfg.info;
ack.type = cmd[0];
if( strlen(cmd + 1) > LEN_UID ) return ack;
strcpy( info->uid, cmd + 1 );
EEPROM.put( eeadrInfo, tck.cfg );
ack.rp = OK;
if ( verbose >= DEBUG ) { //VERBOSE
sprintf( txbuff, "%s %s", "UID: ", tck.cfg.info.uid );
printdebug( txbuff, DEBUG );
}
}
else if( cmd[0] == '$' ) { // Get Board UID
sprintf( txbuff, "%s%s%c", "$", tck.cfg.info.uid, EOL );
Serial.print( txbuff );
ack.rp = NOTHING;
}
else if( cmd[0] == '%' ) { // Get Software Version
sprintf( txbuff, "%s%s%c", "%", version, EOL );
Serial.print( txbuff );
ack.rp = NOTHING;
}
else if( cmd[0] == 'Q' ) { // Get configuration Info
struct cfgparam const* cfg = &tck.cfg;
sprintf( txbuff, "%s:%d,%d,%d,%d%c", "TCFG ",
cfg->track.nled_total,
cfg->track.nled_main,
cfg->track.nled_aux,
cfg->track.init_aux,
EOL );
Serial.print( txbuff );
sprintf( txbuff, "%s:%d,%d,%d,%d%c", "RCFG: ",
cfg->ramp.init,
cfg->ramp.center,
cfg->ramp.end,
cfg->ramp.high,
EOL );
Serial.print( txbuff );
ack.rp = NOTHING;
}
return ack;
}
void sendresponse( ack_t *ack) {
if( ack->rp == OK ) {
Serial.print( ack->type );
Serial.print("OK");
Serial.print( EOL );
}
else if( ack->rp == NOK ) {
Serial.print( ack->type );
Serial.print("NOK");
Serial.print( EOL );
}
memset( &cmd, '\0' , sizeof(cmd) );
}
void param_load( struct cfgparam* cfg ) {
int cfgversion;
int eeAdress = eeadrInfo;
EEPROM.get( eeAdress, tck.cfg );
eeAdress += sizeof( cfgparam );
EEPROM.get( eeAdress, cfgversion );
if ( cfgversion != CFG_VER ) {
param_setdefault( &tck.cfg );
eeAdress = 0;
EEPROM.put( eeAdress, tck.cfg );
eeAdress += sizeof( cfgparam );
EEPROM.put( eeAdress, CFG_VER );
Serial.print("LOAD DEFAULT\n");
}
}

11
test/README Normal file
View file

@ -0,0 +1,11 @@
This directory is intended for PIO Unit Testing and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html