-
Notifications
You must be signed in to change notification settings - Fork 0
tutorial IR distance sensor
How can objects be real if your sensors aren't real?
This tutorial is one of two that covers the following sensors:
- IR line sensor
- IR distance sensor
This sensor needs the following header files to access the relevant functions.
#include "RASLib/inc/common.h"
#include "RASLib/inc/adc.h"
Add the following declarations to it:
static tADC *adc[4];
static tBoolean initialized = false;
Now we should make two functions, an initializer and then a demo. For your final robot, you should call the initializer and then run your own method to grab the IR sensor data.
The initializer should set four pins on the GPIO for ADC input. Let's call the initializer initIRSensor.
void initIRSensor(void){
//we don't want to accidentally reinitialize the GPIO pins again
if(initialized)
return;
initialized = true;
//set four pins for ADC input - you can use these 4 I/O pins or select your own
adc[0] = InitializeADC(PIN_D0);
adc[1] = InitializeADC(PIN_D1);
adc[2] = InitializeADC(PIN_D2);
adc[3] = InitializeADC(PIN_D3);
}
You can find a full list of pins to use at the GPIO pins page.
Next is testing the distance sensor. Let's write a demo function IRSensorDemo. This demo should read in the values of the distance sensor indefinitely until the user stops it with a keypress.
void IRSensorDemo(void){
Printf("Press any key to quit\n");
//loop until key is pressed
while(!KeyWasPressed()){
To read from the distance sensor, we can use the function ADCRead(); It takes in one address of an initialized pin and returns a float distance. Since we initialized the adc[] variable, we use each index as the parameter.
Printf(
"IR values: %1.3f, %1.3f, %1.3f, %1.3f\r",
ADCRead(adc[0]),
ADCRead(adc[1]),
ADCRead(adc[2]),
ADCRead(adc[3])
);
}
Printf("\n");
}
Now you should be able to call both these methods in your main and run it on your robot! Here's the full code for the IR Distance Sensor:
#include "RASLib/inc/common.h"
#include "RASLib/inc/adc.h"
static tADC *adc[4];
static tBoolean initialized = false;
void initIRSensor(void){
//we don't want to accidentally reinitialize the GPIO pins again
if(initialized)
return;
initialized = true;
//set four pins for ADC input - you can use these 4 I/O pins or select your own
adc[0] = InitializeADC(PIN_D0);
adc[1] = InitializeADC(PIN_D1);
adc[2] = InitializeADC(PIN_D2);
adc[3] = InitializeADC(PIN_D3);
}
void IRSensorDemo(void){
Printf("Press any key to quit\n");
//loop until key is pressed
while(!KeyWasPressed()){
Printf(
"IR values: %1.3f, %1.3f, %1.3f, %1.3f\r",
ADCRead(adc[0]),
ADCRead(adc[1]),
ADCRead(adc[2]),
ADCRead(adc[3])
);
}
Printf("\n");