nerdegutta.no
PIC - Toggle an LED using a Hall Effect Sensor
02.05.24
Embedded
Here's a little C program for a PIC microcontroller that toggles an LED based on input from a hall effect sensor:
#include
#define _XTAL_FREQ 8000000 // Set your oscillator frequency
// Configuration settings
#pragma config FOSC = HS // Oscillator Selection bits (HS oscillator)
#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = OFF // Brown-out Reset Enable bit (BOR disabled)
#pragma config LVP = OFF // Low-Voltage Programming Enable bit (RB3/PGM pin has digital I/O function; HV on MCLR must be used for programming)
#define HALL_SENSOR RB0 // Hall effect sensor connected to RB0 pin
#define LED RB1 // LED connected to RB1 pin
void main() {
TRISB0 = 1; // Set RB0 pin as input (Hall effect sensor)
TRISB1 = 0; // Set RB1 pin as output (LED)
while(1) {
if (HALL_SENSOR == 1) { // If the sensor detects a magnetic field
LED = !LED; // Toggle the LED
__delay_ms(100); // Delay for debouncing
}
}
}
This program assumes that the Hall effect sensor is connected to pin RB0 and the LED is connected to pin RB1 of the PIC microcontroller. Adjust the pin configurations (`TRISB0`, `TRISB1`) according to your actual hardware setup. The program continuously checks the status of the hall effect sensor, and when it detects a magnetic field, it toggles the LED. The `__delay_ms()` function is used for debouncing the sensor input.