Hi there
I am new here. I am trying to control an 8 channel relay but find a problem I am still unable to understand. When programming the builtin led and one of the leds from the relay telling them both to go LOW, the builtin works as intended, but the one from the relay does just the opposite. Here's my code:
int relay_1 = 2;
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
pinMode(relay_1, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
digitalWrite(relay_1, HIGH);
Serial.println("Relays on board ON");
delay(5000); // wait for 5 seconds
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
digitalWrite(relay_1, LOW);
Serial.println("Relays on board OFF");
delay(10000); // wait for 10 seconds
}
So builtin led turns on and external led turns off, and viceversa.
Any suggestions?
Yes, most relay boards work by putting logic low on the output, and depending on how you wire up the LED, then the most common way here is to wire them so a high turns them on.
Arduino is a Uno R4 Wifi. Relay board is unknown (had it lying around, worked as intended with a Pi). Single relays are Songle or Soncle, SRD-5VDC-SL-C.
So changing
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
digitalWrite(relay_1, HIGH);
to
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
digitalWrite(relay_1, LOW);
As far say I can tell, the schematic for your board shows that the LED_BUILTIN pin drives the gate of transistor Q3. When the pin is HIGH, Q3 turns on, current can flow from 5V through the yellow led, R25 and Q3 to ground. So a HIGH signal from the pin will light the led.
On the relay board, if the pin connected to IN1 is LOW, current can flow from Vcc, through R1, the opto-isolator U1, through led IN1 into the Arduino pin to ground. So when the pin is LOW, the led is on.
One thing to watch out for with LOW true relays. On startup all pins are set to 0 (LOW) by default, so when you set pinMode to OUTPUT in setup(), the relay will come ON until you digitalWrite it HIGH in the program.
To avoid that, do this in setup():
digitalWrite(relayPin,HIGH; // set pin HIGH before setting to OUTPUT
pinMode(relayPin,OUTPUT); // relay is OFF on program entry