Arduino – Controlling relays

Arduino project – Controlling relays

Introduction

(We = Mikko and Oskari)

We were given an assignment to do arduino project, present demo in class and publish documentation in the web.

So, if you are reading this post and wonder what we are talking about, arduino is open-source single-board microcontroller. Basically, you can program pretty much anything on arduino and make cool robots and gadgets.

Our idea for this project was to make remote controlled relay switch which could be operated by internet browser. For example, you could switch your external hard-disk on and off from your phone or any other location.

Originally, we were interested in controlling mains current by using relays. To have some coffee brewed at morning, for example. We quickly realized that working with mains current would be pretty tricky, not to mention risky at the same time. After a little brainstorming, we decided to stick with  lower-voltage devices such as computer fans and small lights (5-24 volts). For this we happened to have transformer with input of 220-230V 50Hz and output of 12V, making it ideal for dealing with low-voltage electronic devices. As we didn’t have much experience in working with electronics and were lacking power meter, getting relay controller circuit working properly took some time first. Luckily, we were able to borrow one for this project. First we worked out from which terminals voltage was running and from there it got easier.

We had problems getting mobile application working. Arduino rebooting itself when trying to switch relays through android phone. We couldn’t solve this problem and thus abandoned idea of mobile operation. Second big problem was figuring out relays terminals output of power. At first, we assumed that arduino would supply power to the device connected to it, which was not the case. We tried to find datasheet or other information about this matter, but only ended up with some electrical schematics which we didn’t understand at all. Luckily, we were able to borrow power meter from our friend and figured out which pins gave out voltage. This made it much easier to complete proper circuit between the devices. One relay terminal consist of 3 pins, one being normally open, one common connection and the last one normally closed. The device had to be hooked onto common connection pin from its positive output and the power supplier to normally closed one. Then relay would switch this circuit on and off.

The setup

 

We found an old project of Mikko’s which consists of speaker, pre-programmed micro chip, button and some soldered wires. It was operating with 1,5V batteries so a bit less than what our transformer outputs. Being curious to hear some sounds and demo this relay with both computer fan and speaker connected to it, we decided to give it a try. It worked nicely and it still does!

Fritzing made circuit diagram

 

List of parts

Quantity           Part number             Description                                                Price

1                           DEV-00666            Arduino Main Board(Duemilanove)      €22.90

1                           DEV-09026            Arduino Ethernet Shield(v2)                   €31.00

1                           EA-040402             Opto-Isolated 8 Channel Relay Board   $19.50

6                           –                                            Wires                                                  –

1                           –                                            12v output transformer                   –

1                           –                                            5v output transformer                     –

+ multi-tool, power meter, low-voltage devices

Code

#include <SPI.h> // for device communication

#include <Dhcp.h> // configuration for ethernet shield

#include <Dns.h> // deals with dns traffic and gets hosts IP

#include <Ethernet.h>

#include <EthernetClient.h>

#include <EthernetServer.h>

#include <EthernetUdp.h>

#include <util.h>

#include <WebServer.h>

WebServer server(“”, 80);

boolean state[4];

byte mac[] = { // change this to your own unique value

0×00, 0xAA, 0xBB, 0xCC, 0xDE, 0×02 };

