Project tutorial
Arduino and PC control Power Cycle of a Device

Arduino and PC control Power Cycle of a Device © GPL3+

Connecting a PC with a microcontroller( Arduino, LoRa etc ) offers an easy way to control the power cycle of any device.

  • 4 views
  • 0 comments
  • 0 respects

Components and supplies

Necessary tools and machines

About this project

My grand-father turned to me for help. The business he worked for, needed PCs to control Power Cycle of data terminalsconnected to PC.

I found The IoT Power Relay to be the right power device. It is acontrollable power relay equipped with four outputs. The IoT Power Relay allowseasily to control the power going to a device with an Arduino, Raspberry Pi orother single-board computer or microcontroller.

The IoT Power Relay is designed to allow safely to control an outlet device that operates at 3--48VDC or 12--120VAC. Each IoT Power Relay features a singleinput (from the included C13 power cable) to four outputs: one normally on, onealways on, and two normally off. The durable SPDT control relay is rated at30/40A, for 400,000 operations.

1) Concept

PC decides when topower cycle its terminal or in which time window to keep the terminal OFF. Toturn ON or OFF the terminal, PC sends a proper input to Arduino which switchesON/OFF the power 112V relay. I designed the following configuration:

-Arduino connected viaUSB to the PC which is the host of the data terminal

-Arduino connected to the input of The IoT Power Relay

-the power cord of the data terminal plugged to the normally OFF output of The IoT Power Relay

2) Implimentation

I elected to use Snapino ( Arduino + Snap Circuits ) sold @ Amazon. It comes with a base board & LEDs which Iapplied to visualize different states.

-2.1) Interfacing the relay modules to the Arduino

the '-'terminal of the relay box must be routed to GND and the '+' terminal to pin D11on the Snapino.

-2.2) Interfacing Arduino to the PC

For 2-way communication between the PC & the Arduino the Serial link over the USB port.

-2.3) Visualization of States

To display the status of the logical connection between PC & Arduino I routeda RED LED from Arduino’s pin 10 to ground over 100Ohm

To display the status of the input to the relay I connected a GREEN LED from pin11 to GRND

-2.4) Software

We need2 applications:

-Arduino sketch, shown in the CODE section

-C# or Python app on PC

The PC app establishes the serial connectionand sends "@@@\n" to Arduino. This text makes Arduino to follow the 2 commands from PC:

-OFF( 3 char )

-ON-( 3 char )

The PC app runs in one of the 2 modes: attended and unattended. In the latter mode the app is activated with a parameter from another main PC application. Like example: at a specific time the host application may issue one of the commands:

- ComputerToArduino.exe /TurnOn

- ComputerToArduino.exe /TurnOff

- ComputerToArduino.exe /Probe to interrogate the relay state

-2.4.2) PC app in C#

shown in the CODE section

-Screenshot

-2.5) Deployment

Arduino USB driver must be installed on eachPC which needs to power cycle its terminal

3) Results: 4 units were deployed in Spring of 2019. They work flawlessly since then.

Code

Arduino controls The IoT Power RelayArduino
PC decides when to power cycle its terminal or in which time window to keep the terminal OFF. To turn ON or OFF the terminal, PC sends a proper input to Arduino which switches ON/OFF the power 112V relay. I designed the following configuration:
-Arduino connected via USB to the PC which is the host of the data terminal
-Arduino connected to the input of The IoT Power Relay
-the power cord of the data terminal plugged to the normally OFF output of The IoT Power Relay
#include <LiquidCrystal.h>

String inputString = "";         // incoming data buffer
boolean stringComplete = false;  // whether the string is complete
String commandString = "";

int relay = 11;
int ledPin = 10;// to visualize serial connection state

boolean isConnected = false;

void setup() {
  Serial.begin(9600);
  pinMode(relay,OUTPUT);
  pinMode(ledPin,OUTPUT);
  //
 digitalWrite(relay,HIGH);
 delay(7000);
 digitalWrite(relay,LOW); }

void loop() {
  if(stringComplete)
{
  stringComplete = false;
  getCommand();
    
 if(commandString.equals("@@@")) // serial connection
  {
    digitalWrite(ledPin,HIGH);
    String power = "DOWN";
    if (digitalRead(relay)==HIGH)
    { power ="UP";}
    Serial.print(power); 
  }
if(commandString.equals("###")) // 
  { digitalWrite(ledPin,LOW);}

if(commandString.equals("ON-"))
  { turnCloverON(relay);}
  else if(commandString.equals("OFF"))
  {  turnCloverOFF(relay); }
  //
   inputString = "";

}// end of stringComplete test
}//end of loop
//============================================
boolean getLedState()
{
  boolean state = false;
  if(inputString.substring(5,7).equals("ON"))
  {
    state = true;
  }else
  {
    state = false;
  }
  return state;
}
//============================================
void getCommand()
{
  if(inputString.length()>0)
  {
    digitalWrite(ledPin,HIGH);
    // CloverON
     commandString = inputString.substring(0,3);
     //Serial.print(commandString);
  }
}
//=================================================
void turnCloverON(int pin)
{
  digitalWrite(pin,HIGH);
 //  digitalWrite(ledPin,HIGH);
  
}

