fbpixel
Creating a lamp with a touch-sensitive switch

Creating a lamp with a touch-sensitive switch

One application of capacitive sensors is the creation of a tactile switch to turn on a lamp, for example. In this project, we’re going to design a capacitive sensor with Arduino that we’ll use as a tactile switch to turn a lamp on and off.

Hardware

  • Arduino Nano
  • 10M Ohm resistor
  • Relay
  • wire or conductive material
  • AC converter

Wiring diagram

Warning: this project uses 220V. Take the necessary precautions to avoid electrocution.

Code

To create a capacitive sensor, we use the CapacitiveSensor library. When the capacitive sensor changes state, we modify the state sent to the relay to open or close the circuit.

#include <CapacitiveSensor.h>
#define DEBUG 0

//Capacitive sensor
CapacitiveSensor   cs_6_2 = CapacitiveSensor(6, 2);       // 10M resistor between pins 6 & 2, pin 2 is sensor pin, add a wire and or foil if desired
const int sensitivity  = 50;
long val;

//Light
const int lightPin = 9;
bool lightState = false;
bool btnState = false, oldState = false;

//smooth
long smoothval, total;
const int numReadings  = 3;
long readings[numReadings] = {0};
int readIndex;

long threshVal=500;

void setup()
{
  pinMode(lightPin, OUTPUT);
  cs_6_2.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
  Serial.begin(9600);
  Serial.println("Touchless lamp initialized");
  delay(2000);

  for (int i = 0; i < numReadings; i++) {
    val =  cs_6_2.capacitiveSensor(sensitivity);// increase for hi
    smoothval = smooth(val);
  }
}

void loop()
{
  val =  cs_6_2.capacitiveSensor(sensitivity);// increase for hi
  smoothval = smooth(val);

  if (DEBUG) {
    //Serial.print(millis() - timeStart);        // check on performance in milliseconds
    Serial.print("\t");                    // tab character for debug window spacing
    Serial.print(val);                  // print sensor output 1
    Serial.print("\t");
    Serial.print(smoothval);                  // print sensor smooth output
    Serial.println();                  // print sensor smooth output
  }

  // condition
  if (btnState == false && smoothval > threshVal) {
    btnState = true;
  }
  if (btnState == true && smoothval <= threshVal*0.8) {
    btnState = false;
  }

  if (oldState != btnState) {
    if (oldState == false) {
      lightState = !lightState;
    }
    digitalWrite(lightPin, lightState);
    delay(200);
  }
  oldState = btnState;

  delay(100);         // arbitrary delay to limit data to serial port
}

long smooth(long val) { /* function smooth */
  ////Write data on device

  long average;
  // subtract the last reading:
  total = total - readings[readIndex];
  // read from the sensor:
  readings[readIndex] = val;//cs.capacitiveSensor(sensitivity);
  // add the reading to the total:
  total = total + readings[readIndex];
  // advance to the next position in the array:
  readIndex = readIndex + 1;

  // if we're at the end of the array...
  if (readIndex >= numReadings) {
    // ...wrap around to the beginning:
    readIndex = 0;
  }

  // calculate the average:
  average = total / numReadings;
  // send it to the computer as ASCII digits

  return average;
}

Results

When you bring your hand close to the wire that acts as a tactile switch, the lamp should turn on or off. It’s up to you to adjust the sensor sensitivity, resistance and threshVal to obtain the desired behavior.

Next steps

  • Improving the robustness of capacitive sensors to external disturbances
  • Add a feature to automatically switch off the lamp after a certain time

Source

Configuring port forwarding

Configuring port forwarding

When you want to connect to a device outside your Wifi network, you need to set up port forwarding. Once your Raspberry Pi or ESP is connected to your Internet router, you can access it from anywhere by configuring port forwarding.

N.B: For cybersecurity reasons, it can be very dangerous to set up a port forwarding without taking care. For this reason, you should only set up a redirection if you’re sure of what you’re doing, and you should put in place the necessary safeguards (password, etc.).

Principle

On the same network, devices will communicate with their local addresses (e.g. 192.168.x.xxx). Only the router has a public address. When we configure port forwarding, we ask the router to open a public port and link it to a local address.

Ex:

  • public router IP: 82.95.256.144
  • router local IP: 192.168.1.254
  • local device IP: 192.168.1.17 (default port 80)

So if we redirect port 600 to the device’s IP address, we’ll be able to access the device by typing 82.95.256.144:600.

This procedure can be very useful for developing advanced home automation or IoT functions requiring remote access on Raspberry Pi, ESP8266, EP32 or any other device with an Internet connection.