void ui(WebServer &server, WebServer::ConnectionType type, char *tail, bool tail_complete) {  // codiqa was used to do the framework, http://jquerymobile.com/

server.httpSuccess();

P(html1) = // store the HTML in program memory using the P macro

“<!DOCTYPE html>\n”

“<html>”

“    <head>\n”

“        <meta charset=’utf-8′ />\n”

“        <meta name=’viewport’ content=’width=device-width, initial-scale=1′ />\n”

“        <title>\n”

“        </title>\n”

“        <link rel=’stylesheet’ href=’http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css’ />\n”

“        <style>\n”

“          .ui-slider-switch { width: 100%!important }”

“        </style>\n”

“        <script src=’http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js’>\n”

“        </script>\n”

“        <script src=’http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js’>\n”

“        </script>\n”

“    </head>\n”

“    <body>\n”

“        <div data-role=’page’ id=’page1′>\n”

“            <div data-role=’content’>\n”

“<form action=’form’ method = ‘post’>\n”

“     <select name=’rele1′ data-role=’slider’>”;

server.printP(html1);

// defines and shows all relay buttons

if (state[0]){

server.print(“        <option value=’0′>Relay 1 Off</option>\n”);

server.print(“        <option selected=’selected’ value=’1′>Relay 1 On</option>\n”);

}

else{

server.print(“        <option selected=’selected’ value=’0′>Relay 1 Off</option>\n”);

server.print(“        <option value=’1′>Relay 1 On</option>\n”);

}

P(html2) =  “      </select>\n”

“      <br />\n”

“     <select name=’rele2′ data-role=’slider’>”;

server.printP(html2);

if (state[1]){

server.print(“        <option value=’0′>Relay 2 Off</option>\n”);

server.print(“        <option selected=’selected’ value=’1′>Relay 2 On</option>\n”);

}

else{

server.print(“        <option selected=’selected’ value=’0′>Relay 2 Off</option>\n”);

server.print(“        <option value=’1′>Relay 2 On</option>\n”);

}

P(html3) =  “      </select>\n”

“      <br />\n”

“     <select name=’rele3′ data-role=’slider’>”;

server.printP(html3);

if (state[2]){

server.print(“        <option value=’0′>Relay 3 Off</option>\n”);

server.print(“        <option selected=’selected’ value=’1′>Relay 3 On</option>\n”);

}

else{

server.print(“        <option selected=’selected’ value=’0′>Relay 3 Off</option>\n”);

server.print(“        <option value=’1′>Relay 3 On</option>\n”);

}

P(html4) =  “      </select>\n”

“      <br />\n”

“     <select name=’rele4′ data-role=’slider’>”;

server.printP(html4);

if (state[3]){

server.print(“        <option value=’0′>Relay 4 Off</option>\n”);

server.print(“        <option selected=’selected’ value=’1′>Relay 4 On</option>\n”);

}

else{

server.print(“        <option selected=’selected’ value=’0′>Relay 4 Off</option>\n”);

server.print(“        <option value=’1′>Relay 4 On</option>\n”);

}

P(html5) =

“      </select>\n”

“<input type=’submit’ value=’Set’ />”

“</form>\n”

“            </div>\n”

“        </div>\n”

“    </body>\n”

“</html>”;

server.printP(html5);

}

// this code defines using our “set” key to control relays on and off

void form(WebServer &server, WebServer::ConnectionType type, char *tail, bool tail_complete) {

char name[32];

char value[32];

if (type == WebServer::POST) {

while (server.readPOSTparam(name, 32, value, 32))

{

if  (strcmp (name,”rele1″) == 0){

state[0] = atoi(value);

if(!state[0]){

closeRelay(1);

}

else{

openRelay(1);

}

}

if  (strcmp (name,”rele2″)== 0){

state[1] = atoi(value);

if(!state[1]){

closeRelay(2);

}

else{

openRelay(2);

}

}

if  (strcmp (name,”rele3″)== 0){

state[2] = atoi(value);

if(!state[2]){

closeRelay(3);

}

else{

openRelay(3);

}

}

if  (strcmp (name,”rele4″)== 0){

state[3] = atoi(value);

if(!state[3]){

closeRelay(4);

}

else{

openRelay(4);

}

}

}

}

server.httpSeeOther(“index.html”);

}

void setup() {

//trick which prevents relay terminals from going on when starting up

digitalWrite(14, HIGH);

digitalWrite(15, HIGH);

digitalWrite(16, HIGH);

digitalWrite(17, HIGH);

//set pins 14-17 as output

pinMode(14, OUTPUT);

pinMode(15, OUTPUT);

pinMode(16, OUTPUT);

pinMode(17, OUTPUT);

state[0] = false;

state[1] = false;

state[2] = false;

state[3] = false;

Serial.begin(9600); //adding serial port

Serial.print(“Starting “);

Ethernet.begin(mac); // ethernet shield recieves IP-address automatically

String ip;

Serial.print(” My IP address: “);

for (byte thisByte = 0; thisByte < 4; thisByte++) {

// print the value of each byte of the IP address:

ip += Ethernet.localIP()[thisByte];

ip += “.”;

Serial.print(Ethernet.localIP()[thisByte], DEC);

Serial.print(“.”);

}

Serial.println();

server.begin();

server.setDefaultCommand(&ui);

server.addCommand(“index.html”, &ui);

server.addCommand(“form”, &form);

}

void loop() {

server.processConnection();

}

