As digispark is more compact and suitable for my electrical application. Following the same procedure in brtiberio answer. I tried to convert the script from Arduino UNO to digispark, but not succeed
#define irPin 2
const int buttonPin1 = 0;
const int buttonPin2 = 4;
const int relay1 = 1;
const int relay2 = 3;
int Relay1State = 0;
int Relay2State = 0;
int master1State = 0;
int master2State = 0;
int button1State;
int button2State;
int lastButton1State;
long lastDebounceTime1 = 0;
int lastButton2State;
long lastDebounceTime2 = 0;
long debounceDelay = 50;
void setup() {
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
digitalWrite(relay1, Relay1State);
digitalWrite(relay2, Relay2State);
}
void loop() {
int key = getIrKey();
if(key == 7388){
Relay1State = !Relay1State;
if(Relay1State == true)
digitalWrite(relay1, HIGH);
else
digitalWrite(relay1, LOW);
}
if(key == 1778){
Relay2State = !Relay2State;
if(Relay2State == true)
digitalWrite(relay2, HIGH);
else
digitalWrite(relay2, LOW);
}
}
int getIrKey(){
int len = pulseIn(irPin,LOW);
int key, temp;
key = 0;
//Serial.print("len=");
//Serial.println(len);
if(len > 6000) {
for(int i=1;i<=32;i++){
temp = pulseIn(irPin,HIGH);
if(temp > 1000)
key = key + (1<<(i-17));
}
}
if(key < 0 )
key = -key;
//if(key)
//Serial.println(key);
delay(250);
return key;
//**********************//
int reading = digitalRead(buttonPin1);
if (reading != lastButton1State) {
lastDebounceTime1 = millis();
}
if ((millis() - lastDebounceTime1) > debounceDelay) {
if (reading != button1State) {
button1State = reading;
if (button1State == HIGH) {
master1State = !master1State;
Relay1State = master1State;
}
}
}
digitalWrite(relay1, Relay1State);
lastButton1State = reading;
//*******************************//
int reading2 = digitalRead(buttonPin2);
if (reading2 != lastButton2State) {
lastDebounceTime2 = millis();
}
if ((millis() - lastDebounceTime2) > debounceDelay) {
if (reading2 != button2State) {
button2State = reading2;
if (button2State == HIGH) {
master2State = !master2State;
Relay2State = master2State;
}
}
}
digitalWrite(relay2, Relay2State);
lastButton2State = reading2;
}
Any advise, please?
1 Answer 1
Your button code is in the function int getIrKey()
. But it never gets executed, because before it you execute return key;
. With that you leave the function and returning the value of key
. Everthing that comes after the return statement will not be executed.
Putting the button code in that function doesn't make sense in the first place (since the buttons are not used to "get the pressed IR key"). Instead try to put it in the loop()
function, after the other relay code.
not succeed
is not a description of a problem