Find your router’s IP address

  • Under Raspberry Pi or Linux
ip route
  • Under Windows
ipconfig

These commands give, among other things, the local IP address of your router (here 192.168.1.254).

You can use the netstat -a command to get a list of connections to the device and the ports used.

Configure port forwarding

In your browser, you can enter the IP address to access the router’s home page. You will be asked for your login details.

N.B: The port forwarding procedure differs from one box to another. If you search for “box-name Port Forwarding” on the Internet, you should come across the procedure to follow.

Luego busca la opción “Redirección de Puertos” o NAT/PAT. En un bbox, Servicios de la Box > Redirección de Puerto> Configuración.

Click on “Add a rule” and enter the redirection information

From the previous example:

  • Rule name: MyPortForwarding
  • Protocol: TCP
  • Device local IP address: 192.168.1.17
  • Internal port: 80 (can be a set value)
  • External port: 600

N.B: The external port can take a value between 0 and 65535. Port numbers below 1024 or above 49150 are reserved for the system.

Applications

Sources

Using an AC dimmer with ESP32

Using an AC dimmer with ESP32

In home automation, it is interesting to be able to manipulate alternating current in order to control different electrical appliances such as lamps or fans. The AC voltage dimmer is a module allowing to vary the power of an alternating current. It has the same use as a transistor in direct current. It can be used to vary the brightness of a lamp supplied with 220V or to vary the speed of a fan, for example. We will see how to manage the AC voltage dimmer with a NodeMCU ESP32.

Material

  • Computer
  • NodeMCU ESP32
  • USB A Male/Micro B Male Cable
  • AC Light Dimmer

Principle of operation

The AC dimmer consists of a triac (equivalent to a DC transistor) and a phase zero crossing detector to synchronize the voltage variation and the phase of the AC current.

Scheme

As far as the wiring diagram is concerned, the module is connected to the mains via the AC-IN terminal block and the bulb is connected to the LOAD terminal block. On the electronic side, the pins are connected as follows:

  • Vcc at pin 5 or 3.3V of the microcontroller
  • GND to ground GND of the microcontroller
  • Z-C to pin 1 (GPIO possibles 0,1,2,4,5,7,12,13,14,15,16,17,18,19,21,22,23,25,26,27,32,33,34,35,36,39)
  • PWM to pin2 (GPIO possibles 0,1,2,3,4,5,12,13,14,15,16,17,18,19,21,22,23,25,26,27,32,33 )

If you use several drives, the Z-C pins are all connected to the same microcontroller pin (in our case D1). The RBDdimmer library uses some pins in particular, depending on the microcontroller used. Please check the documentation of the library to see which pins you can use.

Caution: When using a NodeMCU, there are different versions of these cards with different pinouts and labels that can sometimes have errors. Ask your supplier and check the documentation of your card.

Code

Before programming your NodeMCU ESP32, make sure that the board manager is installed on the Arduino IDE. To configure the IDE, you can follow this tutorial.

To use the AC Light Dimmer module, we use the RBDdimmer.h library. The library will manage the synchronization between the PWM signal, which sets the power, and the phase of the AC current. Once the library has been imported and the module initialized, we only have to choose the power level between 0 and 100%.

//Libraries
#include <RBDdimmer.h>//https://github.com/RobotDynOfficial/RBDDimmer

//Parameters
const int zeroCrossPin  = 1;
const int acdPin  = 2;
int MIN_POWER  = 0;
int MAX_POWER  = 80;
int POWER_STEP  = 2;

//Variables
int power  = 0;

//Objects
dimmerLamp acd(acdPin,zeroCrossPin);

void setup(){
//Init Serial USB
Serial.begin(115200);
Serial.println(F("ESP32 System"));
acd.begin(NORMAL_MODE, ON);
}

void loop(){
  testDimmer();
}

void testDimmer(){/* function testDimmer */ 
////Sweep light power to test dimmer
  for(power=MIN_POWER;power<=MAX_POWER;power+=POWER_STEP){
    acd.setPower(power); // setPower(0-100%);
      Serial.print("lampValue -> ");
      Serial.print(acd.getPower());
      Serial.println("%");
    delay(100);
  }

  for(power=MAX_POWER;power>=MIN_POWER;power-=POWER_STEP){
    acd.setPower(power); // setPower(0-100%);
      Serial.print("lampValue -> ");
      Serial.print(acd.getPower());
      Serial.println("%");
    delay(100);
  }
}

Result

The brightness of the bulb varies according to the ‘power’ value sent to the module. It is good to note that this module works with dimmable loads and works best with incandescent bulbs. I use an LED bulb and the dimming works well between 6 and 40. Below 6, the lamp goes out, above that, I don’t see any change in brightness and the bulb goes out above 85.

Applications

  • Create a web interface or a Bluetooth application to control electrical devices remotely.

Sources

Using an AC Dimmer with ESP8266

Using an AC Dimmer with ESP8266

The AC voltage variator is a module that allows to vary the power of an alternating current. It has the same use as a transistor in direct current. It can be used to vary the brightness of a lamp supplied with 220V or to vary the speed of a fan, for example. We will see how to manage the AC voltage dimmer with a NodeMCU ESP8266.

Material

  • Computer
  • NodeMCU ESP8266
  • USB A Male/Micro B Male Cable
  • AC Light Dimmer
  • A dimmable bulb

Principle of operation

The AC dimmer consists of a triac (equivalent to a DC transistor) and a phase zero crossing detector to synchronize the voltage variation and the phase of the AC current.

Scheme

As far as the wiring diagram is concerned, the module is connected to the mains via the AC-IN terminal block and the bulb is connected to the LOAD terminal block. On the electronic side, the pins are connected as follows:

  • Vcc at pin 5 or 3.3V of the microcontroller
  • GND to ground GND of the microcontroller
  • Z-C to pin D1 (possible pins D2,D5,D6,D7,D8)
  • PWM at pin D2 (possible pins D0,D1,D5,D6,D7,D8 )

If you use several drives, the Z-C pins are all connected to the same microcontroller pin (in our case D1). The RBDdimmer library uses some pins in particular, depending on the microcontroller used. Please check the documentation of the library to see which pins you can use.

Caution: When using a NodeMCU, there are different versions of these cards with different pinouts and labels that can sometimes have errors. Ask your supplier and check the documentation of your card.

Code

Before programming your NodeMCU ESP8266, make sure that the board manager is installed on the Arduino IDE. To configure the IDE, you can follow this tutorial.

To use the AC Light Dimmer module, we use the RBDdimmer.h. library. The library will manage the synchronization between the PWM signal, which sets the power, and the phase of the AC current. Once the library has been imported and the module initialized, we only have to choose the power level between 0 and 100%.

Before uploading the code, you need to install the RBDdimmer library.

//Libraries
#include <RBDdimmer.h>//https://github.com/RobotDynOfficial/RBDDimmer

//Parameters
const int zeroCrossPin  = D1;
const int acdPin  = D2;
int MIN_POWER  = 0;
int MAX_POWER  = 80;
int POWER_STEP  = 2;

//Variables
int power  = 0;

//Objects
dimmerLamp acd(acdPin,zeroCrossPin);

void setup(){
//Init Serial USB
Serial.begin(115200);
Serial.println(F("ESP8266 System"));
acd.begin(NORMAL_MODE, ON);
}

void loop(){
  testDimmer();
}

void testDimmer(){/* function testDimmer */ 
////Sweep light power to test dimmer
  for(power=MIN_POWER;power<=MAX_POWER;power+=POWER_STEP){
    acd.setPower(power); // setPower(0-100%);
      Serial.print("lampValue -> ");
      Serial.print(acd.getPower());
      Serial.println("%");
    delay(100);
  }

  for(power=MAX_POWER;power>=MIN_POWER;power-=POWER_STEP){
    acd.setPower(power); // setPower(0-100%);
      Serial.print("lampValue -> ");
      Serial.print(acd.getPower());
      Serial.println("%");
    delay(100);
  }
}

Result

The brightness of the bulb varies according to the ‘power’ value sent to the module. It is good to note that this module works with dimmable loads and works best with incandescent bulbs. I use an LED bulb and the dimming works well between 6 and 40. Below 6, the lamp goes out, above that, I don’t see any change in brightness and the bulb goes out above 85.

Applications

  • Create a web interface to control lights remotely.

Sources

Using an AC Light Dimmer with Arduino

Using an AC Light Dimmer with Arduino

The AC light dimmer is a module that allows to vary the power of an alternating current. It has the same use as a transistor in direct current. It can be used to vary the brightness of a lamp supplied with 220V or to vary the speed of a fan, for example.

Material

  • Computer
  • Arduino UNO
  • USB cable A Male/B Male
  • AC Light Dimmer

Principle of operation

The AC dimmer consists of a triac (equivalent to a DC transistor) and a phase zero crossing detector to synchronize the voltage variation and the phase of the AC current.

Scheme