void openRelay(byte channel) {  //method which opens relays

switch (channel) {  //choosing switch-case

case 1:   //case 1 means byte channel=1

digitalWrite(14, LOW);   // connects digital output 14 to ground

state[channel-1] = true;   // sets value for relay’s cell

break;

case 2:

digitalWrite(15, LOW);

state[channel-1] = true;

break;

case 3:

digitalWrite(16, LOW);

state[channel-1] = true;

break;

case 4:

digitalWrite(17, LOW);

state[channel-1] = true;

break;

}

}

void closeRelay(byte channel) { // closes relays

switch (channel) {

case 1:

digitalWrite(14, HIGH);

state[channel-1] = false;

break;

case 2:

digitalWrite(15, HIGH);

state[channel-1] = false;

break;

case 3:

digitalWrite(16, HIGH);

state[channel-1] = false;

break;

case 4:

digitalWrite(17, HIGH);

state[channel-1] = false;

break;

}

}

Mainokset

Simple demo with serial monitor and LED’s

I decided to do little experiment with arduino serial monitor feature.

My goal was to connect two LED’s to my ATMEGA328 -chip and make them go on and off one at a time when certain letters were typed into serial monitor console.
Serial monitor is used, for example, to print out values from sensor readings making them visible to human eye. The serial port has to be taken into use typing Serial.begin(9600); in the code under void setup() .

Here’s the code I used to do this simple demo.

void setup(){

Serial.begin(9600);    // opens serial port and sets data rate to 9600 bytes per second

pinMode(9, OUTPUT);     // sets pins 9 and 8 as output
pinMode(8, OUTPUT);

}

