I can't code Arduino very well
I have Arduino uno with 8 relays all i need to a code i can program it
I have 8 relays i need when i connect the Arduino all the relays open for 1 min
and then all of them close except relay 1 for 10 min and then close and the relay 2 open for 10 min then and then close and relay 3 do the same until relay 6 open for 10 min and then close and then repeat the loop again
can any one help and send me the code
thx
You could try this (mostly AI generated)
// Define the relay pins (adjust these to match your actual connections)
const int relayPins[] = { 2, 3, 4, 5, 6, 7, 8, 9 };
const int numRelays = 8;
void setup()
{
// Initialize all relay pins as OUTPUT
for (int i = 0; i < numRelays; i++)
{
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], HIGH); // Assuming HIGH turns relay OFF (common configuration)
}
// Start with all relays ON for 1 minute
allRelaysOn();
delay(60000); // 1 minute delay
// Turn all relays off
allRelaysOff();
}
void loop()
{
// Cycle through relays 1-6 (indexes 0-5 in the array)
for (int i = 0; i < 6; i++)
{
// Turn on the current relay
digitalWrite(relayPins[i], LOW); // Assuming LOW turns relay ON
// Keep it on for 10 minutes
delay(600000UL); // 10 minutes = 600,000 milliseconds
// Turn off the current relay
digitalWrite(relayPins[i], HIGH);
}
// The cycle will now repeat automatically
}
void allRelaysOn()
{
for (int i = 0; i < numRelays; i++)
{
digitalWrite(relayPins[i], LOW); // Turn all relays ON
}
}
void allRelaysOff()
{
for (int i = 0; i < numRelays; i++)
{
digitalWrite(relayPins[i], HIGH); // Turn all relays OFF
}
}
Perhaps we can help you with the code you currently have. But before anything can be coded, you need a diagram showing how all your project is connected and that included how you are powering the uno and the relays.
Thank you very much i will try it and send you the feedback thx
@hisam99 you said there were eight relays and told us about six of them. So did you mean the pattern should go to relays 7 and 8 as well, or should those relays just be turned , and left, on?
Also, in case you haven't realized, testing any code will be painful. Replace the constants that make each step take one minute with ones that take only 7.777 seconds, or some other random brief period, viz:
delay(7777); // life is short. later: 60000 for 1 minute delay
a7
Define a few more constants at the top of the program to make your life easier
- relay ON/OFF constants so if your relay turns on HIGH or LOW, it is easy to change
- delay times so making them shorter is easier to test
// Define the relay pins (adjust these to match your actual connections)
const int relayPins[] = { 2, 3, 4, 5, 6, 7, 8, 9 };
const int numRelays = sizeof relayPins / sizeof relayPins[0];
// constants (make shorter during testing)
const unsigned long oneMinuteDelay = 6000UL;
const unsigned long tenMinuteDelay = 60000UL;
// define how your relays turn ON/OFF
// many turn on when LOW and off when HIGH
// some are the other way around
#define relayON LOW
#define relayOFF HIGH
void setup()
{
// Initialize all relay pins as OUTPUT
for (int i = 0; i < numRelays; i++) {
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], relayOFF);
}
// Start with all relays ON for 1 minute
allRelaysOn();
delay(oneMinuteDelay); // 1 minute delay
// Turn all relays off
allRelaysOff();
}
void loop()
{
// Cycle through relays 1-6 (indexes 0-5 in the array)
for (int i = 0; i < 6; i++) {
// Turn on the current relay
digitalWrite(relayPins[i], relayON);
// Keep it on for 10 minutes
delay(tenMinuteDelay);
// Turn off the current relay
digitalWrite(relayPins[i], relayOFF);
}
// The cycle will now repeat automatically
}
void allRelaysOn()
{
for (int i = 0; i < numRelays; i++) {
digitalWrite(relayPins[i], relayON);
}
}
void allRelaysOff()
{
for (int i = 0; i < numRelays; i++) {
digitalWrite(relayPins[i], relayOFF);
}
}
I fed your requirements into DeepSeek (AI) to see how it would perform. The code looks plausible but I haven't otherwise checked it. It did, however, make some interesting obervations:
Arduino Relay Control with Timed Sequence
Here's a program that implements your exact requirements:
All relays turn ON for 1 minute when Arduino starts
Then all turn OFF except relay 1, which stays ON for 10 minutes
Then relay 1 turns OFF and relay 2 turns ON for 10 minutes
This continues through relay 6
The sequence then repeats.
// Arduino 8-Relay Sequential Control Program
const int NUM_RELAYS = 8;
const int relayPins[NUM_RELAYS] = {2, 3, 4, 5, 6, 7, 8, 9}; // Update these pins to match your wiring
// Timing constants (in milliseconds)
const unsigned long ALL_RELAYS_TIME = 60000; // 1 minute for all relays
const unsigned long SINGLE_RELAY_TIME = 600000; // 10 minutes per relay
unsigned long previousMillis = 0;
int currentStage = 0;
bool initialSequenceComplete = false;
void setup() {
// Initialize all relay pins as OUTPUT
for (int i = 0; i < NUM_RELAYS; i++) {
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], HIGH); // Start with all relays OFF
}
// Turn ON all relays immediately
allRelaysOn();
previousMillis = millis(); // Start timing
}
void loop() {
unsigned long currentMillis = millis();
if (!initialSequenceComplete) {
// Stage 0: All relays ON for 1 minute
if (currentMillis - previousMillis >= ALL_RELAYS_TIME) {
allRelaysOff();
relayOn(0); // Turn on only relay 1
previousMillis = currentMillis;
currentStage = 1;
initialSequenceComplete = true;
}
}
else {
// Stages 1-6: Each relay gets 10 minutes
if (currentMillis - previousMillis >= SINGLE_RELAY_TIME) {
relayOff(currentStage - 1); // Turn off previous relay
if (currentStage < 6) {
relayOn(currentStage); // Turn on next relay
currentStage++;
} else {
// Restart the sequence from relay 1
relayOn(0);
currentStage = 1;
}
previousMillis = currentMillis;
}
}
}
// Turn ON all relays
void allRelaysOn() {
for (int i = 0; i < NUM_RELAYS; i++) {
digitalWrite(relayPins[i], LOW);
}
}
// Turn OFF all relays
void allRelaysOff() {
for (int i = 0; i < NUM_RELAYS; i++) {
digitalWrite(relayPins[i], HIGH);
}
}
// Turn ON a specific relay (0-7)
void relayOn(int relayNum) {
if (relayNum >= 0 && relayNum < NUM_RELAYS) {
digitalWrite(relayPins[relayNum], LOW);
}
}
// Turn OFF a specific relay (0-7)
void relayOff(int relayNum) {
if (relayNum >= 0 && relayNum < NUM_RELAYS) {
digitalWrite(relayPins[relayNum], HIGH);
}
}
Important Notes:
Pin Configuration: Make sure the relayPins array matches your actual wiring (pins 2-9 are used in this example).
Relay Module Type:
The code assumes an active-low relay module (LOW = ON, HIGH = OFF)
If your module is active-high, swap LOW/HIGH in all relay functions
Timing:
1 minute = 60,000 milliseconds
10 minutes = 600,000 milliseconds
You can adjust these constants if needed
Relays 7 & 8:
These relays are initialized but never used in the sequence (as per your requirements)
They'll remain OFF throughout operation
Reset Behavior:
The sequence will restart from the beginning if Arduino is reset
All relays will turn ON for 1 minute again
Would you like me to add any of the following features?
Serial monitoring for debugging
External trigger to start the sequence
Manual override capability
Non-volatile memory to remember state after power loss.
And because this question often comes up: What budget should I allow for this project? I asked:
Here's a breakdown of the estimated budget for your Arduino 8-relay control project:
Basic Budget Estimate (USD)
-
Arduino Board
- Arduino Uno (clone): $5–$10
- Genuine Arduino Uno: $20–$30
-
8-Channel Relay Module
- 5V 8-relay module (optocoupler isolated): $8–$15
-
Power Supply
- 5V 2A power adapter (for Arduino + relays): $5–$10
- (If relays control high-power devices, add a separate 12V/24V supply)
-
Wiring & Accessories
- Jumper wires, breadboard (optional): $3–$5
- Enclosure (if needed): $5–$20
-
Miscellaneous
- Fuses, terminal blocks, switches (optional): $5–$10
Total Estimated Cost
- Minimum (clone parts, basic setup): ~$20–$30
- Recommended (reliable components, enclosure): ~$40–$60
- Premium (genuine Arduino, industrial relays, safety features): ~$70–$120
Where to Buy
- Budget options: AliExpress, eBay
- Reliable options: Amazon, SparkFun, Adafruit, local electronics stores
Additional Costs (If Needed)
- Sensors (for automation): $5–$20
- LCD display (for status monitoring): $5–$10
- Real-time clock (RTC) module (for timed schedules): $3–$5
Would you like recommendations for specific parts or suppliers based on your location? Also, do you need any modifications to the circuit for high-power loads (e.g., motors, AC devices)?
EDIT
Oh. I was answering in one of the OP's cross posts which has now been merged here.
Anyway, its very interesting that the solutions seem quite similar down to the choice of output pins and variable names.
I have merged your cross-posts @hisam99.
Cross-posting is against the Arduino forum rules. The reason is that duplicate posts can waste the time of the people trying to help. Someone might spend a lot of time investigating and writing a detailed answer on one topic, without knowing that someone else already did the same in the other topic.
Repeated cross-posting can result in a suspension from the forum.
In the future, please only create one topic for each distinct subject matter. This is basic forum etiquette, as explained in the "How to get the best out of this forum" guide. It contains a lot of other useful information. Please read it.
Thanks in advance for your cooperation.
Thank you very much it worked perfectly
Thank you all for your help , it worked perfectly and i did remove the 10 min to 30 sec just to try it the code was so perfect and every line was explained perfectly
I guess @hisam99 is full of free fish and won't be learning to fish himself.
And tools like chatgpt now serve them most of things on platter, so they don't even bother to try learning anything out of their comfort zone.
But the op wasn't even aware of that
. Sad state of affairs
I added some printing instead of wiring a bunch of relays and the sketch functions well.
Did you just use the OP's post?
a7
More or less directly. The entire dialogue is here. It shot off rather prematurely (to my mind). I was expecting it to first clarify the requirements but it does not appear to work like that. It simply makes what it can of a garbled specification, delivers a first guess "solution" on that basis, then starts talking about the ambiguities etc.
The Whole Thing . . .
Me: I have an arduino project which controls 8 relays. I need a program written. Can you help
It: Arduino 8-Relay Control Program
Certainly! Below is a complete Arduino program to control 8 relays. This program includes:
Basic relay control functions
Example usage in setup and loop
Comments explaining each part
// Arduino 8-Relay Control Program
// Define the number of relays and their pins
const int NUM_RELAYS = 8;
const int relayPins[NUM_RELAYS] = {2, 3, 4, 5, 6, 7, 8, 9}; // Change these to match your wiring
// Relay states array (tracking on/off)
bool relayStates[NUM_RELAYS] = {false};
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize all relay pins as OUTPUT
for (int i = 0; i < NUM_RELAYS; i++) {
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], HIGH); // Default to OFF (assuming active-low relay module)
}
Serial.println("8-Relay Controller Initialized");
printRelayStates();
}
void loop() {
// Example usage - cycles through relays one by one
for (int i = 0; i < NUM_RELAYS; i++) {
relayOn(i);
delay(1000);
relayOff(i);
delay(500);
}
// Uncomment below for serial control
// serialControl();
}
// Turn on a specific relay (0-7)
void relayOn(int relayNum) {
if (relayNum >= 0 && relayNum < NUM_RELAYS) {
digitalWrite(relayPins[relayNum], LOW); // LOW turns on most relay modules
relayStates[relayNum] = true;
Serial.print("Relay ");
Serial.print(relayNum);
Serial.println(" ON");
}
}
// Turn off a specific relay (0-7)
void relayOff(int relayNum) {
if (relayNum >= 0 && relayNum < NUM_RELAYS) {
digitalWrite(relayPins[relayNum], HIGH); // HIGH turns off most relay modules
relayStates[relayNum] = false;
Serial.print("Relay ");
Serial.print(relayNum);
Serial.println(" OFF");
}
}
// Toggle a relay's state
void toggleRelay(int relayNum) {
if (relayNum >= 0 && relayNum < NUM_RELAYS) {
if (relayStates[relayNum]) {
relayOff(relayNum);
} else {
relayOn(relayNum);
}
}
}
// Print current relay states to serial
void printRelayStates() {
Serial.println("Current Relay States:");
for (int i = 0; i < NUM_RELAYS; i++) {
Serial.print("Relay ");
Serial.print(i);
Serial.print(": ");
Serial.println(relayStates[i] ? "ON" : "OFF");
}
}
// Optional: Control relays via serial input
void serialControl() {
if (Serial.available()) {
char command = Serial.read();
int relayNum = command - '0'; // Convert char to int
if (relayNum >= 0 && relayNum < NUM_RELAYS) {
toggleRelay(relayNum);
} else if (command == 'a') {
// Turn all relays on
for (int i = 0; i < NUM_RELAYS; i++) relayOn(i);
} else if (command == 'z') {
// Turn all relays off
for (int i = 0; i < NUM_RELAYS; i++) relayOff(i);
} else if (command == 's') {
// Print status
printRelayStates();
}
}
}
Important Notes:
-
Relay Module Type: This code assumes you're using an active-low relay module (common type). If your relays are active-high, change
LOWtoHIGHinrelayOn()and vice versa inrelayOff(). -
Pin Configuration: Update the
relayPinsarray to match the Arduino pins you've connected to your relay module. -
Power Considerations: Ensure your Arduino has a separate power supply for the relays if they're controlling high-power devices.
-
Serial Control: Uncomment the
serialControl()line inloop()if you want to control relays via serial commands (send numbers 0-7 to toggle relays, 'a' for all on, 'z' for all off, 's' for status). -
Example Usage: The current
loop()cycles through each relay one by one for demonstration. Replace this with your own control logic.
Would you like me to modify any part of this program to better suit your specific project needs?
Me:
The complete description of the relay operating schedule is as follows: I have 8 relays i need when i connect the Arduino all the relays open for 1 min
and then all of them close except relay 1 for 10 min and then close and the relay 2 open for 10 min then and then close and relay 3 do the same until relay 6 open for 10 min and then close and then repeat the loop again
It:
Arduino Relay Control with Timed Sequence
Here's a program that implements your exact requirements:
- All relays turn ON for 1 minute when Arduino starts
- Then all turn OFF except relay 1, which stays ON for 10 minutes
- Then relay 1 turns OFF and relay 2 turns ON for 10 minutes
- This continues through relay 6
- The sequence then repeats
// Arduino 8-Relay Sequential Control Program
const int NUM_RELAYS = 8;
const int relayPins[NUM_RELAYS] = {2, 3, 4, 5, 6, 7, 8, 9}; // Update these pins to match your wiring
// Timing constants (in milliseconds)
const unsigned long ALL_RELAYS_TIME = 60000; // 1 minute for all relays
const unsigned long SINGLE_RELAY_TIME = 600000; // 10 minutes per relay
unsigned long previousMillis = 0;
int currentStage = 0;
bool initialSequenceComplete = false;
void setup() {
// Initialize all relay pins as OUTPUT
for (int i = 0; i < NUM_RELAYS; i++) {
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], HIGH); // Start with all relays OFF
}
// Turn ON all relays immediately
allRelaysOn();
previousMillis = millis(); // Start timing
}
void loop() {
unsigned long currentMillis = millis();
if (!initialSequenceComplete) {
// Stage 0: All relays ON for 1 minute
if (currentMillis - previousMillis >= ALL_RELAYS_TIME) {
allRelaysOff();
relayOn(0); // Turn on only relay 1
previousMillis = currentMillis;
currentStage = 1;
initialSequenceComplete = true;
}
}
else {
// Stages 1-6: Each relay gets 10 minutes
if (currentMillis - previousMillis >= SINGLE_RELAY_TIME) {
relayOff(currentStage - 1); // Turn off previous relay
if (currentStage < 6) {
relayOn(currentStage); // Turn on next relay
currentStage++;
} else {
// Restart the sequence from relay 1
relayOn(0);
currentStage = 1;
}
previousMillis = currentMillis;
}
}
}
// Turn ON all relays
void allRelaysOn() {
for (int i = 0; i < NUM_RELAYS; i++) {
digitalWrite(relayPins[i], LOW);
}
}
// Turn OFF all relays
void allRelaysOff() {
for (int i = 0; i < NUM_RELAYS; i++) {
digitalWrite(relayPins[i], HIGH);
}
}
// Turn ON a specific relay (0-7)
void relayOn(int relayNum) {
if (relayNum >= 0 && relayNum < NUM_RELAYS) {
digitalWrite(relayPins[relayNum], LOW);
}
}
// Turn OFF a specific relay (0-7)
void relayOff(int relayNum) {
if (relayNum >= 0 && relayNum < NUM_RELAYS) {
digitalWrite(relayPins[relayNum], HIGH);
}
}
Important Notes:
-
Pin Configuration: Make sure the
relayPinsarray matches your actual wiring (pins 2-9 are used in this example). -
Relay Module Type:
- The code assumes an active-low relay module (LOW = ON, HIGH = OFF)
- If your module is active-high, swap LOW/HIGH in all relay functions
-
Timing:
- 1 minute = 60,000 milliseconds
- 10 minutes = 600,000 milliseconds
- You can adjust these constants if needed
-
Relays 7 & 8:
- These relays are initialized but never used in the sequence (as per your requirements)
- They'll remain OFF throughout operation
-
Reset Behavior:
- The sequence will restart from the beginning if Arduino is reset
- All relays will turn ON for 1 minute again
Would you like me to add any of the following features?
- Serial monitoring for debugging
- External trigger to start the sequence
- Manual override capability
- Non-volatile memory to remember state after power loss
Me:
OK. That is great. What budget should I allow for this project?
It:
Here's a breakdown of the estimated budget for your Arduino 8-relay control project:
Basic Budget Estimate (USD)
-
Arduino Board
- Arduino Uno (clone): $5–$10
- Genuine Arduino Uno: $20–$30
-
8-Channel Relay Module
- 5V 8-relay module (optocoupler isolated): $8–$15
-
Power Supply
- 5V 2A power adapter (for Arduino + relays): $5–$10
- (If relays control high-power devices, add a separate 12V/24V supply)
-
Wiring & Accessories
- Jumper wires, breadboard (optional): $3–$5
- Enclosure (if needed): $5–$20
-
Miscellaneous
- Fuses, terminal blocks, switches (optional): $5–$10
Total Estimated Cost
- Minimum (clone parts, basic setup): ~$20–$30
- Recommended (reliable components, enclosure): ~$40–$60
- Premium (genuine Arduino, industrial relays, safety features): ~$70–$120
Where to Buy
- Budget options: AliExpress, eBay
- Reliable options: Amazon, SparkFun, Adafruit, local electronics stores
Additional Costs (If Needed)
- Sensors (for automation): $5–$20
- LCD display (for status monitoring): $5–$10
- Real-time clock (RTC) module (for timed schedules): $3–$5
Would you like recommendations for specific parts or suppliers based on your location? Also, do you need any modifications to the circuit for high-power loads (e.g., motors, AC devices)?
I'm impressed with its performance at least for simple to describe tasks. I would not necessarily have expected to work without some tweaking, however.
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.