ADC Arduino Arduino UNO BlueSMiRF Bluetooth IR snesor RFCOMM RoboRemo level indicator Sharp sensor analogRead calibration distance display distance meter distance sensor
// Measure distance with a Sharp IR sensor
// send the value via Bluetooth to RoboRemo app
// www.roboremo.app
// Hardware setup:
// BlueSMiRF Arduino
// GND ------- GND
// VCC ------- 5V
// TX-O ------ RX
// RX-I ------ TX
#define bluetooth Serial
// Sharp Arduino
// GND ------- GND
// VCC ------- 5V
// out ------- pinA0
int sharpPin = A0;
// 4cm 5cm 6cm 7cm 8cm 9cm 10cm 11cm 12cm 13cm 14cm 15cm
int calib[] = {562, 476, 405, 349, 310, 276, 248, 224, 205, 190, 178, 166};
int minDist = 40; // mm
int distance(int adcVal) { // returns distance in mm
int calibLen = sizeof(calib)/2;
int res = 0;
if(adcVal>calib[0]) return 0; // if dist < minDist
if(adcVal<calib[calibLen-1]) return minDist + (calibLen-1)*10; // (max)
for(int i=0; i<calibLen-1; i++) {
int a = calib[i];
int b = calib[i+1];
int distA = minDist + i*10;
int distB = minDist + (i+1)*10;
if(adcVal<=a && adcVal>=b)
res = map(adcVal, b, a, distB, distA);
}
return res;
}
char cmd[100];
int cmdIndex;
void exeCmd() {
//if(strcmp(cmd, "some cmd")==0) doSomething();
}
void setup() {
delay(500); // wait for BlueSMiRF to start
bluetooth.begin(115200); // BlueSMiRF default baud is 115200
pinMode(sharpPin, INPUT);
cmdIndex = 0;
}
void loop() {
if(bluetooth.available()) {
char c = (char)bluetooth.read();
if(c=='\n') {
cmd[cmdIndex] = 0;
exeCmd(); // execute the command
cmdIndex = 0; // reset the cmdIndex
} else {
cmd[cmdIndex] = c;
if(cmdIndex<99) cmdIndex++;
}
}
// 32-sample average, to elliminate noise:
int sharpADC = 0;
for(int i=0; i<32; i++) {
sharpADC += analogRead(sharpPin);
delay(1);
}
sharpADC = sharpADC / 32;
String st = (String)"raw " + sharpADC + "\n";
st = st + "dist " + distance(sharpADC) + "\n";
bluetooth.print(st);
delay(100);
}