Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Turn Your PC Into a Motion Sensing Security Device with .NET  : Page 3

Thanks to new types of hardware that can easily be programmed using .NET, you can create a motion sensing application that can be deployed for security—or just for fun.


advertisement
Putting Them Together
Now that we have written the programs for controlling the PIR and the PING))) sensors, let's try to put them together. Because we are constantly monitoring both sensors within an infinite loop, we can simply insert the code for the PIR sensor into the loop for the PING))) sensor. Here is the combined code:

' {$STAMP BS2} ' {$PBASIC 2.5} '---Duration of the trigger--- Trigger CON 1 '---Variable to measure the pulse--- rawDist VAR Word '---The I/O Pin connected to the PING))) sensor--- Ping PIN 15 DO '*********This section is for the PIR sensor******** DEBUG "PIR:" DEBUG BIN IN14, CR, LF '*********This section is for the PING))) sensor******** '---Set the pin to low first--- Ping = 0 '---trigger the sensor--- PULSOUT Ping, Trigger '---measure the echo pulse PULSIN Ping, 1, rawDist '---convert pulses to micro-seconds--- rawDist = rawDist * 2 '---get the single-trip timing--- rawDist = rawDist / 2 '---convert the distance to cm--- rawDist = rawDist /30 '---print out the distance in cm--- DEBUG "PING))):" DEBUG DEC rawDist, CR, LF '---delay for 100 milliseconds--- PAUSE 100 LOOP

The other statements I have added are the printing of strings such as "PIR:" and "PING))):" so that I know which number belongs to which sensor. The other commands such as CR and LF send a carriage return followed by a line feed character after each line is printed. If you run the program now, you will see:

PIR:0 PING))):17 PIR:0 PING))):16 PIR:0 PING))):16 PIR:0 PING))):15 PIR:1 PING))):14 PIR:1 PING))):14 PIR:1 PING))):13 PIR:1 PING))):12 ...

Integrating with the PC
So far all the work has been done on the BoE. But I want to integrate the two sensors with my PC so that I can do something useful. More specifically, how do I get the sensors' values into my PC?



If you observe the top of the Debug Terminal window, you will realize that it gets the debugging information from the BS2 through a serial connection (see Figure 12). In my case, it connects to COM5 with a baud rate of 9600bps.


Figure 12. Serial connection info is shown at the top of the Debug Terminal.
 
Figure 13. Populating the default Form1 with a Label and TextBox controls.

Tip: Note that for the BS2, you can also use the SERIN and SEROUT commands to send serial data into and out of the module. I will explore these two commands in more details in a future article.

You can retrieve the sensor data through the serial connection. Using Visual Studio, create a Windows application and name it C:\Sensors. For this application, I will display the sensor data in a Windows application.

Populate the default Form1 with the following controls (see Figure 13):

  • Label
  • TextBox

Set the Multiline property of txtData to True so that you can display the data from the sensors in each individual line.

Switch to the code-behind of Form1 and declare the following member variables:

Public Class Form1 Dim _PIR_Value As Boolean Private WithEvents serialPort As New IO.Ports.SerialPort

In the Load event of the form, open a serial connection to COM5 (assuming the COM port number used is COM5) using the SerialPort class:

Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load If serialPort.IsOpen Then serialPort.Close() End If Try With serialPort .PortName = "COM5" .BaudRate = 9600 .Parity = IO.Ports.Parity.None .DataBits = 8 .StopBits = IO.Ports.StopBits.One .Handshake = IO.Ports.Handshake.None End With serialPort.Open() Catch ex As Exception MsgBox(ex.ToString) End Try End Sub

In this project, you are only interested in getting data from the sensors; hence you just need to service the DataReceived event from the SerialPort class:

Private Sub DataReceived( _ ByVal sender As Object, _ ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _ Handles serialPort.DataReceived txtData.BeginInvoke(New _ myDelegate(AddressOf updateTextBox), _ New Object() {}) End Sub

Declare a delegate to write the received sensor data into the txtData control:

Public Delegate Sub myDelegate() Public Sub updateTextBox() txtData.AppendText(serialPort.ReadExisting) txtData.ScrollToCaret() End Sub

When data is received from the sensors and written to the txtData control, the text in the txtData control will change. To be notified of the change, service the TextChanged event. In this event, you can retrieve the data from the PIR sensor as well as the PING))) sensor:

Private Sub txtData_TextChanged( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles txtData.TextChanged Dim Sensor_value As String = _ txtData.Lines(txtData.Lines.Length - 2) If Sensor_value.StartsWith("PIR:") Then '---data from the PIR sensor--- If _PIR_Value = False And _ Sensor_value.Substring(4) = True Then '---motion detected--- Label1.Text = "Motion Detected" ElseIf Sensor_value.Substring(4) = False Then '---clear the label--- Label1.Text = String.Empty End If _PIR_Value = Sensor_value.Substring(4) ElseIf Sensor_value.StartsWith("PING))):") Then '---data from the PING))) sensor--- Label2.Text = "Detected distance: " & _ CInt(Sensor_value.Substring(8)) & "cm" End If End Sub

Incoming sensor data are appended to the end of the txtData control. You should be aware that the BS2 may not necessarily send incoming data as complete sentences. For example, the following sentence:

PING))):16

may be sent in two separate blocks:

PING ))):16

In this case, each block of data received by the serialPort.ReadExisting() method is incomplete and you must wait until the whole sentence is received before you can parse it for the data you need. One easy way to solve this is to extract the sensor data from the txtData control. As all incoming data are appended to the end of the TextBox control and the last line may contain a partial sentence, you should thus always extract the second-to-the-last line to extract the sensor information (see Figure 14).


Figure 14. The second-to-the-last line contains a complete sentence so it's better to use it over the last line.
 
Figure 15. The display of the sensor information in a Windows application is illustrated.

To test the application, press F5. Observe how the values change as you initiate some movements in front of the sensors (see Figure 15).

In this article, you have seen how you can use a microcontroller (such as the BS2 from Parallax) to control external electronic devices such as the PIR and PING))) sensors. Along the way, you learned the PBASIC language, a language used to program devices from Parallax. Most importantly, you learned how to interface external devices to your PC through a serial connection.

With this newfound knowledge, your imagination is the limit to what you can do with the sensors. You may want to use it to build a motion detection security system in your office to perform intrusion detection. Or, mount the sensors outside of your cubicle to detect your boss approaching!



Wei-Meng Lee is a Microsoft MVP and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies. He is an established developer and trainer specializing in .NET and wireless technologies. Wei-Meng speaks regularly at international conferences and has authored and coauthored numerous books on .NET, XML, and wireless technologies. He writes extensively on topics ranging from .NET to Mac OS X. He is also the author of the .NET Compact Framework Pocket Guide, ASP.NET 2.0: A Developer's Notebook (both from O'Reilly Media, Inc.), and Programming Sudoku (Apress). Here is Wei-Meng's blog.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap