Controling multiple relays via serial

Ok im not going to lie i know absolutly nothing about C what so ever i bought the arduino well to learn but i think i jumped in head deep the project i want to do is pretty simple i want to control 120vac line with a transistor a diode and a resistor and a relay the project is already layed out here

glacialwanderer.com/hobbyrobotics/?p=9#comment-4891

the code is simple and i some what understand it what i want to be able to do is be able to control 2 or 3 or 4 relays to give you a visual idea of what i want is i want to be able to sit at my computer and open putty and open a connection to COM3 be Greated by Press 1 to toggle relay 1 press 2 to toggle relay 2 press 3 to toggle relay 3

then as i press 1 i want it to toggle one pin if i press 1 again i want it to toggle off and same for 2 and 3 on diffrent pins i know im asking to be spoon fed and im sorry but i was hoping some one might be able to mod the code for 1 more relay so i can get any idea how to add more i thank you for your help in advance as im simply lost :frowning:

#define RELAY_PIN 3

void setup()
{
  pinMode(RELAY_PIN, OUTPUT);
  Serial.begin(9600); // open serial
  Serial.println("Press the spacebar to toggle relay on/off");
}

void loop()
{
  static int relayVal = 0;
  int cmd;

  while (Serial.available() > 0)
  {
    cmd = Serial.read();

    switch (cmd)
    {
    case ' ':
      {
        relayVal ^= 1; // xor current value with 1 (causes value to toggle)
        if (relayVal)
          Serial.println("Relay on");
        else
          Serial.println("Relay off");
        break;
      }
    default:
      {
        Serial.println("Press the spacebar to toggle relay on/off");
      }
    }

    if (relayVal)
      digitalWrite(RELAY_PIN, HIGH);
    else
      digitalWrite(RELAY_PIN, LOW);
   }
}

I would suggest you first study the various examples (start with the Blink sketch), and learn how to play with low-voltage stuff first; household current is NOT something you "play" with (not unless you want to lead a short life); trust me, as someone who has been shocked by both household current, an automobile distributor, and a 90V "ringer" phone line (damn that phone call!) - it isn't fun. I got lucky, you may not.

So take it easy, take it slow, you have plenty of time to learn. Go and pick up a "C programming for dummies" book or something (plenty of them out there); study it, learn how to play with C - play with the Arduino and its system. Maybe get into Processing.

Rather than ask others to do your work (and "learning" for you); take it upon yourself to do it - you will get a much better response from the crowd here if you do so.

That, or paypal us some money, first.

:wink:

Perhaps you didn't read my post through Im no stranger when it comes to electronics i could wire this with a push button in a heart beat the problem is the code not the power im dealing with 120 VAC (heck i work with live phase 3 (560volt) lines daily) my questions as stated isn't that of electronics it's of code perhaps some one who has taken these "shocks" should be playing with lower voltage projects

personally i have done the whole blinking led pin 13 thing i have even manipulated it at diffrent intervals delays and durations (simple stuff) i have even made it blink out S.O.S heck i even bridge pin 12 to ground with a small peizo instead of the LED and changed the output pin in the code

but again my problem is with the coding and honestly i don't want to read 500 pages of C for dummies to understand a bunch of useless things for one simple project this would be designed for let alone go through the tuts and personal buy each component to test the and manipulate stuff in the tuts

my problem is simple when i attempted to manipulate the code it seems every second command i issue now is ignored so im assuming due to the lazy shotty code it is just looping back before going to the next task :-/

i would gladly paypal some one to give me a hand but my paypal account was suspended due to not wanting to provide them with utility bills and credit card statments as i did large transactions with them and my other credit card and utility bills are none of there bussiness

if i had some one local to edmonton i would gladly pay them :slight_smile:

-James

This code starts with a #define statement that says that the relay pin is pin 3.

To control multiple relays, you need more statements like this. Change RELAY_PIN to RELAY_PIN1. Then copy and paste that line. Change the 1 to 2, 3, etc. Change the pin # to match the pins that the relays are actually connected to.

In setup, the pinMode function says that the relay pin is an output pin. You need multiple statements like this - one for each relay.