As far as the wiring diagram is concerned, the module is connected to the mains via the AC-IN terminal block and the bulb is connected to the LOAD terminal block. On the electronic side, the pins are connected as follows:

  • Vcc at pin 5 or 3.3V of the microcontroller
  • GND to ground GND of the microcontroller
  • Z-C at pin 2
  • PWM on pin 3

If you use several drives, the Z-C pins are all connected to the same microcontroller pin (in our case D2). The RBDdimmer library uses some pins in particular, depending on the microcontroller used. Check the documentation of the library to see which pins you can use.

Code

To use the AC Light Dimmer module, we use the RBDdimmer.h library. The library will manage the synchronization between the PWM signal, which sets the power, and the phase of the AC current. Once the library has been imported and the module initialized, we only have to choose the power level between 0 and 100%.

//Libraries
#include <RBDdimmer.h>//https://github.com/RobotDynOfficial/RBDDimmer

//Parameters
const int zeroCrossPin  = 2;
const int acdPin  = 3;
int MIN_POWER  = 0;
int MAX_POWER  = 80;
int POWER_STEP  = 2;

//Variables
int power  = 0;

//Objects
dimmerLamp acd(acdPin);

void setup(){
//Init Serial USB
Serial.begin(9600);
Serial.println(F("Initialize System"));
acd.begin(NORMAL_MODE, ON);
}

void loop(){
  testDimmer();
}

void testDimmer(){/* function testDimmer */ 
////Sweep light power to test dimmer
  for(power=MIN_POWER;power<=MAX_POWER;power+=POWER_STEP){
    acd.setPower(power); // setPower(0-100%);
      Serial.print("lampValue -> ");
      Serial.print(acd.getPower());
      Serial.println("%");
    delay(100);
  }

  for(power=MAX_POWER;power>=MIN_POWER;power-=POWER_STEP){
    acd.setPower(power); // setPower(0-100%);
      Serial.print("lampValue -> ");
      Serial.print(acd.getPower());
      Serial.println("%");
    delay(100);
  }
}

Result

The brightness of the bulb varies according to the ‘power’ value sent to the module. It is good to note that this module works with dimmable loads and works best with incandescent bulbs. I use an LED bulb and the dimming works well between 6% and 40%. Below 6%, the lamp goes out, above that, I don’t see any change in brightness and the bulb goes out above 85%.

Bonus: Management of two AC drives

If you want to use another AC drive at the same time, simply connect the Z-C pin to pin 2 (on UNO) and the PWM pin to pin 5 (or another PWM pin).

In the code, to manage two modules, an additional dimmerLamp object must be declared by initializing the correct output pin.

//Libraries
#include <RBDdimmer.h>//https://github.com/RobotDynOfficial/RBDDimmer

//Constants
#define nbACD 2

//Parameters
const int zeroCrossPin = 2;
const int acdPin[nbACD] ={3,5};
int MIN_POWER[nbACD] ={0,0};
int MAX_POWER[nbACD] ={80,80};
int POWER_STEP[nbACD] ={1,1};

//Variables
int power[nbACD] ={0,0};
dimmerLamp acd[nbACD] ={dimmerLamp(acdPin[0]),dimmerLamp(acdPin[1])};

void setup(){
//Init Serial USB
Serial.begin(9600);
Serial.println(F("Initialize System"));
for(int i=0;i<nbACD;i++) acd[i].begin(NORMAL_MODE, ON);
}

void loop(){
  testDimmer();
}

void testDimmer(){/* function testDimmer */ 
////Sweep light power to test dimmer
for(int i=0;i<nbACD;i++){
  for(power[i]=MIN_POWER[i];power[i]<=MAX_POWER[i];power[i]+=POWER_STEP[i]){
    acd[i].setPower(power[i]); // setPower(0-100%);
      Serial.print(F("lampValue "));Serial.print(i);Serial.print(F(" -> "));
      Serial.print(acd[i].getPower());
      Serial.println(F("%"));
    delay(100);
  }

  for(power[i]=MAX_POWER[i];power[i]>=MIN_POWER[i];power[i]-=POWER_STEP[i]){
    acd[i].setPower(power[i]); // setPower(0-100%);
      Serial.print(F("lampValue "));Serial.print(i);Serial.print(F(" -> "));
      Serial.print(acd[i].getPower());
      Serial.println(F("%"));
    delay(100);
  }
}
}

The two lamps turn on and off gradually, one after the other. You can now apply this tutorial to manage all the lamps in your house.

Applications

  • Control the brightness of a room according to the time of day
  • Control the speed of a fan according to the room temperature

Sources

Retrouvez nos tutoriels et d’autres exemples dans notre générateur automatique de code
La Programmerie