new dir struct / added Sound fx

This commit is contained in:
luca 2020-07-15 13:38:08 +02:00
parent 60230e697b
commit c0935700ae
25 changed files with 15 additions and 1086 deletions

View file

@ -1,2 +1,5 @@
# OLR-Arduino
Minimalist race game with an LED strip.
4 Players and Pit Lane Version

View file

@ -1,39 +0,0 @@
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

@ -1,201 +0,0 @@
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

@ -1,392 +0,0 @@
# 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

@ -1,52 +0,0 @@
/***************************************************
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

@ -1,72 +0,0 @@
/***************************************************
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

@ -1,43 +0,0 @@
/***************************************************
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

@ -1,55 +0,0 @@
/***************************************************
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

@ -1,48 +0,0 @@
/***************************************************
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

@ -1,29 +0,0 @@
/***************************************************
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

@ -1,38 +0,0 @@
/***************************************************
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

@ -1,30 +0,0 @@
#######################################
# 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

@ -1,9 +0,0 @@
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

@ -1,46 +0,0 @@
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

View file

@ -98,9 +98,12 @@ struct race{
bool newcfg;
enum phases phase;
byte numcars;
int winner;
int winner;
};
byte SMOTOR=0;
int TBEEP=0;
int FBEEP=0;
/*------------------------------------------------------*/
enum loglevel verbose = DISABLE;
@ -125,7 +128,7 @@ int win_music[] = {
3136
};
int TBEEP=3;
//int TBEEP=3;
char const version[] = "0.9";
char tracksID[ NUM_TRACKS ][2] ={"U","M","B","I","O"};
@ -179,6 +182,10 @@ void setup() {
ramp_init( &tck );
draw_ramp( &tck );
track.show();
delay(1000);
if ( digitalRead( DIG_CONTROL_1 ) == 0 ) { //retain push switch on reset for activate FX sound
SMOTOR=1;
tone(PIN_AUDIO,100);}
}
if ( digitalRead( DIG_CONTROL_2 ) == 0 ) { //push switch 2 on reset for activate boxes
@ -262,6 +269,8 @@ void loop() {
}
track.show();
if (SMOTOR==1) tone(PIN_AUDIO,FBEEP+int(cars[0].speed*440*1)+int(cars[1].speed*440*2)+int(cars[2].speed*440*3)+int(cars[3].speed*440*4));
if (TBEEP>0) {TBEEP--;} else {FBEEP=0;};
/* Print p command!!! */
unsigned long nowmillis = millis();
@ -672,4 +681,4 @@ void param_load( struct cfgparam* cfg ) {
EEPROM.put( eeAdress, CFG_VER );
Serial.print("LOAD DEFAULT\n");
}
}
}

View file

@ -1,18 +0,0 @@
; 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

View file

@ -1,11 +0,0 @@
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