// Basic FIR filter
// -----------------------------------------
// This implements a low-pass filter with cutoff frequency fc=150Hz @ fs=1kHz
// The impulse response is at coeffs.h.
//
// WARNING!!!!!!!!!!!!!!!!!!!!!!
// This example illustrates the basic sampling-oriented FIR implementation
// but it is inefficient due to improper sampling-time approach.
// For correct sampling time see a sampling-oriented FIR implementation
// using timer interrupts.
//
// (c) 2024 Jorge Iván Marín ([email protected])
#include <SPI.h>
#define ADC_IN 36
#define DAC_OUT 25
#define CS_DAC 5
// Driver for DAC TLC5616
// ----------------------
class TLC5616 {
int CS_pin;
public:
TLC5616(int _CS_pin) {
CS_pin = _CS_pin;
}
void begin(void) {
SPI.begin();
pinMode(CS_pin, OUTPUT);
digitalWrite(CS_pin, HIGH);
}
void write(uint16_t value) {
value = (value & 0x3ff) << 2;
digitalWrite(CS_pin, LOW);
SPI.beginTransaction(SPISettings(20000000, MSBFIRST, SPI_MODE0));
SPI.transfer16(value);
SPI.endTransaction();
digitalWrite(CS_pin, HIGH);
}
};
// Digital Filtering
// ------------------------------------------------
#include "coeffs.h"
float x[Nh];
float filter(float x_ADC) {
int k;
float y;
x[0] = x_ADC;
//Compute convolution
y = 0;
for(k=0; k<Nh; k++) {
y += h[k]*x[k];
}
//Delay elements in the array x
for(k=Nh-1; k>0; k--) {
x[k] = x[k-1];
}
return y;
}
// Función para medir el tiempo de muestreo del filtro
int tiempo_muestreo(int x_in) {
unsigned long time_start, time_end;
int y;
time_start = micros(); // Tiempo antes de aplicar el filtro
y = filter(x_in); // Aplicación del filtro
time_end = micros(); // Tiempo después
Serial.println(time_end - time_start); // Tiempo en microsegundos
return y; // Retornamos la salida filtrada
}
// Entry point
// ----------------
TLC5616 dac(CS_DAC);
void setup() {
Serial.begin(115200);
//DAC Initialization
dac.begin();
// For internal DAC initialization replaces the above line by
// (Note: Not supported in Wowki):
// analogReadResolution(12);
// pinMode(DAC_OUT, OUTPUT);
}
void loop() {
//ADC read (Note: ADC is 12-bit resolution)
int x = analogRead(ADC_IN);
//Perform filtering con medición de tiempo
int y = tiempo_muestreo(x);
//DAC Write (Note: DAC is 10-bit resolution, so we need to scale down)
dac.write(y >> 2);
//For internal DAC replaces the above line by
// dacWrite(DAC1, y>>4);
// Delay until next sampling time
delayMicroseconds(1000);
}