#define ADC_PIN 34
// 每次触发记录数据个数
#define LEN 5000
// 触发电压,以ADC值计
#define TRIGGER 1000
// 采样频率,Hz
#define FREQ 10000
hw_timer_t* timer = NULL;
static void IRAM_ATTR Timer0_CallBack(void);
short calibrate(short val);
short writeBuf[LEN], outBuf[LEN];
short lastVolte = 0;
int len = 0;
bool triggering = false, dataReady = false;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
// 采用80MHz PLL时钟,进行分频后得到1MHz的时钟
timer = timerBegin(0, 80, true);
timerAttachInterrupt(timer, Timer0_CallBack, true);
timerAlarmWrite(timer, 1000000 / FREQ, true);
timerAlarmEnable(timer);
}
void loop() {
// put your main code here, to run repeatedly:
if (dataReady) {
dataReady = false;
// 拷贝数据,防止被记录过程干扰,顺便进行校准
for (int i = 0; i < LEN; i++) {
outBuf[i] = calibrate(writeBuf[i]);
}
for (int i = 0; i < LEN; i++) {
Serial.println(outBuf[i]);
}
}
}
short calibrate(short val) {
// TODO: 根据真实值和ADC的系统误差校正出正确的电压,可以用查表法
return val;
}
static void IRAM_ATTR Timer0_CallBack(void) {
// 读取电压
register int volte = analogRead(ADC_PIN);
if (triggering) {
// 触发模式下直接记录数据
writeBuf[len++] = volte;
if (len == LEN) {
len = 0;
dataReady = true;
triggering = false;
}
} else if (lastVolte < TRIGGER && volte >= TRIGGER) {
// 检测触发条件时开始记录
triggering = true;
}
lastVolte = volte;
}