不需要任何硬件的Arduino电容触摸方法


首先,说明一下转自:http://playground.arduino.cc/Code/CapacitiveSensor 网站。
capacitiveSensor
这个教程仅用arduino的一个数字端口,就能检测到触摸输入的方法。

代码的工作原理是将某一数字引脚设置为接地,并打开arduino内部上拉电阻。然后检测该引脚返回高电平状态所需的时间。readCapacitivePin函数返回是1说明没有任何触控出现。如果大于2或上升至更高,说明触控了该数字引脚所连接的导体。
另外注意:
1、教程说最好在引脚和触摸中间加一个1nf的电容,我手头没有,就没有尝试。
2、引脚切换到输出模式以使端口放电,如果连接到电压源,将使引脚短路,可能会损坏Arduino和连接到引脚的任何硬件!
代码如下:

int capval;
void setup()
{
Serial.begin(9600);
Serial.println(“Touch senser”);
}
void loop ()
{
capval = readCapacitivePin(8);
Serial.println(capval, DEC);
//触摸8号引脚连接的导体时,capval将升高
if (capval > 2) {
//做事情…
//Serial.println(capval, DEC);
delay(10);
}
}
//http://playground.arduino.cc/Code/CapacitiveSensor
uint8_t readCapacitivePin(int pinToMeasure) {
// Variables used to translate from Arduino to AVR pin naming
volatile uint8_t* port;
volatile uint8_t* ddr;
volatile uint8_t* pin;
// Here we translate the input pin number from
// Arduino pin number to the AVR PORT, PIN, DDR,
// and which bit of those registers we care about.
byte bitmask;
port = portOutputRegister(digitalPinToPort(pinToMeasure));
ddr = portModeRegister(digitalPinToPort(pinToMeasure));
bitmask = digitalPinToBitMask(pinToMeasure);
pin = portInputRegister(digitalPinToPort(pinToMeasure));
// Discharge the pin first by setting it low and output
*port &= ~(bitmask);
*ddr |= bitmask;
delay(1);
// Make the pin an input with the internal pull-up on
*ddr &= ~(bitmask);
*port |= bitmask;
// Now see how long the pin to get pulled up. This manual unrolling of the loop
// decreases the number of hardware cycles between each read of the pin,
// thus increasing sensitivity.
uint8_t cycles = 17;
if (*pin & bitmask) { cycles = 0;}
else if (*pin & bitmask) { cycles = 1;}
else if (*pin & bitmask) { cycles = 2;}
else if (*pin & bitmask) { cycles = 3;}
else if (*pin & bitmask) { cycles = 4;}
else if (*pin & bitmask) { cycles = 5;}
else if (*pin & bitmask) { cycles = 6;}
else if (*pin & bitmask) { cycles = 7;}
else if (*pin & bitmask) { cycles = 8;}
else if (*pin & bitmask) { cycles = 9;}
else if (*pin & bitmask) { cycles = 10;}
else if (*pin & bitmask) { cycles = 11;}
else if (*pin & bitmask) { cycles = 12;}
else if (*pin & bitmask) { cycles = 13;}
else if (*pin & bitmask) { cycles = 14;}
else if (*pin & bitmask) { cycles = 15;}
else if (*pin & bitmask) { cycles = 16;}
// Discharge the pin again by setting it low and output
// It’s important to leave the pins low if you want to
// be able to touch more than 1 sensor at a time – if
// the sensor is left pulled high, when you touch
// two sensors, your body will transfer the charge between
// sensors.
*port &= ~(bitmask);
*ddr |= bitmask;
return cycles;
}


《“不需要任何硬件的Arduino电容触摸方法”》 有 4 条评论

发表评论

您的电子邮箱地址不会被公开。