Interrupt

Hi
I want to measure with an interrupt every 20ms the CO2-sensor and every second the O2-sensor.
I’ve created a Timer1.attachInterrupt (measure, 1000000) and a methode measure, but I do not know what I put into this method or how I write it.

#include <TimerOne.h>
#include <SDP6x.h>

#include <SoftwareSerial.h>
#include <Wire.h>

char buf[50];
int state = 0;
float difPressure;
String co2wert;
String o2wert;
int i = 0;
float dt = 0.06;
float volumen = 0;
float pres1 = 0;
float pres2 = 0;
float dif = 0;
int n = 0;
float avolumen = 0;
int l = 0;
float flow = 0.0;




SoftwareSerial co2Serial(2, 3);
SoftwareSerial o2Serial(4, 5);

void setup() {

  Timer1.initialize(20000);
  Serial.begin(9600);
  co2Serial.begin(9600);
  o2Serial.begin(9600);
  Wire.begin();
  difPressure = 0.0;

  Timer1.initialize(1000000); // 1 sec
  Timer1.attachInterrupt(measure, 1000000);

}

void measure(){
  
}

Let's show us the actual and complete code please. Plus links to the used libraries.

It looks like you try to read these sensors using SoftwareSerial. Forget to do that in interrupt context as you would do with your current approach. SoftwareSerial depends on interrupts itself (so in interrupt context where interrupts are disabled, it won't work) but blocks everything during it's byte transfers. It's a crippled piece of software that you should only use if you really have no other choice.

You do know that with 9600 baud you get about 20 characters over a serial interface within 20ms in best case, don't you?

kim_x:
I want to measure with an interrupt every 20ms the CO2-sensor

20 millisecs is a very long time for an Arduino. I can't see any need to use interrupts. Just use millis() as illustrated in Several Things at a Time. The same technique can be used with micros() if you need more precision.

...R

As pylon said, SoftwareSerial bogarts interrupts. If you're bent on using it, try my github page where I placed three hacked versions that deal exclusively with one port only so interrupts are left alone on the other two. Look for SSerialB, C or D. Also remember that SoftwareSerial only allows you to read from a single port. The documentation says a single port at a time but I've never gotten it to work on multiple instances. At least my butchered versions allow it to co-exist with other interrupt driven peripherals, it now works with PinChangeInt and EnableInterrupt.

If you still want to be interrupt driven at 20ms intervals, best to use the watchdog timer and sleep in between.