I am using a PIC12F675 microcontroller with the MPLAB X IDE. I am trying to detect the state of a machine by monitoring an LED with a photoresistor. I have the circuit working such that when the machine's LED is on, my chip is getting the input and turning on an LED of its own to match. I am not using interrupts right now, but instead just polling constantly for the input from the photoresistor circuit.
The two possible states for the LED, when the machine is turned on, are BLINKING and ON. It's never just OFF when the machine is powered.
I could use an interrupt but I am getting stuck on the idea of how to wait a certain amount of time while polling. The LED I am monitoring blinks about twice a second. So I would need to watch it for a second and then record it as "OFF" if at any point during that second the pin went low. ( There's a pull-down resistor on the input pin. )
I am not very experienced with C and have only used it for programming small chips like these to do small tasks. Is there some feature or function of C that would be useful for this? Or is there some way in the logic that I'm overlooking? Please help me figure out how to detect a blinking light vs. an ON light.
Here is my code so far:
// PIC12F675 Configuration Bit Settings
// 'C' source line config statements
// CONFIG
#pragma config FOSC = INTRCIO // Oscillator Selection bits (INTOSC oscillator: CLKOUT function on GP4/OSC2/CLKOUT pin, I/O function on GP5/OSC1/CLKIN)
#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT enabled)
#pragma config PWRTE = ON // Power-Up Timer Enable bit (PWRT disabled)
#pragma config MCLRE = OFF // GP3/MCLR pin function select (GP3/MCLR pin function is MCLR)
#pragma config BOREN = OFF // Brown-out Detect Enable bit (BOD enabled)
#pragma config CP = OFF // Code Protection bit (Program Memory code protection is disabled)
#pragma config CPD = OFF // Data Code Protection bit (Data memory code protection is disabled)
#define _XTAL_FREQ 4000000
#include <xc.h>
#include <stdlib.h>
#include <htc.h>
void init_ports(void) {
ANSEL = 0x00; // Set ports as digital IO not analog input.
ADCON0 = 0x00; // Shut off ADC.
CMCON = 0x07; // Shut off comparator.
VRCON = 0x00; // Shut off the voltage reference.
TRISIO = 0xA; // All GPIO pins output except 1&3.
GPIO = 0x00; // Make all pins LOW
T0IE = 0; // Disable timer interrupt.
GPIE = 0; // GPIO port change interrupt
GIE = 0; // Global interrupt for recognition of interrupts.
}
void main(void) {
init_ports();
/* Wait 1 second for power up. */
__delay_ms(1000);
while(1) {
// Check for input on GPIO 1
if (GPIO & 0b000010) {
// Turn on the LED on GPIO 4
GP4 = 1;
}
else{
// Turn off the LED on GPIO 4
GP4 = 0;
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…