nerdegutta.no
PIC - Toggle an LED using a Hall Effect Sensor
29.12.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 < xc.h > #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 } } }