void turnCloverOFF(int pin)
{
  digitalWrite(pin,LOW);
}
//====================================================
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}
C# Controls ArduinoC#
We need 2 applications:
-Arduino sketch
-C# or Python app on PC

The PC app establishes the serial connection and sends "@@@\n" to Arduino. This text makes Arduino to follow the 2 commands from PC:
-OFF( 3 char )
-ON-( 3 char )
The PC app runs in one of the 2 modes: attended and unattended. In the latter mode the app is activated with a parameter from another main PC application.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Diagnostics;
using System.Threading;

namespace ComputerToArduino
{
    public partial class Form1 : Form

    {
       static bool awaitingSerial= false;
        static string indata = ""; 
        bool isConnected = false;
        String[] ports;
        SerialPort port;
   
        string sMsg = Environment.NewLine + System.DateTime.Now.ToString() + " ";//+

        public Form1()
        {
            InitializeComponent();
            // 
            checkBox1.Enabled = false;
            getAvailableComPorts();
           


            foreach (string port in ports)
            {
                comboBox1.Items.Add(port);
                Console.WriteLine(port);
                if (ports[0] != null)
                {
                    comboBox1.SelectedItem = ports[0];
                }
            }
        }
      
        private void button1_Click(object sender, EventArgs e)
        {
            if (!isConnected)
            {
                connectToArduino();
            } else
            {
                disconnectFromArduino();
            }
        }

        void getAvailableComPorts()
        {
            ports = SerialPort.GetPortNames();
            //MessageBox.Show(ports.Length.ToString());
        }

        private void connectToArduino()
        {
            if (ports.Length==0)
            {
                MessageBox.Show("No Arduino Board has been found!");
                return;
            }
            isConnected = true;
            string selectedPort = comboBox1.GetItemText(comboBox1.SelectedItem);

            port = new SerialPort(selectedPort, 9600, Parity.None, 8, StopBits.One);
            indata = "";
            port.Open();
            port.Write("@@@\n");
            button1.Text = "Disconnect";
            awaitingSerial = true;

            Thread.Sleep(700);
            while (port.BytesToRead != 0)
            {
               // byte
                var currByte = port.ReadByte();
                  //  .ReadByte();
                indata += Convert.ToChar(currByte).ToString();
            }




            //
           // MessageBox.Show(indata);
            relayState.Text = indata;
            if ((indata == "UP") ||
                (indata == "P"))
            { checkBox1.Checked = true; }
            else
            { checkBox1.Checked = false; }
            //Thread.Sleep(1000);
            relayState.Text = indata;
            //
            enableControls();
            checkBox1.Enabled = true;
        }
        private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            var serialPort = (SerialPort)sender;
            var data = serialPort.ReadExisting();
           // ProcessData(data);
        }
        private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
 
            SerialPort sp = (SerialPort)sender;
            indata = sp.ReadExisting();
          
