2

I'm using an Arduino Nano with a capacitive touch sensor and a potentiometer. I'm trying to get my code to differentiate between three different program states.

  • One is when my touch sensor is NOT being touched.
  • Two is when my touch sensor IS being touched.
  • And three is when my touch sensor is being touched AND a potentiometer is being moved at the same time.

I'm having trouble picking up the second program state, when I'm simply touching the fader but not moving the potentiometer. Program state 1 works great, but program state 3 activates even when there's no data coming in from the potentioeter.

Here's the code. And ideas?

#include <CapacitiveSensor.h>
#define rxPin 4
#define txPin 1

const byte touchSend = 2;
const byte touchReceive = 7;

byte minimumCp = 200; // Raise if the fader is too sensitive (0-16383)

bool touched = false; //Is the fader currently being touched?

CapacitiveSensor touchSensor = CapacitiveSensor(touchReceive, touchSend);

void setup() {
  touchSensor.set_CS_AutocaL_Millis(0xFFFFFFFF);
  pinMode(rxPin, INPUT );
  pinMode(txPin, OUTPUT); 
  Serial.begin(57600);
}
void loop() {
  int faderPos = analogRead(A7);
  int lastfaderValue;
  int totalCp =  touchSensor.capacitiveSensor(30);
  if (totalCp <= minimumCp) {  // Not Touching Fader
      touched = false;
      Serial.println("Not Touching Fader"); 
      delay(15);}
  if ((faderPos == lastfaderValue) && (totalCp > minimumCp)) { // Touching Fader
      touched = true; 
      Serial.println("Touching Fader, NOT Moving"); 
      delay(15);}
  if ((faderPos != lastfaderValue) && (totalCp > minimumCp)) { // Touching Fader and Moving
      touched = true; 
      Serial.println("Touching Fader, Moving"); 
      delay(15);}
  lastfaderValue = faderPos; }
2
  • Your lastfaderValue is always equal to faderPos.
    – hcheung
    Commented Jun 20, 2021 at 2:05
  • Every time you enter loop you’re comparing the pot input with an arbitrary value that you think is the last pot value, but since it’s local to loop, it isn’t. You may have not intended that to be a local variable. I’d add that you’ll probably want a minimum pot delta as well since simultaneous reads may not report the same value even if it’s not being moved. Commented Jun 20, 2021 at 2:06

1 Answer 1

2

Figured it out.

I had the lastfaderValue integer in the wrong spot. It works when I put it at the beginning of the code (before the setup).

I also added a tolerance, so that the potentiometer can still fluctuate slightly when I'm not touching it.

Works well now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.