Then, you establish communication with the serial port, and send some data to the port. Change the message sent, to something like:

Serial.println("Press a number from 1 to n to toggle a relay on/off");

(Change n to however many relays you have.)

Then, in loop, you have a variable that defines the state of the relay - relayVal.

This is declared static so that a new instance is not created during each pass through loop. This would be better as a global variable, declared outside of loop. The static keyword would not be needed, then.

It would also be better if this was a boolean variable, since the relay is either on (true) or off (false).

boolean relay1State = false; // Assume off to start with
boolean relay2State = false;

Add however many of these you need.

Then, you check whether there is serial data, or not. If there is, you read the next character. Then, you do something based on that character.

If the character is a space, you toggle the relay. If not, you send the prompt again.

Change the case ' ': statement to case '1':, and the relayVal ^= 1; statement to relay1State = !relay1State;

case '1':
{
   relay1State = !relay1State; // If true, make false. If false, make true
   digitalWrite(RELAY_PIN1, relay1State);
}

Add additional cases for 2, 3, 4, etc.

Get rid of the if/else block at the end of loop. The relay setting has already been done.

PaulS thank you your a god send :slight_smile: plus your idea made the code so much more easyer :slight_smile: this is what i ended up with

#define RELAY1 13
#define RELAY2 12

void setup()
{
  pinMode(RELAY1, OUTPUT);
  pinMode(RELAY2, OUTPUT); 
  Serial.begin(9600); // open serial
  Serial.println("Press 1 or 2 to toggle relay on/off");
}
boolean relay1State = false; // Assume off to start with
boolean relay2State = false;
void loop()
{
  static int relayVal = 0;
  int cmd;

  while (Serial.available() > 0)
  {
    cmd = Serial.read();

    switch (cmd)
    {
   case '1':
{
   relay1State = !relay1State; // If true, make false. If false, make true
   digitalWrite(RELAY1, relay1State);
   break;
} 
   case '2':
{
   relay2State = !relay2State; // If true, make false. If false, make true
   digitalWrite(RELAY2, relay2State);
   break;
} 
   default:
        {
          Serial.println("There are only 2 options Relay 1 or Relay 2");
      }
    }
  }
  }

now im just trying to figure out how to have it print the relay state as when it is on or off :slight_smile:

Cheers again truly appreciated even if i can't figure out the stupid Serial.println

even if i can't figure out the stupid Serial.println

Well, maybe if you'd talk nice about it, it would work for you. :smiley:

Or, perhaps explain what problem you are having with it.

I think what he is talking about is after the relay is toggled, he wants feedback on his serial monitor that tells him such.

So, if I made the correct assumption, here is what I would do.

In each of your cases of your switch, add the following code:

if (relayxState = true)
{
Serial.println("Relay x is ON");
}
else
{
Serial.println("Relay x is OFF");
}
Where 'x' is the relay number associated with the particular case you are working in. :-?

Serial.print and Serial.println do two different things. The Serial.print syntax outputs whatever you put within quotation marks in the parenthesis, but does not add a return to the end of the line.

Serial.println does exactly the same thing, except it adds a carriage return at the end of the line.

So, Serial.print(x) in a for loop where x is increased by one each time will output:
123456789101112(etc...)

Serial.println(x) in the same for loop will output:
1
2
3
4
5
6
7
8
9
10
11
12
(etc...)

Perhaps you didn't read my post through Im no stranger when it comes to electronics i could wire this with a push button in a heart beat the problem is the code not the power im dealing with 120 VAC (heck i work with live phase 3 (560volt) lines daily) my questions as stated isn't that of electronics it's of code perhaps some one who has taken these "shocks" should be playing with lower voltage projects

First off, calm down.

Second - yes, maybe I should play with lower voltage projects; in fact, I mostly do - I know my limits, you apparently don't (otherwise you wouldn't have started this project, jumping in head-first, right?).

Third:

You never said anything about having electronics or electrical knowledge, you presented some code and some frustration; most people who post as you do either have knowledge of one or the other, rarely do people have both (which I don't understand, especially when it comes to computers and microprocessors; software is hardware virtualized, hardware is software made "real" - otherwise emulators wouldn't exist, nor would microcode work, nor would the ENIAC have been able to perform loops - its "code" was all switches and wires!).

