Hi, just posting some progress on the current control project, I've gotten all my functionality into the attiny as far as blinking, fade in-fade out, strobe, etc. some fun stuff, I was working on figuring out how to digitally do what I was doing with the op amps and RC's in software and decided to write a base 2 running average algorithm, the goal being speed, code below, feel free to tear it apart haha. I haven't written it into a class yet, just wrote it in the main arduino loop to proof it out. so far it works well on the scope, the finished code will have a maximum current that can't ever be exceeded without going into shutdown mode, but the running average threshold will be lower, basically a "slow blow" fuse. the maximum current trigger will be tested every roughly 100uS, on the ADC interrupt, so any screwdrivers across the terminals will result in 100uS or less of the mosfet driving screwdriver current until it is shut down...
C++:
byte runningAverage[32]; //the buffer for samples
byte currentAverage; //the current average (runningSum >> 5)
volatile byte count;
unsigned int runningSum;
byte counter;
byte counterA;
void setup() {
for (byte i=0; i<31; i++)
runningAverage[i] = 0;
DDRB = 0b00000010;
TCCR1 = 0b01100111;
OCR1C = 0xFF;
OCR1A = 0x20;
TIMSK = 0b01000110;
ADMUX = 0b00100011;
ADCSRA = 0b11101111;
ADCSRB &= 0b11111000;
counter = 0;
counterA = 1;
}
void loop() {
}
ISR (TIMER1_OVF_vect){
}
ISR (TIMER1_COMPA_vect){
}
ISR (ADC_vect){
count++;
if (count == 255){
//OCR1A = ADCH;
count = 0;
takeSample(ADCH);
}
}
//this method should store the sample in the array adds the sample to the running sum, and subtract
//the n-32 term from the running sum
void takeSample(byte sample){
runningAverage[counter] = sample; //store the sample in the buffer
runningSum += sample; //add the sample to the running sum
runningSum -= runningAverage[counterA]; //subtract the oldest sample from the running sum
counter++;
if (counter >= 32)
counter >>= 5;
counterA++;
if (counterA >= 32)
counterA >>= 5;
currentAverage = (runningSum >> 5) & 0xFF; //divide sum by 32 to get average
OCR1A = currentAverage;
}