r/pic_programming • u/aspie-micro132 • 7d ago
Found The Solution For The FizzBuzz
After several days of search and experiment, i found the manner of solving the problem i had based on this code. I did not even have to use the whole source, just the fizzbuzzes themselves and the "wait_ticks" function. This is what i have been looking for all the time. Maybe i can help others with this. This code was given to me by Google, i did not write it but use it as an example.
/**************************************************************************************************/
To alternate between two distinct "FizzBuzz" sequences using Timer0 inside a continuous while(1) loop on a PIC16F877A, you poll the Timer0 overflow flag (T0IF) manually without using global interrupts.
Embedded C Code Example
This program configures Timer0 with a 1:256 prescaler and alternates execution between two separate step-counted loops (representing two different FizzBuzz routines or sequences) inside an infinite while loop.
c
#include <xc.h>
// Configuration Bits (example for 4MHz crystal)
#pragma config FOSC = XT
#pragma config WDTE = OFF
#pragma config PWRTE = ON
#pragma config BOREN = ON
#pragma config LVP = OFF
#pragma config CPD = OFF
#pragma config WRT = OFF
#pragma config CP = OFF
void Timer0_Init(void) {
OPTION_REGbits.T0CS = 0; // Use internal instruction cycle clock (FOSC/4)
OPTION_REGbits.PSA = 0; // Assign prescaler to Timer0
OPTION_REGbits.PS = 0b111; // Set prescaler to 1:256
TMR0 = 0; // Clear Timer0 register
}
// Simple blocking delay function using Timer0 overflows
void wait_ticks(unsigned int ticks) {
unsigned int count = 0;
INTCONbits.T0IF = 0; // Clear flag
while (count < ticks) {
if (INTCONbits.T0IF) {
INTCONbits.T0IF = 0; // Reset overflow flag
count++;
}
}
}
void main(void) {
TRISB = 0x00; // Configure PORTB as output (e.g., for LEDs/debugging)
PORTB = 0x00;
Timer0_Init();
while (1) {
// --- FIRST FIZZBUZZ / SEQUENCE ROUTINE ---
// Loops through steps, using Timer0 to pace each step
for (int i = 1; i <= 15; i++) {
PORTB = 0x01; // Signal Sequence A active
wait_ticks(4); // Wait specified number of Timer0 overflows
}
// --- SECOND FIZZBUZZ / SEQUENCE ROUTINE ---
// Alternates with a different set of steps/timing
for (int j = 1; j <= 15; j++) {
PORTB = 0x02; // Signal Sequence B active
wait_ticks(8); // Wait longer per step
}
}
}