Try Embedded

Touch lamp (TTP223)

Switch a lamp on and off with a capacitive touch pad, and dim it with a long touch.

Input · Beginner

In a real product: Touch lamp (Smart home): A capacitive pad switches and dims the lamp.

A touch pad has no moving parts and works through a thin plastic or glass cover, which is why lamps, kettles and lifts use them. The TTP223 chip senses a finger and switches its output like a button.

What you'll learn

  • Reading a touch sensor's digital output
  • Telling a tap from a long touch with millis()
  • Dimming an LED with analogWrite()

How it works

In momentary mode SIG is HIGH while the pad is touched. The chip drives the output itself, so no pull-up is needed. The sketch watches for the moment the touch starts and ends: a short touch toggles the lamp, and while a touch lasts longer than half a second the brightness steps down and wraps round, as many touch lamps do.

Try this

  • Run it and press the pad: tap to switch, hold to dim.
  • Change the pad's mode to "toggle" in its settings: now the chip itself flips its output on each touch. What does the sketch need to change to work with it?
  • Add a second pad that only turns the lamp off.

sketch.ino

// A touch lamp: tap the TTP223 (SIG on 2) to switch the LED on 9, hold it to dim.
const int PAD = 2, LAMP = 9;
const int LEVELS[] = {255, 120, 40};

bool on = false, touching = false, dimmed = false;
int level = 0;
unsigned long touchedAt = 0, lastStep = 0;

void setup() {
  Serial.begin(9600);
  pinMode(PAD, INPUT);
  pinMode(LAMP, OUTPUT);
}

void loop() {
  bool t = digitalRead(PAD) == HIGH;
  if (t && !touching) { touchedAt = millis(); dimmed = false; }
  if (t && on && millis() - touchedAt > 500 && millis() - lastStep > 400) {
    level = (level + 1) % 3;
    lastStep = millis();
    dimmed = true;
    Serial.print("Brightness ");
    Serial.println(LEVELS[level]);
  }
  if (!t && touching && !dimmed) {
    on = !on;
    Serial.println(on ? "On" : "Off");
  }
  touching = t;
  analogWrite(LAMP, on ? LEVELS[level] : 0);
  delay(10);
}

Lessons behind it