以下是根据我们目前所知的一些观察结果。
我相信电容式触摸传感器不会返回高/低结果,除非它们是“数字电容式触摸传感器”。非数字的可能会返回模拟值,因此您可能需要使用 AnalogRead 函数。
在这种情况下,您的代码可能如下所示:
senVal1 = analogRead(sen1);
if (senVal1 > 800) {
// Do sensor is touched stuff
}
另外,假设您的 LED 通过其阴极连接到 Arduino(即 LOW = ON),那么您似乎永远不会关闭任何 LED。那就是没有这样的代码:
digitalWrite(LEDX, HIGH);
所以结果可能是所有 LED 都会亮起并保持亮起。
最后,您可能想要引入一些去抖动和/或尚未放手。考虑以下几点:
void loop() {
// read the state of the sensor0 value:
senState0 = digitalRead(sen0); // This appears to be in the wrong place!!!!
// check if the sensortouch is pressed.
// if it is, the sensorState is HIGH:
if ( senState0 == HIGH ) {
if (sentouchCount1 % numberOfLED1 == 0 ){
digitalWrite(LEDR,LOW);
digitalWrite(LEDR1,LOW);
}
循环函数每秒将被调用多次(例如每秒数千次)。您的逻辑实际上是“是否按下 Sensor0?”。该测试每秒执行很多次。因此,涉及“sentouchCount1”的测试将每秒执行很多次。
假设您实际上通过向其添加一个来更改某处的 senttouchCount1 值,这将快速循环遍历 if 语句的所有可能值,导致所有 LED 看起来都立即打开。
但是,您不会更改 senttouchCount1 的值,因此只有第一个打开 LEDR 并且 LEDR1 可能被激活。
哦,关于“还没有放手”位,请考虑以下代码:
boolean isPressed = false;
loop() {
if (senState0 == HIGH && !isPressed) {
// do stuff when we detect that the switch is pressed
isPressed = true; // Make sure we don't keep doing this for the entire
// duration the user is touching the switch!
} else if (senState0 == LOW && isPressed) {
isPressed = false; // User has let go of the button, so enable the
// previous if block that takes action when the user
// presses the button.
} // You might need to search "debouncing a switch", but I do not think this is required for capacative touch sensors (especially digital ones).
根据我在下面的评论,您可能需要执行以下操作:
boolean isSensor1Touched = false;
void loop() {
// read the state of the sensor0 value:
senState0 = digitalRead(sen0); // This appears to be in the wrong place!!!!
// check if the sensortouch is pressed.
// if it is, the sensorState is HIGH:
if ( senState0 == HIGH && ! isSensor1Touched) {
sentouchCount1++;
isSensor1Touched = true;
if (sentouchCount1 % numberOfLED1 == 0 ){
digitalWrite(LEDR,LOW);
digitalWrite(LEDR1,LOW);
}
if (sentouchCount1 % numberOfLED1 == 1 ){
digitalWrite(LEDG,LOW);
digitalWrite(LEDG1,LOW);
}
if (sentouchCount1 % numberOfLED1 == 2){
digitalWrite(LEDB,LOW);
digitalWrite(LEDB1,LOW);
}
} else if (senState0 == LOW && isSensor1Touched) {
isSensor1Touched = false;
}
// Then repeat for other sensors...