Skip to content

Instantly share code, notes, and snippets.

@jackgu1988
Created July 8, 2017 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackgu1988/085fb432b1d0005083cbd5570a55d6ab to your computer and use it in GitHub Desktop.
Save jackgu1988/085fb432b1d0005083cbd5570a55d6ab to your computer and use it in GitHub Desktop.
int sensorValue1 = 0;
int sensorValue2 = 0;
boolean s1 = false;
boolean s2 = false;
int sensorValue = 0;
float sensorPressed[] = {0, 0};
float prop = 0;
int sensorMax[] = {0, 0};
const byte acceptableError = 0;
const byte mid = 50;
const byte noiseLen = 30;
boolean pressing = false;
boolean greater;
unsigned long currentTime = 0;
unsigned long endTime = 0;
int pressTime = 0;
void setup() {
Serial.begin(115200);
// turn on LED to signal the start of the calibration period:
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
// calibrate during the first two seconds
while (millis() < 2000) {
sensorValue1 = analogRead(0);
sensorValue2 = analogRead(1);
if (sensorValue1 > sensorMax[0])
sensorMax[0] = sensorValue1;
if (sensorValue2 > sensorMax[1])
sensorMax[1] = sensorValue2;
}
// add acceptable error
for (byte i = 0; i < 2; i++)
sensorMax[i] += acceptableError;
// signal the end of the calibration period
digitalWrite(13, LOW);
}
boolean sensor(byte pin) {
sensorValue = analogRead(pin);
greater = sensorValue > sensorMax[pin];
if (pressing && greater)
sensorPressed[pin] += sensorValue - sensorMax[pin];
return greater;
}
byte findPin() {
if (sensorPressed[0] > mid && sensorPressed[1] > mid) {
if (sensorPressed[0] > sensorPressed[1])
prop = sensorPressed[1] / sensorPressed[0];
else
prop = sensorPressed[0] / sensorPressed[1];
if (prop > 0.4)
return 1;
}
if (sensorPressed[0] > sensorPressed[1])
return 0;
else
return 2;
}
void loop() {
s1 = sensor(0);
s2 = sensor(1);
if (s1 || s2) {
if (!pressing) {
currentTime = millis();
pressing = true;
}
} else if (pressing) {
endTime = millis();
pressTime = endTime - currentTime;
pressing = false;
if (pressTime > noiseLen) {
Serial.print(findPin());
memset(sensorPressed, 0, sizeof(sensorPressed));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment