volatile int8_t brightness = 128;
void setup() {
//D9 40hz ping signal
//D3 - light PWM pin
//D2 - sound pin driven manually
pinMode(2, OUTPUT);
/**
* URL: https://dbuezas.github.io/arduino-web-timers/#mcu=ATMEGA328P&timer=1&CompareOutputModeA=toggle&OCR1A=50000&clockPrescalerOrSource=8&topValue=OCR1A&CompareOutputModeB=toggle&interruptA=on&OCR1B=2000&interruptB=on
* Mode : CTC
* Period : 25.0005 ms
* Frequency: 39.9992 Hz
* Outputs :
* - B1: 50.00%, toggle
* - B2: 50.00%, toggle
*/
noInterrupts();
TCCR1A = 0x00;
TCCR1B = 0x00;
TCCR1A =
1 << COM1A0 |
1 << COM1B0;
TCCR1B =
1 << WGM12 |
1 << CS11;
TIMSK1 =
1 << OCIE1A |
1 << OCIE1B;
DDRB =
1 << DDB1 |
1 << DDB2;
OCR1A = 50000;
OCR1B = 2000;
//PWM genertor for brightness regulation
/**
* URL: https://dbuezas.github.io/arduino-web-timers/#mcu=ATMEGA328P&timer=2&CompareOutputModeB=clear-up%2C+set-down&OCR2B=128&clockPrescalerOrSource=8
* Mode : PCPWM
* Period : 255 us
* Frequency: 3.92157 kHz
* Outputs :
* - D3: 50.20%, clear-up, set-down
*/
TCCR2A = 0x00;
TCCR2B = 0x00;
TCCR2A =
1 << COM2B1 |
1 << WGM20;
TCCR2B =
1 << CS21;
DDRD =
1 << DDD3;
OCR2B = 0;
interrupts();
}
ISR(TIMER1_COMPA_vect) {
//we need to know the output state to make a beep on the rising edge
//(PINB,1) corresponds to D9
if(bitRead(PINB,1)){
//set D2 high
PORTD = PORTD | B00000100;
//set PWM duty cycle to the brightness level needed
OCR2B = brightness;
}else{
//set PWM duty cycle to 0, thus shutting light off
OCR2B = 0;
}
}
ISR(TIMER1_COMPB_vect) {
//set D2 low
PORTD = PORTD & B11111011;
}
void loop() {
//0-255 value from ADC. We don't need 10 bits
brightness = analogRead(A1) >> 2;
}