Page 119

PWM colours breadboard layout

Page 120

const int RED_PIN = 11; const int GREEN_PIN = 5; const int BLUE_PIN = 6; void setup() { pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); } void loop() {     setColour(255, 0, 0); // red //setColour(0, 255, 0); // green //setColour(0, 0, 255); // blue //setColour(255,255,255); // white (well blueish white) delay(1000); setColour(0, 0, 0); //off delay(1000); } void setColour(byte red, byte green, byte blue) { analogWrite(RED_PIN, red); analogWrite(GREEN_PIN, green); analogWrite(BLUE_PIN, blue); }

Page 122

const int DIG_RED_PIN = 7; const int MSECS_ON = 250; // 25% of 1,000 const int MS_SEC = 1000; void setup() { pinMode(DIG_RED_PIN, OUTPUT); } void loop() { digitalWrite(DIG_RED_PIN, HIGH); delayMicroseconds(MSECS_ON); digitalWrite(DIG_RED_PIN, LOW); delayMicroseconds(MS_SEC - MSECS_ON); }

Page 123

void setup() { pinMode(LED_BUILTIN, OUTPUT); // setup the LED pin noInterrupts(); // disable all interrupts TCCR1A = 0; // Timer control register TCCR1B = 0; // bit twiddling to set signal division and mode TCNT1 = 3036; // Set counter to start value 65536 - (16Mhz / 256) TCCR1B |= (1 << CS12); // 256 prescaler TIMSK1 |= (1 << TOIE1); // set timer overflow interrupt interrupts(); // re-enable interrupts } ISR(TIMER1_OVF_vect){ TCNT1 = 3036; // reset timer for 1 sec blink then toggle LED digitalWrite(LED_BUILTIN, digitalRead(LED_BUILTIN) ^ 1); } void loop() { }

Page 124

void setup() { pinMode(LED_BUILTIN, OUTPUT); // setup the LED pin noInterrupts(); // disable all interrupts TCCR1A = 0; // Timer control register TCCR1B = 0; TCNT1 = 0; // Zero timer counter register for Timer1 // now the register bit twiddling OCR1A = 62500; // Set the compare match register for 1Hz TCCR1B |= (1 << WGM12); // CTC mode TCCR1B |= (1 << CS12); // 256 prescaler TIMSK1 |= (1 << OCIE1A); // set timer compare interrupt interrupts(); // re-enable all interrupts } // An output compare interrupt on Timer1 calls this ISR ISR(TIMER1_COMPA_vect){ // timer compare interrupt service routine digitalWrite(LED_BUILTIN, digitalRead(LED_BUILTIN) ^ 1); // toggle LED } void loop() { }

Page 125

void setup() { pinMode(LED_BUILTIN, OUTPUT); // setup the LED pin noInterrupts(); // disable all interrupts TCCR2A = 0; // Timer control register TCCR2B = 0; TCNT2 = 0; // Set counter to 0 OCR2A = 240; //Compare match register TCCR2A |= (1 << WGM21); // CTC Mode TCCR2B |= (1 << CS22) | (1 << CS20) | (1 << CS21); // max prescaler TIMSK2 |= (1 << OCIE2A); // set timer compare interrupt interrupts(); // re-enable interrupts } ISR(TIMER2_COMPA_vect){ digitalWrite(LED_BUILTIN, digitalRead(LED_BUILTIN) ^ 1); }