Quantcast
Channel: C# – Falafel Software Blog
Viewing all articles
Browse latest Browse all 54

PIR Sensor with a Photon, Particle Cloud, and a UWA

$
0
0

My latest sensor experiment involved the PIR Motion Sensor (HC-SR501) that comes with the Photon Maker Kit. The motion sensor didn’t have the best English documentation; however, there were enough translations and fragments out on the Internet to get the job done.

I decided to interface the motion sensor with a Photon, and then feed the sensor output to a UWA through the Particle Cloud by using a Particle Event Stream.

WP_20151113_002

The sensor has two potentiometers on its PCB. One controls the sensitivity of the sensor and the other controls the output latch delay.

PIRSensor

Turning the sensitivity down essentially limits the range of the device. This setting is useful in limiting false alarms depending upon the sensor environment. The output latch delay is used to delay the output going low after being triggered high from motion being detected. For me, I’d rather keep this setting as low as possible so I can take care of any latching function in software.

Software

The UWA I wrote for this project connects to a Particle Event Stream from the targeted Photon, which you can download here. I’ve played with Particle Event Streams in my previous post about the Useless Machine. The value that the Photon is sending via the stream is an ADC value between 0 and 4096. Anything above 2048 is interpreted as a motion present value; anything below is no motion. When no motion is detected the UWA shows the user a green “Clear” indicator. When motion is detected the UWA shows the user a red “Motion” indicator. That’s it, nothing fancy. You can see a quick video of the project working below.

Parts Used

  • Photon x 1
  • PIR Motion Sensor x 1

Schematic

Photon-PIR-Motion-Sensor (4)

 

PIR Motion Stream UWA

You need to make sure to use your own Device ID and Access Token. As I did with in my Useless Machine project, I’m connecting to a Particle Event Stream. In this case the event name is “Motion”. We’re reading the Json event data and then displaying the motion indicator based upon the event value.

public sealed partial class MainPage : Page
{
    const string PHOTON1DEVICEID = "{YOURDEVICEID}";
    const string ACCESS_TOKEN = "{YOURACCESSTOKEN}";
    SolidColorBrush MotionColor = new SolidColorBrush(Colors.Red);
    SolidColorBrush ClearColor = new SolidColorBrush(Colors.Green);
    public MainPage()
    {
        this.InitializeComponent();
    }
    private async void Open_Stream_Click(object sender, RoutedEventArgs e)
    {
        (sender as Button).IsEnabled = false;
        string url = String.Format("https://api.particle.io/v1/devices/{0}/events/Motion?access_token={1}", PHOTON1DEVICEID, ACCESS_TOKEN);
        WebRequest request = WebRequest.Create(url);
        request.Method = "GET";
        using (WebResponse response = await request.GetResponseAsync())
        {
            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream);
                int blankRead = 0;
                while (blankRead <= 5)
                {
                    var str = await reader.ReadLineAsync();
                    if (string.IsNullOrEmpty(str))
                    {
                        ++blankRead;
                        if (blankRead > 1)
                        {
                            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                            {
                                streamResultTextBox.Text = "Blank: " + blankRead.ToString();
                            });
                        }
                    }
                    else if (str == "event: Motion")
                    {
                        blankRead = 0;
                        var data = await reader.ReadLineAsync();
                        var jsonData = JsonConvert.DeserializeObject<ParticleEvent>(data.Substring(data.IndexOf("data:") + 5));
                        await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                        {
                            streamResultTextBox.Text = jsonData.data > 2048 ? "Motion" : "Clear";// "Data: " + jsonData.data;
                            streamResultTextBox.Foreground = jsonData.data > 2048 ? MotionColor : ClearColor;
                        });
                    }
                }
            }
        }
        (sender as Button).IsEnabled = true;
    }
}
public class ParticleEvent
{
    public int data { get; set; }
    public string ttl { get; set; }
    public string published_at { get; set; }
    public string coreid { get; set; }
}

PIR Motion Sensor Firmware

I’m using a loop to take 100 quick readings within 1 second. The reason I’m doing this is in case the output latch delay on the motion sensor is set to go off in less than a second. The loop takes multiple values and keeps the largest one. Every second that max value is sent to the cloud using the “Motion” event.

#define PIRPIN A0
int val;
void setup() {

}

void loop() {
    val = 0;
    for(int i = 0; i < 100; i += 1)
    {
        int rval = analogRead(PIRPIN);
        if (rval > val)
        {
            val = rval;
        }
        delay(10);
    }
    Particle.publish("Motion",String(val));
}

Conclusion

This project demonstrates that Photon and the Particle Cloud is dead simple to hook up to various sensors and applications. Get started hooking up your favorite sensors.

The post PIR Sensor with a Photon, Particle Cloud, and a UWA appeared first on Falafel Software Blog.


Viewing all articles
Browse latest Browse all 54

Trending Articles