床屋行ったので書いてみた
timerone ライブラリを使用しているので、gitからダウンロードしてね
/*
50Hz meas
use lib :
github.com/PaulStoffregen/TimerOne.git
1/50Hz = 0.02 (1 period)
0.02 / 100 =0.0002 =200u ( 100 sample = 1 period)
*/
#include <TimerOne.h>
#define SAMPLE_SZ 100
#define SAMPLE_PERIOD 200 // us
#define BLOCK_SZ 50
#define BLOCK_SZ_INV (1.0/50.0)
int sample_buf[SAMPLE_SZ];
int sample_buf_p;
int sample_buf_ready;
void isr_timer1() {
int data;
if( sample_buf_p < SAMPLE_SZ ){
data = analogRead(0); // wait for ADC
sample_buf[ sample_buf_p ] = data;
sample_buf_p++;
}
if( sample_buf_p == SAMPLE_SZ ){
sample_buf_ready = 1;
sample_buf_p++;
}
}
void setup() {
Serial.begin(9600);
sample_buf_p = 0;
sample_buf_ready = 0;
Timer1.initialize(SAMPLE_PERIOD); // unit=usec
Timer1.attachInterrupt(isr_timer1);
}
void loop() {
int i,j; int data;
int max; int min;
float sum; float avr;
float val;
sum = 0;
for (j = 0; j < BLOCK_SZ; j++) {
while( sample_buf_ready == 0 ) ;
max = 0;
min = 32767;
for (i = 0; i < SAMPLE_SZ; i++) {
data = sample_buf[i];
if (max < data) max = data;
if (min > data) min = data;
}
sample_buf_p = 0;
sample_buf_ready = 0;
sum += ( max - min );
}
avr = sum * BLOCK_SZ_INV; // outer loop sz
val = avr * (5000.0 / 1024.0) / 2.0 / sqrt(2) * 10.0 - 500.0;
Serial.println(val);
}