When trying to use the timer1 interrupt *and* digiUSB, digiUSB doesn't work any more (in the loop it prints only one line - see code). Without using a timer1 interrupt, digiUSB alone works. The timer1 interrupt works in both cases. Some time ago i read in some forum about a new version of the digiUSB library compatible with timer1 interrupts, but the link to it was not valid. Unfortunately i can't find it again.
Does anybody know a link to a digiUSB library which does not perturb/is not perturbed by the timer1 interrupt?
This is the code:
#define useTimer1 true //to verify digiUSB, set useTimer1 false
#include <DigiUSB.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#define adc_p2 1
#define outPin 0
#define ledPin 1 //LED on Model A or Pro
volatile int y, u, w=500, p=100, a=500, ct=0, dt=1000;
static inline void initTimer1(void)
{
TCCR1 |= (1 << CTC1); // clear timer on compare match
TCCR1 |= (1 << CS13) | (1 << CS12) | (1 << CS11); //clock prescaler 8192
OCR1C = 255; // compare match value
TIMSK |= (1 << OCIE1A); // enable compare match interrupt
}
ISR(TIMER1_COMPA_vect)
{
int ct1 = millis();
y = analogRead(adc_p2); if(y<1) y=1; if(y>999) y=999;
u = control(y);
analogWrite(outPin, u/4);
digitalWrite(ledPin, digitalRead(ledPin) ^ 1); //toggle LED
ct1 = ct1 - millis();
ct = ct1;
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(outPin, OUTPUT);
DigiUSB.begin();
DigiUSB.println();
if (useTimer1) {
initTimer1(); // initialize timer registers
sei(); // enable interrupts
}
}
void loop() {
DigiUSB.print(millis()/100);
DigiUSB.print('\t');
DigiUSB.println(ct);
if (dt>0) DigiUSB.delay(dt);
else DigiUSB.refresh();
}
int control(int y) {
int out;
if (p<=0) out = a;
else out = int(100.0*float(w-y)/float(p)) + a;
if(out<0) out=0; if(out>999) out=999;
return out;
}