👁 1019 | Tristan Schulze lately updated this on Mai 21, 2022
0
Arduino basic code for two sensors
/*
* This sketch uses both visual distance sensors to send key data via USB keyboard
*
* */
#include "Keyboard.h" // reference to keyboard lib
int keycodes[] = {48,49,50,51,52,53,54,55,56,57}; // key map for all keys from 0 to 9
int dist_sensor_pin = 0; // Sharp IR GP2Y0A41SK0F (4-30cm, analog)
int ldr_sensor_pin = 0; // Sharp IR GP2Y0A41SK0F (4-30cm, analog)
float smoothed_distance = 0;
int distance = 0;
int ldr_threshold = 5; // value used as trigger edge for ldr sensor
bool is_triggered = false;
void setup() {
Keyboard.begin(); // intialize Leonardo as a generic keyboard
}
void loop() {
int brightness = analogRead(ldr_sensor_pin)/1024; // read brightness value from LDR sensor
float volts = analogRead(dist_sensor_pin)*0.0048828125; // value from sensor * (5/1024)
distance = 13*pow(volts, -1); // worked out from datasheet graph
distance = constrain(distance, 4, 30);// for reliability : limit all incoming data to range of 4-30
// !!! SMOOTHING calculation for distance sensor
int smooth_amount = 10;
smoothed_distance = smoothed_distance + ((distance - smoothed_distance)/smooth_amount);
float mapped_distance = map(smoothed_distance, 4, 30, 0, 10);
if(brightness<ldr_threshold && is_triggered == false ){
// send keyboard data
Keyboard.write( keycodes[ int(mapped_distance) ] ); // send keycode to computer
//set catching bool to avoid multiple triggering
is_triggered = true;
}
// make triggerable again when sensor is light again
if(brightness>ldr_threshold){
is_triggered = false;
}
delay(10); //tiny delay for stability
}