Hello Paul,
I noticed that my teensy gets stuck if analogRead() is called at high rate in the main loop() while analogRead() (on a different pin, with different variables) was called in an interrupt callback. This can be solved by deactivating interrupts temporarily around the analogRead() of the main loop… But is this behavior normal ?
Here is some testing code (type 'g' in the serial monitor to start and stop the interrupt)
I noticed that my teensy gets stuck if analogRead() is called at high rate in the main loop() while analogRead() (on a different pin, with different variables) was called in an interrupt callback. This can be solved by deactivating interrupts temporarily around the analogRead() of the main loop… But is this behavior normal ?
Here is some testing code (type 'g' in the serial monitor to start and stop the interrupt)
Code:
#define EMG_PIN_1 A1
#define EMG_SAMPLE 'g'
#define EMG_SAMPLE_PERIOD 1000
#define BUFSIZE 64
volatile uint16_t emg1_buffer[BUFSIZE];
volatile uint32_t emg_time_buffer[BUFSIZE];
volatile uint8_t head=0;
volatile uint8_t tail=0;
IntervalTimer timer0;
volatile unsigned long emg_ref_time=0;
void emg_callback(void)
{
uint8_t next_head = (head + 1) % BUFSIZE;
if (next_head != tail) {
/* there is room */
emg1_buffer[head]=analogRead(EMG_PIN_1);
emg_time_buffer[head]=micros()-emg_ref_time;
head = next_head;
}
}
void setup()
{
Serial.begin(115200);
Serial.flush();
analogReadRes(16);
analogReadAveraging(8);
pinMode(13,OUTPUT);
}
void loop()
{
byte c=' ';
if (Serial.available()>0)
{
c = Serial.read();
}
static boolean sampling=false;
if (c==EMG_SAMPLE)
{
if (sampling)
{
sampling=false;
timer0.end();
digitalWrite(13,LOW);
}
else
{
emg_ref_time=micros();
timer0.begin(emg_callback,EMG_SAMPLE_PERIOD);
sampling=true;
digitalWrite(13,HIGH);
}
}
//**********COMMENT THIS PART TO REMOVE PROBLEM
//**********OR UNCOMMENT CLI() AND SEI()
static uint32_t k=0;
if (sampling)
{
k++;
}
if ((k>10000) && (k<50000))
{
//cli();
int a=analogRead(A0);
//sei();
k++;
}
//****************************************
uint16_t e1;
uint32_t t;
boolean data_to_send=false;
cli();
if (head != tail)
{
t=emg_time_buffer[tail];
e1=emg1_buffer[tail];
tail = (tail + 1) % BUFSIZE;
data_to_send=true;
}
sei();
if (data_to_send)
{
Serial.print(t);
Serial.print(",");
Serial.println(e1);
}
}