TMR0 as a counter, declare new variables, use symbols, use a relay ...
In the previous two examples the microcontroller executes the program without being affected by its surrounding. Practically, microcontroller-based devices operating in this manner are very rare (for example, a simple neon sign controller). Input pins are also used in this example. The schematic is given 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 in such a way that any button pressure causes the TMR0 timer to count one pulse. When the number of pulses matches the number stored in the TEST register, a logic one (5V) will appear on the PORTD.3 pin. This voltage is used to activate an electromechanical relay, and this bit is therefore called ‘RELAY’ in the program. Here, 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 run some other device instead of relay, while a 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 required, then something else should be turned on or off....' Header****************************************************** program example_3 ' Program name symbol RELAY = PORTD.3 ' Pin PORTD.3 is named RELAY dim TEST as byte ' Variable TEST is of byte type main: ' Start of program TEST = 5 ' Constant TEST = 5 ANSEL = 0 ' All I/O pins are configured as digital ANSELH = 0 PORTA = 0 ' Reset PORTA TRISA = 0xFF ' All portA pins are configured as inputs PORTD = 0 ' Reset PORTD TRISD = %11110111 ' Pin RD3 is configured as an output, while other pins are ' configured as inputs OPTION_REG.5 = 1 ' Counter TMR0 receives pulses through the RA4 pin OPTION_REG.3 = 1 ' Prescaler rate is 1:1 TMR0 = 0 ' Reset timer/counter TMR0 while 1 if TMR0 = TEST then ' Does the number in timer match constant TEST? RELAY = 1 ' Numbers match. Set the RD3 bit (output RELAY) end if wend ' Remain in endless loop end. ' End of programOnly one symbol (RELAY) is used here. It is assigned the third pin of PORTD in declaration.
symbol RELAY = PORTD.3 ' Symbol RELAY = PORTD.3If several port D pins are connected to relays, the expression above could be written in this way as well: