This commit is contained in:
Alex Alvarado
2022-05-10 11:46:53 +02:00
commit ce25af73ab
8 changed files with 291 additions and 0 deletions

5
.gitignore vendored Normal file
View File

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

10
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}

38
include/I2C_COM_API.hpp Normal file
View File

@ -0,0 +1,38 @@
// Comandos del cronómetro
enum ChronoCommands
{
ForceStart = 0x01, // Forzar inicio
ForceStop = 0x02, // Forzar detención
ForceReset = 0x04 // Forcer reinicio del cronómetro
};
// Modos de operación del dispositivo
enum DeviceModes
{
CHRONO = 0x00 // Modo Cronómetro
};
// Estructura para un comando de la API sin datos
struct ChronoAPICommand
{
const static char type = 0xAA; // Cabecera de Comando
ChronoCommands command; // Comando solicitado
};
// Unión genérica para serializar y des-serializar tipos
template <typename T>
union buffer
{
T data;
uint8_t buffer[sizeof(T)];
};
// Función para enviar un buffer por I2C
template <typename T>
void SendBuffer(buffer<T> buffer)
{
Wire.flush();
Wire.beginTransmission(0x26);
Wire.write(buffer.buffer, sizeof(T));
Wire.endTransmission();
}

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

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

25
platformio.ini Normal file
View File

@ -0,0 +1,25 @@
; 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:attiny85]
platform = atmelavr
board = attiny85
board_build.f_cpu =8000000L
framework = arduino
upload_protocol=stk500v1
upload_port = /dev/ttyUSB1
upload_speed = 19200
upload_flags =
-b$UPLOAD_SPEED
-P$UPLOAD_PORT
#lib_deps = nickcengel/TinyWireSio@0.0.0-alpha+sha.722ada4382

117
src/main.cpp Normal file
View File

@ -0,0 +1,117 @@
/*
* Firmware de cronómetro con detector laser
* Este firmware permite detectar el tiempo transcurrido en
* milésimas de segundo des de que se interrumpe
*/
#include <Arduino.h>
#include <Wire.h>
#include <avr/interrupt.h>
#include <avr/iotn85.h>
#undef F_CPU
#define F_CPU 8000000
#include "I2C_COM_API.hpp"
#define I2C_SLAVE_ADDR 0x26
#define LDR_START PCINT1
#define LDR_STOP PCINT3
uint8_t master_data[16];
uint8_t master_data_length;
buffer<long> ms; // Buffer donde se almacena el valor del cronómetro
bool started = false; // Flag que indica si el cronómetro está iniciado
long reference = 0; // Variable de referencia para calcular el incremento de tiempo
DeviceModes mode = CHRONO;
// Responder a solicitudes I2C
void requestHandler()
{
switch (mode)
{
case CHRONO: // En modo cronómetro o por defecto, enviar buffer de tiempo.
default:
#warning Workarround para el problema de la función millis
buffer<long> ms2 = ms;
ms2.data *= 2;
SendBuffer(ms2);
break;
}
}
void receiveHandler(int length)
{
for (uint8_t i = 0; i < length; i++)
master_data[i] = Wire.read();
// El mensaje es un comando de cronómetro
//if (master_data[0] == ChronoAPICommand::type)
//{
// switch ((ChronoCommands)master_data)
// {
// case (ChronoCommands::ForceStart):
// started = true;
// break;
// case (ChronoCommands::ForceStop):
// started = false;
// break;
// case (ChronoCommands::ForceReset):
// reference = millis();
// break;
// }
//}
}
// Vector INT0 para detectar interrupciones
ISR(PCINT0_vect)
{
bool strt = !digitalRead(LDR_START); // Invert start signal read
bool stop = digitalRead(LDR_STOP);
if (started)
{
// El cronómetro está en marcha y se detecta
// la condición de parada
if (stop)
started = false;
}
else
{
// El cronómetro está parado y se detecta
// la condición de inicio
if (strt)
{
reference = millis();
started = true;
}
}
}
void setup()
{
// Resetear todas las salidas
PORTB = 0x00;
// Iniciar el bus I2C
Wire.begin(I2C_SLAVE_ADDR);
Wire.onReceive(receiveHandler);
Wire.onRequest(requestHandler);
// Poner los pines del comparador en modo entrada
pinMode(LDR_START, INPUT);
pinMode(LDR_STOP, INPUT);
// Configurar registros para habilitar las interrupciones
cli();
MCUCR |= 0b00000001; // Interrumpir con cualquier cambio de nivel
GIMSK |= (1 << PCIE); // Activar PCINT (Pin Change Interrupt)
PCMSK |= (1 << PCINT1 | 1 << PCINT3); // Habilitar interrupción para los pines de la LDR
sei();
}
void loop()
{
if (started) // Si el cronómetro está funcionando:
ms.data = millis() - reference; // Actualizar marca de tiempo
delay(1); // Darle tiempo al attiny para que se haga un café
}

11
test/README Normal file
View File

@ -0,0 +1,11 @@
This directory is intended for PlatformIO 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 PlatformIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html