Well I've mashed this together and it appears to do what I want but is it well written? How should it be written?
Note: There is a bit of code in the 'void loop()' to form a square wave oscillator.
Note 2: I'm trying to create a single period using timer1. These periods are between 432uS and 3.7mS in size and are to control one of the digital pins.
// Arduino timer CTC interrupt example
//
// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>
#define LEDPIN 13
#define pulse 7
int grad = 4;
int b = OCR1A;
long previousMillis = 0;
long interval = 1000;
unsigned long currentMillis = millis();
int ledState = LOW;
void setup()
{
Serial.begin(9600);
pinMode(pulse, OUTPUT);
digitalWrite(pulse, LOW);
pinMode(LEDPIN, OUTPUT);
digitalWrite(LEDPIN, LOW);
attachInterrupt(0, start_timer, FALLING);
}
void loop()
{
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis; // save the last time you blinked the LED
if (ledState == LOW)// if the LED is off turn it on and vice-versa:
ledState = HIGH;
else
ledState = LOW;
digitalWrite(pulse, ledState); // set the LED with the ledState of the variable:
}
}
void start_timer()
{
digitalWrite(LEDPIN, HIGH);
cli(); // disable global interrupts
TCNT1 = 0;
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
OCR1A = 62; //3.7 mS
//OCR1A = 11; //432 mS
TCCR1B |= (1 << WGM12); // turn on CTC mode:
TCCR1B |= (1 << CS10); // Set CS10 and CS12 bits for 1024 prescaler:
TCCR1B |= (1 << CS12);
TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt:
sei(); // enable global interrupts:
}
ISR(TIMER1_COMPA_vect)
{
digitalWrite(LEDPIN, LOW);
}
Many thanks for any help.