Problem with Timer on particle P1

Hello,
I am using particle P1. in my code i am using D2, D3, P1S0, P1S1 as PWM pins and also using TIMER6 with SparkIntervalTimer library. on library page i found that Allocating a hardware timer will disable PWM capabilities to certain pins based on the timer allocated. but TIMER6 and TIMER7 is not allocated to any pin. but problem is when code is running it will become hang somewhere. is that PWM pins i am using creating problem with timer6? also another problem when i set timer6 to < 50msec it stops displaying serial log? am i missing some point? anyone can lead me towards problem?

@tejasvini, neither TIMER6 or TIMER7 shouldn't cause interference. However, when you say:

Do you do any logging in the TIMER ISR? Can you post your ISR code?

@peekay123, No i am not using serial log in ISR. just normal adc read and storing it. here is my ISR code.

void IsrForTimer()
{
  Inf.Volt = (ADCRead(ADC_READ_PIN1) * MUL_TO_GET_ACTUAL_VOLT);
  Inf.ActualVolt = (Inf.Volt + PACK_DISCHARGE_VOLTAGE_OFFSET);
  PackAvg.addValue(Inf.ActualVolt);    // adding value to buffer for averaging
  Inf.AvgCnt++;

  if(Inf.AvgCnt == 10)
  {
    Inf.Current = (ADCRead(_ADC2) * MUL_TO_GET_ACTUAL_CURRENT);
    CurrentAvg.addValue(Inf.Current);
    Inf.AvgCnt = 0;
    
    Sensor1Avg.addValue((sensorTh1.read()) / 10);		// temperature sensor read and add to buffer
    Sensor2Avg.addValue((sensorTh2.read()) / 10);
    
  }

  Inf.TestVolt = (ADCRead(VOLT_READ_PIN) * MUL_TO_GET_ACTUAL_TEST_VOLT);
  TestAvg.addValue(Inf.TestVolt);
}

You are calling multiple functions we can’t see, so any of these could cause the crash.
Especially the sensorXXX.read() calls seem problematic.

1 Like

@ScruffR @peekay123 , i just spent some more time on that troubleshooting and landed with issue that in code at one place i am reading analog pin. when code is executing that line and before it finished analogread(pin) if interrupt is triggered (now i changed my timer with software timers based on freeRtos) then it will execute timer ISR but after that it will not return to execute main loop for few seconds or minutes and just receives timer INT at regular interval and after that few seconds it will resume main loop execution but stops timer? can anyone have this kind of problem?

@tejasvini, you are doing a lot of calculations in the ISR. Personally, I like to keep ISR code small with as few calculations as possible. In your case, I would suggest having the ISR simply read raw ADC values and queuing them in a FIFO or circular buffer. You then do your dequeing and calculations in loop().

As for your issue, the ADC is not a “protected” resource so if you interrupt and do ADC reads while loop() is doing an ADC read, I am not sure what will happen. Normally, you should make the ADC read in loop() ATOMIC so it can’t be interrupted.

2 Likes

@peekay123, thanks for your response. ATOMIC have solved the problem.

2 Likes