Model Railroad Controller

The PWM runs from 28Hz on low speed to 100Hz on high speed. The PWM is controlled via an interrupt function that is called every 32 microseconds.

Exported from Notepad++
// Set timer2 TIMSK2 = (TIMSK2 & B11111110) | 0x01; TCCR2B = (TCCR2B & B11111000) | 0x01; // Timer overflow interrupt is called every 32us for now ISR(TIMER2_OVF_vect) { //Much quicker alternative than digitalWrite if (pwmCounterA < pulseWidthCounter[speedA]) PORTD |= B10000000; else PORTD &= B01111111; if (pwmCounterA >= periodCounter[speedA]) pwmCounterA = 0; else pwmCounterA += 1; //Much quicker alternative than digitalWrite if (pwmCounterB < pulseWidthCounter[speedB]) PORTD |= B01000000; else PORTD &= B10111111; if (pwmCounterB >= periodCounter[speedB]) pwmCounterB = 0; else pwmCounterB += 1; }

The first part is used in setup(), the second part contains the code that creates the PWM. The variables pulseWidthCounter and periodCounter are arrays which contain values per speed and can be filled with other values, based on the PWM mode. The PWM values are calculated with the excell sheet.