more G-Labs products

Author Topic: two led control with 2 switch module using HomeGenie and arduino  (Read 777 times)

March 05, 2017, 07:23:40 PM
Read 777 times

drish

  • *
  • Information
  • Newbie
  • Posts: 5
How to get .hgx program file for controlling 2 leds(on/off) using 2 switch modules by using Arduino and Homogenie.
Aim of project( 1.switch A0 can control on/off of green led and 2. switch A2 can control on/off of red led).
Can i pls get help to get csharp program in .hgx for this project.

The .hgx program which i have already is for controlling of one led using switch given below.
Program:

var portname = "COM7"; /* Serial port on PC or on Raspberry Pi */

/* Virtual module added in Setup(Trigger) section (other tab) */
/* In this case we added one module with the address "A0" in the domain "HomeAutomation.MCU"
 domain of type "Switch" and using the "generic switch" widget for displaying it in the control
 panel. There are other widgets that can be used (sensor, door, window, light, dimmer etc..)
 Btw, a program can also create more that just one module by using AddVirtualModules. */
//Program.AddVirtualModule("HomeAutomation.MCU", "A0", "Switch", "homegenie/generic/switch");

/* We will use this module */
/* Now, to get a reference to your virtual module: */
var module = Modules.InDomain("HomeAutomation.MCU").WithAddress("A0").Get();
/* var mod1 = Modules.InDomain("HomeAutomation.X10").WithAddress("A2"); */

/* Serial Reception */
/* HandleMessageReceived(): ASCII
 * HandleStringReceived(): UTF-8 */
Action<string>
HandleStringReceived = (string message) =>
{
  /* This will be called every time a message is received from serial port */
  Program.Notify("SerialPort String", message);
   /* our MCU Protocol is very simple, 1 Byte RXed, if that is '0' turn on module, otherwise turn off */
  if (message[0] != '0')
  {
    module.On();
  }
  else
  {
    module.Off();
  }
  /* turn the hue light 1 on (method 2, calling api directly)
   module.Command("Control.On").Execute(); */
};

Action<bool>
HandleStatusChanged = (bool connected) =>
{
  /* this will be called every time the connection status changes */
  Program.Notify("SerialPort Status", connected ? "CONNECTED!" : "DISCONNECTED!");
};

/* As a switch, the module should also handle "Control.On" and "Control.Off" commands issued by the user
 from the Web user interface, or by scripting. (define Web service) */
When.WebServiceCallReceived("HomeAutomation.MCU", ( args ) =>
    {
      string[] reqs = ((string)args).Split('/');
      var res = "{ 'ResponseValue' : 'ERROR' }";
     
      try
      {
        string command = reqs[2];
        /* string moduleid = reqs[1]; *//* we wont use this since we only have one module */
        switch(command)
        {
          case "Control.On":
             /* eg. Control URL: http://hg_address/api/HomeAutomation.MCU/A0/Control.On */
            /* eg. here you send a message to the serial port for switch ON the device */
            Program.RaiseEvent(module, "Status.Level", "1", "Indicator");
            res = "{ 'ResponseValue' : 'OK' }";
            SerialPort.SendMessage("1");
             break;
          case "Control.Off":
             /* eg. http://hg_address/api/HomeAutomation.MCU/A0/Control.Off */
            /* here you send a message to the serial port for switch OFF the device */
            Program.RaiseEvent(module, "Status.Level", "0", "Indicator");
            res = "{ 'ResponseValue' : 'OK' }";
            SerialPort.SendMessage("0");
             break;
        }
      }
      catch (Exception ex)
      {
        res = ex.Message + " " + ex.StackTrace;
      }
      return res; /* unable to process request */
    });

/* open the serial port channel and register handlers */
SerialPort.WithName( portname )
   .OnStatusChanged( HandleStatusChanged )
   /* .OnMessageReceived( HandleMessageReceived ) */ /* For UTF-8  */
   .OnStringReceived( HandleStringReceived )
   .Connect( 9600 ); /* change baud rate if needed */
 .......... end.........

i wanted to do same project using 2 leds on /off using 2 switches.. if i edit this program it shows many error since i dont have good knowledge in Csharp program. Can anyone please help by sending C# .hgx file for this project
« Last Edit: March 06, 2017, 06:52:17 AM by drish »

March 07, 2017, 12:02:48 AM
Reply #1

IanR

  • **
  • Information
  • Jr. Member
  • Posts: 31
Hello
In your script (Arduino code) what are the commands that switch on / off the 2 leds?
IanR

March 07, 2017, 06:21:34 AM
Reply #2

drish

  • *
  • Information
  • Newbie
  • Posts: 5
Thank you sir for your kind response.
arduino program code is given below. Can you pls check it

/******************************************************************************
 * \brief       Test basic I/O functions with HomeGenie Home Automation SW
 * \author      Arpad Toth <mrx23dot // gmail>
 * $Author:     $
 * $Id:         $
 * \copyright   GNU Public License v3.
 * \details     Written for Energia with TI LaunchPad MSP430G2553
 * \ingroup     HG
 * \addtogroup  HG
 * @{
 *****************************************************************************/

/* ============================================================================
 *                                   Types
 * ==========================================================================*/
typedef int8_t tSI8;
typedef uint8_t tUI8;

enum
{
  FALSE = 0u, TRUE
};
/* TRUE = 1 */

/* ============================================================================
 *                             Private Constants
 * ==========================================================================*/
static const tUI8 buttonPin = 2; /* the number of the pushbutton pin */
static tUI8 ledPin1 = 4; /* the number of the LED pin green*/
static tUI8 ledPin2 = 6; /* the number of the LED pin red */

/* ============================================================================
 *                             Private variables
 * ==========================================================================*/
static String inputString = ""; /* a string to hold incoming data */
static tUI8 buttonState = FALSE; /* variable for reading the pushbutton status */
static tUI8 last_state = FALSE;
static tUI8 DATA_OUT = FALSE;

/* ============================================================================
 *                                Functions
 * ==========================================================================*/

/*****************************************************************************/
/** \brief    setup() only runs once after boot
 *****************************************************************************/