I guess I made the wrong assumption; I had a 50/50 chance; I appologize.

With that said, I still suggest you at least attempt to learn how to code; it will serve you in good stead. It isn't that difficult if you have a grasp of basic process flow understanding, as well a boolean logic (and a bit of algebra and math, when and where it is needed). I don't understand the apparent hostility towards learning something that can only help you in your understanding of the underlying hardware; I am sure that you didn't come by your other knowledge of electronics via divine intervention or what-had-you. You likely were shown how hands-on, and/or read some books on electrical/electronic theory, right? The same is true of programming - no one just sits down and starts coding (although here I will give Ada Lovelace props for not only being able to write a working program to calculate Bernoulli numbers for Babbage's Analytical Engine designs, but she did so "blind", with no hardware at all - that's skill).

So please; heed my suggestion to learn this stuff - it will only help you in the long run, and you can pass on what you learn to others. Hopefully people who are helping you here to understand the code aren't acting in vain, and you will learn how the code works by seeing and understanding the code being presented to you. Good luck, and I hope your project turns out the way you expect!

:slight_smile:

Now for what I think are the really cool ideas once you get it working...

  1. Switch over to using Solid State relays instead of transistors and solenoids... you get simpler interfacing, quiet operation, higher current capacity options, faster switching and options like "dimming" with PWM (though that last one is untested by me).

  2. Get the Ethernet shield. Code up a telnet listener. Turn things on and off from the Telnet connection.

WC - a very good explanation of serial.print vs serial.println.

and I do like your tag line - "who needs a volt meter...." - I've known electricians like that... mostly they only tested 120vac that way - 120vac tingles, 277vac.... well - that HURTS!!! :-X

Ken H.

I got unlucky with the phone line - I was adding a new line at a new house my wife and I were renting, and forming the wire around the screw at the junction box, and wouldn't you know that someone picked just that moment to call us?

Getting shocked by the automobile ignition happened on an orange fur covered VW on the first morning of my first day at Burning Man (the car wouldn't start; ended up being burned up fuel pump wiring - I got it fixed, I was the hero of that camp, they made me an AWESOME turkey sandwich for lunch - sadly, the car was burned to the ground at Thunderdome; I guess it was destined to die)...

:smiley:

If that VW was an older 6 volt version it wasn't too bad, the 12 vdc ignitions are more voltage on the spark plug - but if you really want to "ring your chimes" grab the coil wire on a racing magneto - some those can hit 70K volts!! Still tingles thinking about that.... but for a solid "hurt" one leg of a 3 ph 480vac to ground (277vac) really "jolts".

Been "tingled" with 120vac so many times over the yrs I tend to forget just how dangerous it really is.

Ken H>

I know phone ringer voltage intimately... well.. my arm does after I leaned up against a phone cutdown rack (one of these --> http://www.shutterpoint.com/Photos-ViewPhoto.cfm?id=438987) a few times.

Also reminds me of when I was experimenting with multiple neon lamps in the 70's. (total noob) Many things went pop... much copper melted... eyesight temporarily lost...

Dad rushed in to see what I did... I said "experimenting"

I wished I'd said what I realized I'd learned as a result... but that understanding came with time.

"It's not really experimenting until things go horribly wrong."

cr0sh your right i grossly overeacted and was hostile im sorry i do infact have basic electronic knowledge i think it was just a late night i was very frusterated and the ol lady was being grumpy that i converted our dinning area into a hobby workshop :stuck_out_tongue: non the less im sorry i don''t have a fantastic knowledge in electronics but enough to get me by i think the only realy jolts i have gotten in my life was when fixing the wireing on a phase 3 560v welder and the welder up the shops by some chance of stopped working for some lovly fate of god and thought i unplugged his and plugged mine back in while working on it 100% my fault should have locked out the plug i got some nasty burns and nerve damage and other then that not a whole hell of alot more other then licking a 9volt as a kid to see if it's dead or not lol

as to WileyCoyote cheers you know i was almost 100% i tried that exact thing but i must have bugger something :slight_smile: appreciate it mate

-James