TMR0 as a counter, declaring new variables, enumerated constants, using relay ...
Referring to the previous examples, the microcontroller executes the program without being affected in any way by its surrounding. Practically, devices operating in this manner are very rare (for example, simple neon sign controller). Input pins are also used in this example. There is a schematic in figure below, while the program is on the next page. It’s still very simple. Timer TMR0 is used as a counter. The counter input is connected to a push button so that any button press causes timer TMR0 to count one pulse. When the number of pulses matches the number stored in the TEST register, a logic one (5V) appears on the pin PORTD.3. This voltage activates an electromechanical relay, and this bit is called ‘RELAY’ in the program, therefore. In this example, the TEST register stores number 5. Of course, it can be any number obtained either by computing or defined as a constant. Besides, the microcontroller can activate some other device instead of relay, while the sensor can be used instead of the push button. This example illustrates one of the most common applications of the microcontroller in the industry; when something is performed as many times as needed, then something else should be turned on or off..../*Header******************************************************/ void main() { char TEST = 5; // Constant TEST = 5 enum outputs {RELAY = 3}; // Constant RELAY = 3 ANSEL = 0; // All I/O pins are configured as digital ANSELH = 0; PORTA = 0; // Reset port A TRISA = 0xFF; // All portA pins are configured as inputs PORTD = 0; // Reset port D TRISD = 0b11110111; // Pin RD3 is configured as an output, while the rest are // configured as inputs OPTION_REG.F5 = 1; // Counter TMR0 receives pulses through the RA4 pin OPTION_REG.F3 = 1; // Prescaler rate is 1:1 TMR0 = 0; // Reset timer/counter TMR0 do { if (TMR0 == TEST) // Does the number in timer match constant TEST? (PORTD.RELAY = 1); // Numbers match. Set the RD3 bit (output RELAY) } while (1); // Remain in endless loop
enum outputs {RELAY = 3}; // Constant RELAY = 3If several port D pins are connected to relays, the expression above could be written in this way as well:
enum outputs {RELE = 3, HEATER, MOTOR = 6, PUMP};All the constants, following those with assigned values (RELAY = 3 and MOTOR = 6), are automatically assigned values incremented by 1 relative to the previous constant value. In this example, constants HEATER and PUMP will be assigned values 4 and 7, respectively (HEATER = 4 and PUMP = 7).