Got my PIC programmer today at long last, and below is my first program for my 16F628, designed to flash an LED connected to output RA1 at 1Hz...
The circuit at first appears to work - but the frequency of the LED flash is slightly faster than 1Hz. I'm not sure what the exact frequency is, but I measured 48.5 seconds for 50 flashes (1.03 Hz) and then 62 flashes in a minute (1.03 Hz again). The maths is correct according to the datasheet, and I've run the code in a simulator which agrees with me and turns RA1 on and off every second - so where have I gone wrong?
There's no way the code takes an entire second to "reset" after the bit toggling part, so is there something wrong with my 16F628's internal clock? Note that the initial __config sets the chip to use the internal 4MHz oscillator; the source frequency of Timer2 is FOsc/4 = 1MHz.
Help would be much appreciated Merry Christmas/happy holidays to all.
ahydra
Code:
LIST P=16F628
#INCLUDE <P16F628.INC>
__config 0x3D18 ; set up config bits (code protection off etc)
C1 EQU 0x20
ORG 0x00
MAIN
CLRF PORTA
MOVLW 0x07
MOVWF CMCON
BCF STATUS, RP1
BSF STATUS, RP0 ; go to bank 1
MOVLW 0x11
MOVWF TRISA ; A: 4 and 0 as inputs, others out
MOVLW 0x00
MOVWF TRISB ; B: all out
MOVLW d'249'
MOVWF PR2 ; set Timer2 to count up to 250
BCF STATUS, RP0 ; go back to bank 0
MOVLW 0x7E
MOVWF T2CON ; enable timer2 with a prescaler of 16 (postscaler too, but this isn't used)
MOVLW d'125'
MOVWF C1 ; initialise C1
LOOP ; main loop begins here
MOVF TMR2, 0 ; 1000000 / 16 = 62500 hz
BTFSC STATUS, Z ; test zero flag, if not zero goto FLASH
GOTO FLASH
GOTO LOOP
FLASH
; gets to here 62500 / 250 = 250 hz
; so we use C1 to divide by 125, and we get 2Hz
; that is one flash (one on/off sequence) every second
DECF C1, 0
MOVWF C1 ; store C1
MOVWF PORTB ; also copy C1 to port B (debug)
BTFSS STATUS, Z ; test to see if C1 was 0
GOTO LOOP2 ; if it wasn't, go to final loop
MOVLW d'125'
MOVWF C1 ; reset C1
MOVF PORTA, 0 ; read PORTA
XORLW 0x2 ; toggle bit 1
MOVWF PORTA ; write PORTA
LOOP2
MOVF TMR2, 0 ; test tmr2 for non-zero before returning
BTFSS STATUS, Z ; test zero flag, when not zero resume the loop
GOTO LOOP
GOTO LOOP2
END
The circuit at first appears to work - but the frequency of the LED flash is slightly faster than 1Hz. I'm not sure what the exact frequency is, but I measured 48.5 seconds for 50 flashes (1.03 Hz) and then 62 flashes in a minute (1.03 Hz again). The maths is correct according to the datasheet, and I've run the code in a simulator which agrees with me and turns RA1 on and off every second - so where have I gone wrong?
There's no way the code takes an entire second to "reset" after the bit toggling part, so is there something wrong with my 16F628's internal clock? Note that the initial __config sets the chip to use the internal 4MHz oscillator; the source frequency of Timer2 is FOsc/4 = 1MHz.
Help would be much appreciated Merry Christmas/happy holidays to all.
ahydra
Last edited: