Hi everybody,
I am new to teensy and am trying to understand the ADC library. For my application I need to sample two analog channels that represent the currents through a stepper motor coils and track the position of the stepper. Below is a skeleton program that samples two channels continuously.
1. Does the code look reasonable? Any red flags? Any suggestion? I think that ~10k samples/sec should be more than enough.
2. I run built this with Arduino IDE for Teensy 3.2. Will same code work also on Teensy 4.0?
Thanks
Z.
I am new to teensy and am trying to understand the ADC library. For my application I need to sample two analog channels that represent the currents through a stepper motor coils and track the position of the stepper. Below is a skeleton program that samples two channels continuously.
1. Does the code look reasonable? Any red flags? Any suggestion? I think that ~10k samples/sec should be more than enough.
2. I run built this with Arduino IDE for Teensy 3.2. Will same code work also on Teensy 4.0?
Thanks
Z.
Code:
// Skeleton program for reading two input analog channels.
#include <stdio.h>
#include <ADC.h>
const int adcPin1 = A9;
const int adcPin2 = A3;
ADC *adc = new ADC();
elapsedMicros time;
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(adcPin1, INPUT);
pinMode(adcPin2, INPUT);
adc->setReference(ADC_REFERENCE::REF_3V3, ADC_0);
adc->setReference(ADC_REFERENCE::REF_3V3, ADC_1);
adc->setAveraging(4, ADC_0);
adc->setAveraging(4, ADC_1);
adc->setResolution(12, ADC_0);
adc->setResolution(12, ADC_1);
adc->setConversionSpeed(ADC_CONVERSION_SPEED::MED_SPEED, ADC_0);
adc->setConversionSpeed(ADC_CONVERSION_SPEED::MED_SPEED, ADC_1);
adc->setSamplingSpeed(ADC_SAMPLING_SPEED::MED_SPEED, ADC_0);
adc->setSamplingSpeed(ADC_SAMPLING_SPEED::MED_SPEED, ADC_1);
// We use adc0_isr to read also adc1.
adc->enableInterrupts(ADC_0);
// NOTE: this return a error status if pins are not supported.
adc->startSynchronizedContinuous(adcPin1, adcPin2);
delay(100);
}
// TODO: should these be volaitile?
int isr_count = 0;
ADC::Sync_result result;
void loop() {
// Take a snapshot of isr values and reset isr_count
int _isr_count;
ADC::Sync_result _result;
__disable_irq();
{
_isr_count = isr_count;
_result = result;
isr_count = 0;
}
__enable_irq();
// Print snapshot
char buffer[60];
sprintf(buffer, "%d %5d %5d", _isr_count, _result.result_adc0, _result.result_adc1);
Serial.println(buffer);
adc->printError(); // Print adc errors, if any
digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN));
delay(1000);
}
void adc0_isr(void) {
isr_count++;
// NOTE: if sampling 16 bits, need t clear the high
// 16 bits of result's fields to undo the 16 bit to 32 bit sign extension.
result = adc->readSynchronizedContinuous();
// TODO: insert stepper position tracking here.
}