void loop (){            // here we set loop which reads keys typed into serial monitor console

if (Serial.available()) {

char ser = Serial.read();

if(ser == ’a’){        /* defines that if exactly letter  ”a”  is typed, LED connected to pin number 9 is set to HIGH, meaning its on and at the same time pin 8 is set LOW /*

digitalWrite(9, HIGH);
delay(100);
digitalWrite(8, LOW);
delay(100);

}else if(ser == ’b’){    // the same things as before, only with letter ” b ”

digitalWrite(9, LOW);
delay(100);
digitalWrite(8, HIGH);
delay(100);

}
}

}

Testing Micro Servo HD-1600A and solving some Windows 7 – compatibility problems

I got my hands on this little servo and decided to test it out. I didn’t have arduino development software installed on my computer running Windows 7, so I decided to install that also. I surfed to http://arduino.cc/en/Main/Software and downloaded the required files to my computer. Everything went smoothly until I tried to upload code to my ATMEGA328-chip. Windows 7 didn’t install the necessary drivers by itself.

This was quickly fixed with a little googling around and I found instructions to manually install required drivers. All it took was to go into control panel -> system and security -> Device Management and section ”Other devices” . There it was with a yellow question mark. Right-click and install drivers, searching the arduino package I just downloaded (it includes the drivers) , and choosing the drivers folder and clicking next. Drivers installed correctly.

Second problem I had was this weird error message when I tried to upload some code to my chip: avrdude: stk500_getsync(): not in sync: resp=0x00

I found out that this is very common error in arduino since it just means that the device isn’t responding, for whatever reason. First, I booted my computer and tried again. Didn’t work. I went back to check the drivers and noticed they had been uninstalled for some reason? I installed them again like the first time, and now it showed device COM1 (like first time) and new one, COM8. I decided to try out this new found port since the first one wasn’t responding and there it was, worked. I don’t know what might have caused this, apparently it might be just a bug.

After these efforts, I ran this example code succesfully found in arduino development software and it made the rotor turn around 180 degrees:

// Sweep
// by BARRAGAN <http://barraganstudio.com&gt;
// This example code is in the public domain.
#include <Servo.h>

Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created

int pos = 0; // variable to store the servo position

void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop()
{
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable ’pos’
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable ’pos’
delay(15); // waits 15ms for the servo to reach the position
}
}

Sensor I’d like to try out

I was searching the web for different sensors for arduino projects and I found myself interested in this particular one. It is SeeedStudio SEN92355P Grove Moisture Sensor. This easy-to-use sensor is meant to observe and gather data about its surrounding moisture levels.

Here is the link to datasheet http://www.domko.ru/pdf/SEEEDUIN/SEN92355P.pdf .

I found it very interesting because there might be good project for me to do with this as I was planning planting some herbs anyway as spring is coming and weather getting nice and warm. I could use this sensor with arduino to set-up a little intelligent gardener device. It would keep an eye on when the soil is getting too dried up and give out and alarm meaning the herbs need watering. And I must admit, sometimes I simply forget to water my plants so this would serve good practical use for me. It would also be interesting application as it kind of lets plants to communicate with a human in a way of asking help (watering) when they need it.

Here’s a practical demo-code for this sensor, which basically reads it and prints out how moist there is, wherever it is. Simple and effective.

 

 

int sensorPin = A0;    // select the input pin for the potentiometer

int sensorValue = 0;  // variable to store the value coming from the sensor

void setup() {

// declare the ledPin as an OUTPUT:

Serial.begin(9600);

}

void loop() {

// read the value from the sensor:

sensorValue = analogRead(sensorPin);

delay(1000);

Serial.print(”sensor = ” );

Serial.println(sensorValue);


}

You can purchase this sensor from  http://www.seeedstudio.com/depot/grove-moisture-sensor-p-955.html  for the price of 4 dollars and 99 cents, so its not very expensive either, which only makes it better.

http://www.eio.com also has some in stock but for a whopping price of $5.95 , what a ripoff…


Arduino sensor AD5220 Increment/Decrement Digital Potentiometer

I was given assignment to try and test out this particular sensor (AD5220) on Arduino Duemilanove ATMEGA328.

I tied to google information about it and its properties/uses, and found only somewhat little. Only thing I found out, is that it is digital potentiometer to control voltage’s. One good thing
is that I found the datasheet for this component as .pdf  AD5220 datasheet  . Unfortunately, I did not find any way to test out this sensor as it is. It can clearly be used, for example, to control voltage’s incoming to LED lights thus making them brighter/dimmer at will.

 

 

 

 

First Arduino experience

I did my first experiment in Arduino environment on linux ubuntu recently.

I started off with some basic  components:

3 LED lights, microchip controller Arduino Duemilanove (ATMEGA328), breadboard for connecting components, couple wires in different colors and UBS cable to connect my chip into PC.

 

When starting in Arduino development environment, first you need to download and install Arduino software package from packet management. It can be found by searching for “Arduino”. The program itself is pretty clear and efficient, kinda reminds me of VLC media player.  On installing you have to give program certain rights and reboot might be needed afterwards.

One thing I had some problems at first was the default setup in Arduino development software for chip-model. You have to choose chip you are using from the Board – tab. You can check what kind of chip you have from markings on it, its written on some sticker or on the board itself. So in my case I changed the board setting to “Arduino Duemilanove”.

Now, my goal to achieve with these new tools was to get the 3 LED’s blink repeatedly every one at a different time. So it would look like continuous horizontal blinking.  I used the “demo code” from Arduino program itself and modified it a bit for my use. There are several of these demo codes available, like blinking LED’s or fading them etc. You can find these codes from top navigation bar.

When you connect wires from your chip to breadboard, it powers the whole row horizontally. Here’s a simple picture about how I did my connections.

 

Yellow dots are other end of wires, black ones are LED’s negative pin and red ones are positive (LED has little notch on the negative side) . Blue lines and box represent the chip itself where wires are connected.

 

And here’s the code I used

/*

Christmastlight, sets leds on and off repeatedly on rows.

*/

 

void setup() {

// Sets told pins as output source

pinMode(13, OUTPUT);

pinMode(10, OUTPUT);

pinMode(11, OUTPUT);

}

void loop() {

digitalWrite(10, HIGH);   // LED on

delay(100);              // wait 0,1 seconds (100 milliseconds)

digitalWrite(10, LOW);    // LED off

delay(100);

 

digitalWrite(13, HIGH);

delay(100);

digitalWrite(13, LOW);

delay(100);

digitalWrite(11, HIGH);

delay(100);

digitalWrite(11, LOW);

delay(100);

}

Hello, world! – Javalla sekä Pythonilla+Tietokoneen sisuskalut

  • Hello world, javalla ja pythonilla.

Javalla:

public class HelloWorld {
public static void main(String[] args)
{
System.out.println(”Hello World!”);
}
}

Python:

print “Hello, world!”

 

 

Javakoodia kokeilin Eclipse Classic 3.7.1 , joka on saatavissa eclipsen omilta sivuilta täältä http://www.eclipse.org/downloads/ .

Myös Pythonilla on oma ilmainen ohjelmansa, sekin on ilmainen ja lisäksi avointa lähdekoodia http://www.python.org/download/ .

  • Tietokoneeni sisältö