Advertisement
shapingthings

MPR121 Proximity Distance

Jun 15th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.02 KB | None | 0 0
  1. // touch includes
  2. #include <MPR121.h>
  3. #include <Wire.h>
  4. #define MPR121_ADDR 0x5A
  5. #define MPR121_INT 4
  6.  
  7. // mapping and filter definitions
  8. #define LOW_DIFF 0
  9. #define HIGH_DIFF 10
  10. #define filterWeight 0.3f // 0.0f to 1.0f - higher value = more smoothing
  11. float lastProx = 0;
  12.  
  13. // the electrode to monitor for proximity
  14. #define PROX_ELECTRODE 0
  15.  
  16. // define LED_BUILTIN for older versions of Arduino
  17. #ifndef LED_BUILTIN
  18. #define LED_BUILTIN 13
  19. #endif
  20.  
  21. void setup() {
  22.   Serial.begin(57600);
  23.  
  24.   pinMode(LED_BUILTIN, OUTPUT);
  25.  
  26.   if (!MPR121.begin(MPR121_ADDR)) Serial.println("error setting up MPR121");
  27.   MPR121.setInterruptPin(MPR121_INT);
  28.  
  29.   MPR121.setRegister(MPR121_NHDF, 0x01); //noise half delta (falling)
  30.   MPR121.setRegister(MPR121_FDLF, 0x3F); //filter delay limit (falling)
  31. }
  32.  
  33. void loop() {
  34.   readTouchInputs();
  35. }
  36.  
  37. void readTouchInputs() {
  38.  
  39.   MPR121.updateAll();
  40.  
  41.   // only make an action if we have one or fewer pins touched
  42.   // ignore multiple touches
  43.  
  44.   for (int i = 1; i < 12; i++) { // Check which electrodes were pressed
  45.     if (MPR121.isNewTouch(i)) {
  46.  
  47.       //pin i was just touched
  48.       Serial.print("pin ");
  49.       Serial.print(i);
  50.       Serial.println(" was just touched");
  51.       digitalWrite(LED_BUILTIN, HIGH);
  52.     } else {
  53.       if (MPR121.isNewRelease(i)) {
  54.         Serial.print("pin ");
  55.         Serial.print(i);
  56.         Serial.println(" is no longer being touched");
  57.         digitalWrite(LED_BUILTIN, LOW);
  58.       }
  59.     }
  60.   }
  61.  
  62.   // read the difference between the measured baseline and the measured continuous data
  63.   int reading = MPR121.getBaselineData(PROX_ELECTRODE) - MPR121.getFilteredData(PROX_ELECTRODE);
  64.  
  65.  // Serial.print("Proximity electrode: ");
  66.  // Serial.println(reading);
  67.  
  68.   unsigned int prox = constrain(reading, LOW_DIFF, HIGH_DIFF);
  69.   lastProx = (filterWeight * lastProx) + ((1 - filterWeight) * (float)prox);
  70.   uint8_t thisOutput = (uint8_t)map(lastProx, LOW_DIFF, HIGH_DIFF, 0, 254);
  71.  
  72.   Serial.println(thisOutput);
  73.   analogWrite(9, thisOutput);
  74.  
  75.   //delay(10);
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement