Basic Stamp 2 voltage Detector

This is part of my Smart Home series available exclusively on Jafty.com, Jafty Interactive Web Development’s service site. It is part of a series I am writing while building my own smart home out of a home I purchased in Akron, Ohio. The premise is that I have used a micro-controller(Basic Stamp 2) device to link a laptop PC to several electrical objects around my home. I now have it so there are battery powered LED lights in every room of the house and they can be turned on and off using a computer which the Basic Stamp 2 micro-controller is plugged into. The lights and battery also link to the micro-controller. The micro-controller serves as a medium between the PC, battery, lights, etc.

The system works good, but I thought for the home to be truly “smart”, it should also know the voltage of the battery banks used throughout the home to power different objects(batteries are currently charged using a small 900 watt gasoline generator). This article is about how to build a voltage monitoring device that uses a Basic Stamp 2 micro-controller to check the voltage of a battery and report it on the computer screen it is connected to.

How to build a Voltmeter Circuit for Basic Stamp 2

 

Here is a schematic of the voltage meter circuit for the Basic Stamp 2 I drew using Open Office Draw:

Voltmeter-circuit

The above  schematic contains a small modification I made to the resistance. Adjusting the resistance of the 690k ohm resistor adjusts the voltage value. Adding more resistance lessens the value of the voltage read, so you can add or subtract to it as needed to fit your requirements.  Basically what we have is a 470 ohm resistor(r1) coming off of one of the io pins on the Basic Stamp 2(BS2-io-pin). The other end of the resistor(r1) attaches to the positive leg of a 0.02 uf film capacitor(c1). Then attached to the same positive leg is a 600k ohm resistor(r2) and this is the positive lead used for checking voltage on the positive side of the battery to be tested. Coming off of the other, negative lead of the capacitor(c1), is a wire going to the vss ground on the Basic Stamp 2 micro-controller. Finally another wire lead comes off of the Basic Stamp 2 vss ground to go to the negative terminal of the battery or device to be tested for voltage. Here are the values of the required components summarized:

  • r1 = 470 ohm
  • r2 = 690k ohm
  • c1 = 0.02 uf micro film capacitor(the green ones)

As you can see, the circuit for testing voltage is very simple and we all know that testing voltage is not quite considered simple. There can be analog to digital conversion integrated circuits used and many other more complex components, but this is a very simple circuit made possible due to the use of the Basic Stamp 2 micro-controller and it’s rc time ability. Therefore, the program we need to run is not quite as simple as the circuit, but is still very easy and this is by far the easiest way I could find to accurately check DC voltage and report the results on my PC. Next, we’ll cover how to write a program in pbasic to put onto the Basic Stamp 2 in order to check voltage with the circuit outlined above.

PBasic Code to Check Voltage Using Basic Stamp 2

‘ {$STAMP BS2}
‘ {$PBASIC 2.5}

rct VAR Word  ‘RCtime value
Vx VAR Word  ‘calculated voltage (this will = applied voltage Vx)
Cn1 CON 48576  ‘first constant, see below
Cn2 CON 8  ‘second constant used below
‘ circuit attached to Pin 0
LOW 0
TheLOOP:
RCTIME 0,0,rct
LOW 0
Vx=Cn1 / rct + Cn2
DEBUG HOME,DEC? rct,”Vx= “, DEC Vx/10,”.”,DEC1 Vx
PAUSE 500
GOTO TheLOOP

As you can see, the above code may look a little complicated, but it is as short and sweet as you will find when it comes to code to check voltage using a micro-controller. I promise you, this is the simplest way to check DC voltage using a Basic Stamp 2 micro-controller. Also we need to report that voltage to a computer running Windows 7 or 8. This turned out to be a challenge that took me several hours to overcome, but not to worry, I’ll share my ultimate solution with you next.

How to send Data from Basic Stamp 2 to a Windows 7 or 8 PC and Present to Screen

The basic challenge for me was: How do I get the voltage value from the Basic Stamp 2 to a web page running on my Windows 7 PC using XAMPP for Windows? The main issue seemed to be that Windows computers running either windows 7 or above don’t allow a scripting language such as PHP to read data from serial ports. I found that I was very easily able to write data to the Basic Stamp 2 micro-controller from Windows 7 using PHP and the fopen/fput commands and similar methods. However, while I was able to open a connection using PHP’s fopen command, I was not able to read data from the serial port using PHP at all. I tried almost every possible method I could find and nothing worked. That was very aggravating to say the least! I ended up finding a method that worked if you first wrote something to the serial port and then read it after a 1 second pause. This is the only way that would allow me to read data from a serial port using Windows 7 and PHP. Below is the function I used. It writes a “v” to the stamp micro-controller first which is used to ask for a voltage reading. Then it reads and parses the response from the serial port.

<?php

//this file is included in ControlLights.php to show voltage
function getSerialData($port){
‘mode $port: BAUD=9600 PARITY=N data=8 stop=1 xon=off’;
$fp = fopen ($port.”:”, “r+”);
if (!$fp) {
echo “ERROR! COM3 Port failed to open.“;
} else {
//send command to get voltage from stamp(cannot read data from serial without using fputs first for some reason!)
fputs ($fp, “v”);
sleep(1);
//get serial data:
$response = fread($fp,19);
//echo “response: $response”;//NOTE: this produced text before voltage, so I parsed it out below:
$resparr = explode(“volts:”,$response);
$voltage = $resparr[1];
echo “$voltage Volts“;
fclose ($fp);
}
}//end function.
getSerialData(“COM3”);
?>

I included the above PHP file within the web page that I wanted to show the voltage on and it worked perfect! To view the whole thing, see my tutorial on controlling lights which includes the above script in the ControlLights.php file to show the battery voltage on screen in the app I use to turn lights and appliances in my home on and off.

 

How to Control House Lights From Anywhere

In this article, How to Control House Lights From Anywhere, I am going to give a solution for the basic problem; How do you turn a light in your home on or off using your computer, phone or other online device? Also, I aim to control my home’s lights by voice commands from within the home.

The problem:

In a nutshell, the basic problem is, how do you control a light from a webpage? It could be either a webpage or an online app, but the concepts are similar. Also there is the voice control to think about. Voice operation is secondary because once I figure out how to turn the light on and off from my PC, then I can work in a voice control module from that point.

Since I want to control a light from a computer and through the internet, I think my best solution lies withing PHP as a starting point. So, basically I need to figure out how to control a light in my house with PHP. Once that is achieved, I can expand on that solution to do it from my PC, phone, the internet and via voice commands inside my home.

The next thing I did was asked myself: How can I get PHP to interact with the physical world? I had to think outside of the box and came up with using a PC or laptop based in my home as a controlling device. So then my problem becomes a little more focused. I had to find a solution to: “How do you control a light from a PC” Once that’s accomplished, you can communicate with that home-based PC via a network to control your home’s lights from anywhere with any device you like that can get online.

The Solution:

So, knowing that PHP is, for the most part, a web based language and a server-side language, I figured I would need another method of communicating with a hardware device to switch my house lights on and off. However, I thought that I could figure out what languages and technologies to use to control my lights from a PC and later find a way to communicate with the language/technologies I used from PHP.

Long story short, I decided upon using a micro-controller peripheral device known as the BASIC STAMP 2 as the light switch. Therein lies the first coding challenge.  The Basic Stamp 2 is basically a very small computer that was given the name “Stamp” because of it being the approximate size of a U.S. postage stamp. The Basic Stamp 2 uses a coding language named PBasic that is, as the name suggests, a very basic-like programming language. Being unfamiliar with PBasic, I spent the good part of a day learning how to do the basic coding necessary to turn a light on and off from the Stamp 2 Device. Next, I spent the majority of another whole day learning to communicate with the device through a USB port or serial cable from PHP. That’s why I am posting my findings online. If someone else ever has to do something similar or if I have to do it again in the future, they or I can simply reference this post on my website to figure it all out saving many hours of research and testing.

In summary, the solution I am using to control lights(and later other things) in my home, is a combination of PHP, PBasic, PC and the Basic Stamp 2. Here is the workflow:

Workflow for Creating a web-based Light Switch for your Home:

Basically there are three high-level steps to achieving my goal of controlling my home’s lights remotely. They are:

1) Create a circuit using the Basic Stamp 2 micro-controller that can turn a light on and off.

2) Write a program in PBasic to install on the Basic Stamp 2 that can control the circuit in the previous step.

3) Write a program in PHP that can send signals to the Basic Stamp 2 PBasic program letting it know to turn the light on or off.

Step by Step Low Level Instructions

The Step by Step Instructions for Building My Soon-to-be Famous Remote Lighting System are a lot more complex. Here are the step-by-step instructions to build the system I am employing in my smart home:

1) Obtain a device to interface with your PC in order to interact with the outside world(toggle a light). I decided to go with a micro-controller called “Basic Stamp 2” by Parallax. If you want to be able to follow this tutorial, I recommend you use the same one. Otherwise, some of the steps in this tutorial will not apply to your situation. I bought the Basic Stamp 2 HomeWork Board. I suppose you could use any implementation that has the same chip, but this tutorial is based upon using the exact version available on Parallax’s website here: https://www.parallax.com/product/555-28188.

2) Set up your Basic Stamp 2. I’m not going to go into too much detail about setting up your Basic Stamp 2 because you can get everything you need from Parallax’s interactive “Getting Started” guide found at http://www.parallax.com/go/BASICStampStartHelp/ and also you could download the PDF or read it online at https://www.parallax.com/sites/default/files/downloads/28125-Getting-Started-from-Help-v2.5.pdf.

3) Once you have the Basic Stamp 2 up and running and after you have tested it by writing a simple test program to make sure it works, you can create your light switch circuit. You will need a NPN transistor, a relay to trigger a high voltage (110 AC) light, a basic 470 Ω resistor and some wire leads in addition to a light of course. Here is a very basic switch circuit I got to work, but I must warn you that it doesn’t include the recommended NPN transistor that should go between the no. 14 pin and the relay or the 470 ohm resistor just mentioned. These could be important because most relays in general will throw back power surges to your micro-controller and fry it! I am the dangerous type, so I risked it. Just kidding, I found a reed relay that was considered safe, but it is definitely NOT recommended that you do the same and if you do, it is at your own risk… Here’s the circuit I used none-the-less. Just add the resistor and NPN transistor before the relay to be safe if you’re not sure about the risks:

OLYMPUS DIGITAL CAMERA

In the above image, you can see that pin 14 connects to the relay’s positive while the negative connects to the Vss or ground.  The two pins on the reed relay the are in the center on either end are the pins that the higher voltage, 110 vac travels through. Those two pins make a connection when current is applied to the two pins on either side of the relay that are connected to pin 14 and the Vss ground. In the above image, the white and green alligator clips lead to the 110 volt ac power supply and the golden wires lead to a 110 volt light fixture.  Also, in the above image you see a nine pin connector and the one I used has a USB connection. The wiring is the same though.

4) Write the PBasic code. Now that you have the circuit, it’s time to write the PBasic program to control it and test it. Here is the code I used to control a single light. Note that the code requires input which will eventually come from a PHP script over a USB cord, but for now you can test it by typing 1 or 2 on your keyboard as long as you keep your debug terminal running while using the editing software for the Basic Stamp 2. Type the following PBasic code into your Basic Stamp editor file and save it as a .bs2 file before downloading it to the device:

‘ {$STAMP BS2}
‘ {$PBASIC 2.5}

‘ This program accepts the numbers 1 & 2 as commands to turn light on off.
‘ Other values produce an error msg in debug term.

‘ ——– Pin Assignments ——–
INPUT_PIN CON 16

‘ ——– Constant Assignments ——–
BAUDMODE CON 16468

‘ ——– Variable Assignments ——–
Command VAR Byte
Counter VAR Nib

GOSUB Task3

Main:
DO
GOSUB GetInput
LOOP
END

‘ Receives input from some external source
GetInput:
SERIN INPUT_PIN, BAUDMODE, [Command]
GOSUB TakeAction
RETURN

TakeAction: ‘ Determines what to do based on result of GetInput
SELECT Command
CASE “1”
GOSUB Task1
RETURN
CASE “2”
GOSUB Task2
RETURN
CASE ELSE
GOSUB Task3
RETURN
ENDSELECT

Task1:
DEBUG CR, “Turning on light one.”
HIGH 12
PAUSE 50
RETURN

Task2:
DEBUG CR, “Turning off light one.”
LOW 12
PAUSE 50
RETURN

Task3:
DEBUG CR, “Please select one or two to turn the light on or off!”
PAUSE 50
RETURN

That’s it, now test the code by clicking the run icon in the editor then typing 1 or 2 on your PC’s keyboard to turn the light on or off that is connected to your circuit from the previous step. If it doesn’t work, check to be sure that your computer is using the same com port and baud rate that is set in the program and if not, change the settings in the above file accordingly.

5) Write the PHP code. Next is time to write the PHP code that will interact with the serial port, handing down information to the Basic Stamp 2 device and telling it to turn the 110 volt AC light on and off. Here’s the code I wrote for my first test case that worked great because it is as simple as it gets. You can expand on this later as needed, but here is the basic working PHP code:

 <?php
if(isset($_POST[“sbdrm”])){
exec(“mode com3: BAUD=9600 PARITY=n DATA=8 STOP=1”);// to=off dtr=off rts=off
$fp =fopen(“com3”, “w”);
//$fp = fopen(‘/dev/ttyUSB0′,’r+’); //use this for Linux
//value of bedroom light
$onoff = $_POST[‘bdrm’];
if($onoff == “off”) fwrite($fp, “2”); //write string to serial
if($onoff == “on”) fwrite($fp, “1”); //write string to serial
fclose($fp);
echo “Light toggled!<br />”;
}//end if sbdrm is hit
?>

Finally, we have the simple version of the HTML code:

<h1>Light Controls</h1>

<h2>Bedroom Light</h2>
<form method=”post” action=””>
<input type=”radio” id=”bdrm” name=”bdrm” value=”on”> On<br />
<input type=”radio” id=”bdrm” name=”bdrm” value=”off”> Off<br />
<input type=”submit” id=”sbdrm” name=”sbdrm” value=”GO!” />
</form>