            awaitingSerial = false;
           // Debug.Print("Data Received:");
           // Debug.Print(indata);
          //  MessageBox.Show("Data Received:" + indata);

        } 
        private void Led1CheckboxClicked(object sender, EventArgs e)

        {
            if (isConnected)
            {
                if (checkBox1.Checked)
                {
                    //MessageBox.Show("OOOONNNN");
                    port.Write("ON-\n");
                    
                    relayState.Text = "UP";
                }
                else
                {
                    port.Write("OFF\n");
                   // checkBox1.Text = "Off";
                    relayState.Text = "Down";
                   // checkBox1.BackColor = Color.AntiqueWhite;
                }
            }
            if (checkBox1.Checked)
            {
                checkBox1.Text = "ON";
                checkBox1.BackColor = Color.LightGreen;
            }
            else
            {
                checkBox1.Text = "Off";
                checkBox1.BackColor = Color.AntiqueWhite;
            }
        }

       

        private void disconnectFromArduino()
        {
            isConnected = false;
            port.Write("###\n");
            port.Close();
            port.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedHandler);
            button1.Text = "Connect";
            disableControls();
            checkBox1.Enabled = false;
            resetDefaults();
            relayState.Text = "unknown";
            checkBox1.Checked = false;
            //Thread.Sleep(1000);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (isConnected)
            {
              //  port.Write("#TEXT" + textBox1.Text + "#\n");
            }
        }

        private void enableControls()
        {
            checkBox1.Enabled = true;
           // checkBox2.Enabled = true;
           // checkBox3.Enabled = true;
           // button2.Enabled = true;
           // textBox1.Enabled = true;
           // groupBox1.Enabled = true;
            //groupBox3.Enabled = true;

        }

        private void disableControls()
        {
          //  checkBox1.Enabled = false;
           // checkBox2.Enabled = false;
           // checkBox3.Enabled = false;
           // button2.Enabled = false;
           // textBox1.Enabled = false;
           // groupBox1.Enabled = false;
          //  groupBox3.Enabled = false;
        }

        private void resetDefaults()
        {
            checkBox1.Checked = false;
            //checkBox2.Checked = false;
            //checkBox3.Checked = false;
            //textBox1.Text = "";
            
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            //
            //    start parameters 
            //
            string[] args = Environment.GetCommandLineArgs();

            // The first commandline argument is always the executable path itself.

            if (args.Length == 1)  // no parameters
            {

            }//--- n0 parameters
            //TurnOn
            //
            if (args.Length > 1)
            {
                //
                sMsg += button1.Text + Environment.NewLine;
                //
                if (Array.IndexOf(args, "/TurnOFF") != -1)
                {
                    sMsg += Environment.NewLine+"/TurnOFF";
                    button1.PerformClick();
                    if (button1.Text == "Disconnect")
                    {
                        sMsg += "=Connected" + "/state:" + checkBox1.Text;
                        //
                        if (checkBox1.Text == "ON")
                        {
                             checkBox1.Checked = false;
                            if (checkBox1.Text == "Off")
                            {
                                sMsg += Environment.NewLine + " "+
                                "Clover power:OFF" + Environment.NewLine;
                               
                            }
                            //
                        }// flip OFF state
                    }// connected
                   
                }//  turn OFF parameter
                //---------------------------------------------
                 if (Array.IndexOf(args, "/TurnOn") != -1)
                    {
                        sMsg += Environment.NewLine + "/TurnOn";
                        button1.PerformClick();
                        if (button1.Text == "Disconnect")
                        {
                            sMsg += "=Connected" + "/" + checkBox1.Text;
                            //
                            if (checkBox1.Text == "Off")
                            {
                                checkBox1.Checked = true;
                                if (checkBox1.Text == "ON")
                                {
                                    sMsg += Environment.NewLine + " " +
                                    "Clover power:ON" + Environment.NewLine;
                                   
                                }
                                //
                            }// flip OFF state
                        }// connected in state ON

                        
                    }// "/TurnOn" patameter
                //------------------------------------------
                //
                // probe POWER state
                //
                 //---------------------------------------------
                 if (Array.IndexOf(args, "/probe") != -1)
                 {
                    if ( ISConnection() )
                    {
                       sMsg += Environment.NewLine + "/cmd:probe";
                       PowerStateIS();
                    }// connected
       
                 }// "/probe" patameter
                 System.IO.File.WriteAllText("C:\\IT\\POS\\Arduino2Clover\\CloverPower.txt", sMsg);
                 System.Windows.Forms.Application.Exit();
            }//-------   runtime parameters end -----------------
        }
        //============================
        void PowerStateIS()
        {
            sMsg += Environment.NewLine + " ";
            string s = "Clover power:";
            string powerState = checkBox1.Text;
           
            sMsg += s+powerState + Environment.NewLine;

        }
        //========================================
        bool ISConnection()
        {
            bool lConnected= false;
            sMsg += Environment.NewLine;
            //
            
            button1.PerformClick();
            if (button1.Text == "Disconnect")
            {
                lConnected = true;
                sMsg += "=Connected" + "/state:" + checkBox1.Text;
            }
            else
            { sMsg += "=DisConnected" + "/state:UNDEFINED"; }
            
            //
             return (lConnected);
        }
        //==================================================
        //==============================
    }
}

Schematics

PC Controls 112V
PC and Arduino control power cycle of terminal connected to PC
Pccontrols112volt g5unfevnxg

Comments

Similar projects you might like

Blinds (Or Any AC Power Motor) Control

Project tutorial by gomecin

  • 24,166 views
  • 41 comments
  • 85 respects

Take Control Over Lego Power Functions

Project tutorial by Patrick Müller

  • 62,607 views
  • 5 comments
  • 77 respects

Hacking A RC Car To Control It Using An Android Device

Project tutorial by MJRoBot

  • 30,170 views
  • 0 comments
  • 47 respects

Blaster with AWS Alexa Voice Control & IR Firing Power

Project tutorial by Tom

  • 4,178 views
  • 1 comment
  • 28 respects
Add projectSign up / Login