void setup()
{
  /* initialize serial/UART port */
  Serial.begin(9600u);
  /* reserve 200 bytes for the inputString */
  inputString.reserve(200u);

  /* init pins */
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

/*****************************************************************************/
/** \brief    Loop runs till there is power.
 *****************************************************************************/
void loop()
{
  /* check if the pushbutton is pressed. */
  /* if it is, the buttonState is LOW (inverting) */
  buttonState = digitalRead(buttonPin);
  digitalWrite(ledPin2, !buttonState); /* visual feedback */

  if ((buttonState != last_state) && (last_state != FALSE))
  {
    DATA_OUT = !DATA_OUT; /* invert state */
    Serial.println(DATA_OUT);
  }
  last_state = buttonState; /* Update falling edge detection */
}

/*****************************************************************************/
/** \brief    Handle UART/serial data reception
 *
 *  SerialEvent occurs whenever a new data comes in the
 * hardware serial RX. This routine is run between each
 * time loop() runs, so using delay inside loop can delay
 * response. Multiple bytes of data may be available.
 *****************************************************************************/
void serialEvent()
{
  while (Serial.available())
  {
    /* get the new byte: */
    char inChar = (char) Serial.read();

    /* Change Output pin state (now Green LED) based on what has been received */
    if (inChar == '0')
    {
      digitalWrite(ledPin1, LOW);
    } else if(inChar == '1')/* anything but '0' char received */
    {
      digitalWrite(ledPin1, HIGH);
    }
  }
}

/* ============================================================================
 *                                  @} EOF
 * ==========================================================================*/

March 07, 2017, 10:27:19 AM
Reply #3

drish

  • *
  • Information
  • Newbie
  • Posts: 5
i have edited and tried csharp program for 2 led control using 2 switch modules: program run successfully. But only green led could controlled. red led didnt show the op. Can you pls check the code and correct it.

var portname = "COM1"; /* Serial port on PC or on Raspberry Pi */

/* Virtual module added in Setup(Trigger) section (other tab) */
/* In this case we added one module with the address "A0" in the domain "HomeAutomation.MCU"
 domain of type "Switch" and using the "generic switch" widget for displaying it in the control
 panel. There are other widgets that can be used (sensor, door, window, light, dimmer etc..)
 Btw, a program can also create more that just one module by using AddVirtualModules. */
//Program.AddVirtualModule("HomeAutomation.MCU", "A0", "Switch", "homegenie/generic/switch");

/* We will use this module */
/* Now, to get a reference to your virtual module: */
var module = Modules.InDomain("HomeAutomation.MCU").WithAddress("A0").Get();
var mod1 = Modules.InDomain("HomeAutomation.X10").WithAddress("3").Get();

/* Serial Reception */
/* HandleMessageReceived(): ASCII
 * HandleStringReceived(): UTF-8 */
Action<string>
HandleStringReceived = (string message) =>
{
  /* This will be called every time a message is received from serial port */
  Program.Notify("SerialPort String", message);
   /* our MCU Protocol is very simple, 1 Byte RXed, if that is '0' turn on module, otherwise turn off */
  switch(message)
  {
    case "A0":
    if (message[0] != '0')
  {
    module.On();
  }
  else
  {
    module.Off();
  }
    break;
    case "3":
     if (message[0] != '0')
  {
    mod1.On();
  }
  else
  {
    mod1.Off();
  }
    break;
  }
  /* turn the hue light 1 on (method 2, calling api directly)
   module.Command("Control.On").Execute(); */
};

Action<bool>
HandleStatusChanged = (bool connected) =>
{
  /* this will be called every time the connection status changes */
  Program.Notify("SerialPort Status", connected ? "CONNECTED!" : "DISCONNECTED!");
};

/* As a switch, the module should also handle "Control.On" and "Control.Off" commands issued by the user
 from the Web user interface, or by scripting. (define Web service) */
When.WebServiceCallReceived("HomeAutomation.MCU", ( args ) =>

    {
      string[] reqs = ((string)args).Split('/');
      var res = "{ 'ResponseValue' : 'ERROR' }";
     
      try
      {
        string command = reqs[2];
        string moduleid = reqs[1];/* we wont use this since we only have one module */
        switch(command)
        {
          case "Control.On":
             /* eg. Control URL: http://hg_address/api/HomeAutomation.MCU/A0/Control.On */
            /* eg. here you send a message to the serial port for switch ON the device */
            Program.RaiseEvent(module, "Status.Level", "1", "Indicator");
           
            res = "{ 'ResponseValue' : 'OK' }";
            SerialPort.SendMessage("1");
             break;
          case "Control.Off":
             /* eg. http://hg_address/api/HomeAutomation.MCU/A0/Control.Off */
            /* here you send a message to the serial port for switch OFF the device */
            Program.RaiseEvent(module, "Status.Level", "0", "Indicator");
           
            res = "{ 'ResponseValue' : 'OK' }";
            SerialPort.SendMessage("0");
             break;
        }
      }
      catch (Exception ex)
      {
        res = ex.Message + " " + ex.StackTrace;
      }
      return res; /* unable to process request */
    });
When.WebServiceCallReceived("HomeAutomation.X10", ( args ) =>

    {
      string[] reqs = ((string)args).Split('/');
      var res = "{ 'ResponseValue' : 'ERROR' }";
     
      try
      {
        string command = reqs[2];
        string moduleid = reqs[1]; /* we wont use this since we only have one module */
        switch(command)
        {
          case "Control.On":
             /* eg. Control URL: http://hg_address/api/HomeAutomation.MCU/A0/Control.On */
            /* eg. here you send a message to the serial port for switch ON the device */
            Program.RaiseEvent(mod1, "Status.Level", "1", "Indicator");
           
            res = "{ 'ResponseValue' : 'OK' }";
            SerialPort.SendMessage("1");
             break;
          case "Control.Off":
             /* eg. http://hg_address/api/HomeAutomation.MCU/A0/Control.Off */
            /* here you send a message to the serial port for switch OFF the device */
            Program.RaiseEvent(mod1, "Status.Level", "0", "Indicator");
           
            res = "{ 'ResponseValue' : 'OK' }";
            SerialPort.SendMessage("0");
             break;
        }
      }
      catch (Exception ex)
      {
        res = ex.Message + " " + ex.StackTrace;
      }
      return res; /* unable to process request */
    });


/* open the serial port channel and register handlers */
SerialPort.WithName( portname )
   .OnStatusChanged( HandleStatusChanged )
   /* .OnMessageReceived( HandleMessageReceived ) */ /* For UTF-8  */
   .OnStringReceived( HandleStringReceived )
   .Connect( 9600 ); /* change baud rate if needed */

March 08, 2017, 10:38:04 AM
Reply #4

drish

  • *
  • Information
  • Newbie
  • Posts: 5
Arduino program part for two leds operations with switch: Can you pls check it and get me the Csharp solution code for this. The entire arduino program is given in the previous reply. Also i tried this Csharp program and result run succesfully but only one led could control. Another led didnt work. Can you pls check that also.

void setup()
{
 
  Serial.begin(9600u);
  inputString.reserve(200u);

  /* init pins */
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

/*****************************************************************************/
/** \brief    Loop runs till there is power.
 *****************************************************************************/
void loop()
{
  /* check if the pushbutton is pressed. */
  /* if it is, the buttonState is LOW (inverting) */
  buttonState = digitalRead(buttonPin);
  digitalWrite(ledPin2, !buttonState); /* visual feedback */

  if ((buttonState != last_state) && (last_state != FALSE))
  {
    DATA_OUT = !DATA_OUT; /* invert state */
    Serial.println(DATA_OUT);
  }
  last_state = buttonState; /* Update falling edge detection */
}


void serialEvent()
{
  while (Serial.available())
  {
    /* get the new byte: */
    char inChar = (char) Serial.read();

    /* Change Output pin state (now Green LED) based on what has been received */
    if (inChar == '0')
    {
      digitalWrite(ledPin1, LOW);
    } else if(inChar == '1')/* anything but '0' char received */
    {
      digitalWrite(ledPin1, HIGH);
    }
  }

March 09, 2017, 12:05:45 AM
Reply #5

IanR

  • **
  • Information
  • Jr. Member
  • Posts: 31
Hello again
I have had a look at the code you have posed. But both the Scratch (Arduino code) and the c# (HG code) are both set up for only 1 LED communications.
I use Arduinos for sensors and looking at using them for relays.
I am working on a demo for you hope to post tomorrow. Sorry time is agent me today.
IanR


March 09, 2017, 07:18:10 AM
Reply #6

drish

  • *
  • Information
  • Newbie
  • Posts: 5
Ok. i changed code for different leds  in Arduino and  C# program. But still like same before only.
edited Arduino program:

typedef int8_t tSI8;
typedef uint8_t tUI8;

enum
{
  FALSE = 4u, TRUE = 2u,
};

...............................
...............................
*********************************************************************/
void loop()
{
  /* check if the pushbutton is pressed. */
  /* if it is, the buttonState is LOW (inverting) */
  buttonState = digitalRead(buttonPin);
  digitalWrite(ledPin2, !buttonState); /* visual feedback */

  if ((buttonState != last_state) && (last_state != FALSE))
  {
    DATA_OUT = !DATA_OUT; /* invert state */
    Serial.println(DATA_OUT);
  }
  last_state = buttonState; /* Update falling edge detection */
}


corresponding C#Program given below.

switch(message)
  {
    case "A0":
    if (message[0] != '0')
  {
    module.On();
  }
  else
  {
    module.Off();
  }
    break;
    case "3":
     if (message[0] != '4')
  {
    mod1.On();
  }
  else
  {
    mod1.Off();
  }
    break;
  }

i  couldnt identity the error

March 09, 2017, 10:05:23 PM
Reply #7

IanR

  • **
  • Information
  • Jr. Member
  • Posts: 31
Hello
(Your code looks to be only sending 1 or 0 (1 on and 0 off) so it can only operate 1 LED.)

I Include the HG and Arduino code.

This code has 2 LED outputs that are controlled from HG. The number of LEDs (outputs) can be changed easily. The LEDs are on pins 4 and 6 of the Arduino, witch matches the scratch code you posted.

This software also has 2 button inputs that are displayed on HG. It could be easily modified for other sensors and even Analogue ones. The buttons are on pins 24 & 25 of the Arduino again these can be easily changed.

There are lots of comments but if you need more help then just leave a message.

IanR