Arduino 如何使用模拟值制作高低环路
所以我把灯放在我的房间里,它们将被esp32控制 esp32具有电容式触摸功能,因此可使用该功能进行控制 我的问题是,我需要控制它,一按打开,第二按关闭 我试过一些方法,但没有成功,所以这是代码Arduino 如何使用模拟值制作高低环路,arduino,Arduino,所以我把灯放在我的房间里,它们将被esp32控制 esp32具有电容式触摸功能,因此可使用该功能进行控制 我的问题是,我需要控制它,一按打开,第二按关闭 我试过一些方法,但没有成功,所以这是代码 const int touchPin = 4; const int ledPin = LED_BUILTIN; const int threshold = 10; int touchValue; boolean oldSwitchState = LOW; boolean newSwitchStat
const int touchPin = 4;
const int ledPin = LED_BUILTIN;
const int threshold = 10;
int touchValue;
boolean oldSwitchState = LOW;
boolean newSwitchState = LOW;
int i;
void setup(){
Serial.begin(115200);
delay(1000);
pinMode(ledPin, OUTPUT);
}
void loop(){
touchValue = touchRead(touchPin);
i = touchRead(touchPin);
Serial.println(touchValue);
boolean s;
s = map(i,20,50,1,0);
Serial.println(s);
digitalWrite(ledPin, 1);
newSwitchState = s;
if ( newSwitchState != oldSwitchState ){
if ( newSwitchState == HIGH ) {
digitalWrite(ledPin, HIGH);
}
else{
digitalWrite(ledPin, LOW);
}
oldSwitchState = newSwitchState;
}
delay(500);
}
为了实现你想要的,你需要修改你的if。。。比较newSwitchState和oldSwitchState的其他部分 不必检查newSwitchState是高还是低,您可以维护另一个变量,该变量在状态更改时切换 这句话有点意思
...
boolean toggleState = false;
...
void loop() {
...
if ( newSwitchState != oldSwitchState ) {
if ( toggleState == false ) {
toggleState = true;
digitalWrite(ledPin, HIGH);
}
else {
toggleState = false;
digitalWrite(ledPin, LOW);
}
oldSwitchState = newSwitchState;
}
...
}
这就是有效的代码
const int touchPin = 4;
const int ledPin = LED_BUILTIN;
int touchValue;
bool outputstate = 0;
void setup() {
Serial.begin(115200);
delay(1000);
pinMode(ledPin, OUTPUT);
}
void loop() {
touchValue = touchRead(touchPin);
i = touchRead(touchPin);
Serial.println(touchValue);
if(touchValue < 30){
outputstate = !outputstate;
digitalWrite(ledPin, outputstate);
delay(1000);
}
}
const int touchPin=4;
const int ledPin=发光二极管内置;
int值;
布尔输出状态=0;
无效设置(){
序列号开始(115200);
延迟(1000);
引脚模式(LED引脚,输出);
}
void循环(){
touchValue=touchRead(touchPin);
i=触摸读取(触针);
Serial.println(touchValue);
如果(接触值<30){
outputstate=!outputstate;
数字写入(ledPin,输出状态);
延迟(1000);
}
}