Skip to content

Instantly share code, notes, and snippets.

@maxpromer
Created March 18, 2017 09:22
Show Gist options
  • Save maxpromer/c0a6e40a98956012efb165bc171a3ccf to your computer and use it in GitHub Desktop.
Save maxpromer/c0a6e40a98956012efb165bc171a3ccf to your computer and use it in GitHub Desktop.
/*
* File: main.c
* Author: [email protected]
*
* Created on 3/18/2017 8:09:13 AM UTC
* "Created in MPLAB Xpress"
* Full code you can see : https://mplabxpress.microchip.com/mplabcloud/example/details/306
*/
#include <xc.h>
#include "mcc.h"
#include <htc.h>
#define Trig_Pin LATCbits.LATC5
#define Echo_Pin PORTCbits.RC6
unsigned long pulseIn() {
while(Echo_Pin == 0) ;
unsigned long time_t = 0;
while(Echo_Pin == 1) {
__delay_us(1);
time_t++;
}
return time_t;
}
void main(void) {
SYSTEM_Initialize();
TRISA = 0xF0;
TRISCbits.TRISC5 = 0; // Set RC5 to OUTPUT
TRISCbits.TRISC6 = 1; // Set RC6 to INPUT
LATA = 0x01;
while(1) {
Trig_Pin = 0;
__delay_us(5);
Trig_Pin = 1;
__delay_us(10);
Trig_Pin = 0;
unsigned long PulseWidth = pulseIn();
unsigned int distance = PulseWidth * 0.0173681;
distance = distance < 5 ? 0 : (distance > 8 ? 3 : distance - 5);
LATA = 0x01<<(distance);
__delay_ms(100);
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment