John Abbott
Published © GPL3+

DogWatcher (MKR1000)

This is MKR1000/Windows 10 based device to keep your dog out of areas he should not be in by sounding an alarm and taking his photo.

IntermediateShowcase (no instructions)20 hours5,842
DogWatcher (MKR1000)

Things used in this project

Hardware components

Arduino MKR1000
Arduino MKR1000
×1
Raspberry Pi 2 Model B
Raspberry Pi 2 Model B
You can use Windows 10 IoT on your Raspberry Pi 2, or just run it from any device, such as your Surface or laptop.
×1
PIR Motion Sensor (generic)
PIR Motion Sensor (generic)
×1
Buzzer
Buzzer
I wanted a buzzer that would get my dog's attention a little better, so I picked this one up from Amazon (http://www.amazon.com/9-15V-HYD-4218-Active-Electronic-Buzzer/dp/B01DOAADWM). The one from Amazon is probably too loud for most situations.
×1
Darlington High Power Transistor
Darlington High Power Transistor
I used this so I could drive a much larger buzzer using a 12V power supply. This is not needed if using a smaller buzzer that can be powered from the GPIO pin.
×1
Breadboard (generic)
Breadboard (generic)
×1
Resistor 330 ohm
Resistor 330 ohm
×1

Software apps and online services

Arduino StandardFirmataWifi
I loaded the MKR1000 with the StandardFirmataWifi example from the example library. The only change was so it would authenticate against my Wifi.
Windows 10 IoT Core
Microsoft Windows 10 IoT Core
This can be used on the Raspberry Pi 2 (or 3) or it can be run from any Windows 10 computer.
Microsoft Azure
Microsoft Azure
I used the Azure IoT Hub to send and receive messages from outside of the device running the DogWatcher software.
Visual Studio 2015
Microsoft Visual Studio 2015
I used the Community Edition.

Story

Read more

Schematics

Schematic

The specific pins to connect to are documented in the source code. It will depend on what Arduino device you use to host your Firmata and connect to your devices.

Code

MainPage.XAML

VBScript
This is the code from the graphical interface (XAML) written in Visual Studio (Visual Basic)
<Page
    x:Class="DogWatcherHub.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DogWatcherHub"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Image x:Name="DoggieLoxImage" HorizontalAlignment="Left" Height="480" VerticalAlignment="Top" Width="640" Margin="374,10,0,0" Source="Assets/Dog.jpg"/>
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="748" Margin="10,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="364"/>
        <Ellipse x:Name="Shape" Fill="Teal" HorizontalAlignment="Left" Height="200" Stroke="Black" VerticalAlignment="Top" Width="200" Margin="813,558,0,0" StrokeThickness="5"/>
    </Grid>
</Page>

MainPage (Visual Basic code)

VBScript
This is the guts of the application. This is written Visual Basic (Visual Studio 2015 Community Edition).

This requires Windows-Remote-Arduino, as well as the Microsoft.Azure.Devices.Client.PCL. These are both installed from the NuGet Manager (or console). I have added the Windows IoT Extensions for the UWP primarily for future expansion on the Raspberry Pi 2.

Replace the Azure connect string with yours and specify the IP or HostName of you Arduino.

This establishes the connection with the Arduino, as well as the Azure IoT Hub. Once connected, it processes any messages from the Hub to ARM or disarm the DogWatcher.
Imports Microsoft.Maker.Firmata
Imports Microsoft.Maker.Serial
Imports Microsoft.Maker.RemoteWiring
Imports Microsoft.Azure.Devices.Client
Imports System.Text
Imports Windows.Media

' The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

''' <summary>
''' An empty page that can be used on its own or navigated to within a Frame.
''' </summary>
Public NotInheritable Class MainPage
    Inherits Page

    '=================================================================================================
    ' Device specific configuration.  Set your own values here.
    '-------------------------------------------------------------------------------------------------
    Private Const AzureIoTHubConnectionString = ""
    Private myHost As New Windows.Networking.HostName("x.x.x.x")
    Private myPort As UShort = 3030
    '=================================================================================================

    Private DogWatcherArmStatus As Boolean = False
    Private isArduinoReady As Boolean = False
    Private myMKR1000 As RemoteDevice
    Private myConnection As NetworkSerial

    Private Const buzzerPin As Byte = 4
    Private Const ledPin As Byte = 6
    Private Const motionPin As Byte = 1
    'Private Const motionPin As String = "A1"
    Dim isMoving As Boolean = True

    Dim mySolidColorBrush As New SolidColorBrush()
    Dim myStrokeColorBrush As New SolidColorBrush()

    Dim ArduinoTimer As New DispatcherTimer

    Private Sub MainPage_Loading(sender As FrameworkElement, args As Object) Handles Me.Loading
        mySolidColorBrush.Color = Windows.UI.Color.FromArgb(0, 0, 255, 0)
        Shape.Fill = mySolidColorBrush
        Shape.Fill.Opacity = 25

        myConnection = New Microsoft.Maker.Serial.NetworkSerial(myHost, myPort)
        myMKR1000 = New Microsoft.Maker.RemoteWiring.RemoteDevice(myConnection)
        myConnection.begin()
        AddHandler myConnection.ConnectionEstablished, AddressOf DogWatcherConnectionEstablished
        AddHandler myMKR1000.DeviceReady, AddressOf MKR1000Ready
        'AddHandler myMKR1000.DigitalPinUpdated, AddressOf Arduino_DigitalPinUpdated

        ReceiveDataFromAzure()
        TakePhoto()
        SendDataToAzure("Connected to Azure")
        DogWatcherARM()
        ArduinoTimer.Interval = TimeSpan.FromMilliseconds(100)
        AddHandler ArduinoTimer.Tick, AddressOf checkArduino
        ArduinoTimer.Start()
    End Sub

    Sub checkArduino()
        If isArduinoReady Then
            'Dim checkValue As UShort = myMKR1000.analogRead(motionPin)
            Dim checkValue As PinState = myMKR1000.digitalRead(motionPin)
            Dim currentlyMoving As Boolean = False
            If (checkValue = PinState.HIGH) Then
                currentlyMoving = True
            End If
            If isMoving <> currentlyMoving Then
                If (currentlyMoving) Then
                    mySolidColorBrush.Color = Windows.UI.Color.FromArgb(255, 255, 0, 0)
                    Shape.Fill = mySolidColorBrush
                Else
                    mySolidColorBrush.Color = Windows.UI.Color.FromArgb(127, 0, 0, 255)
                    Shape.Fill = mySolidColorBrush
                End If
                isMoving = currentlyMoving
                If DogWatcherArmStatus Then
                    If isMoving Then
                        myMKR1000.digitalWrite(buzzerPin, PinState.HIGH)
                        TakePhoto()
                    Else
                        myMKR1000.digitalWrite(buzzerPin, PinState.LOW)
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub MKR1000Ready()
        myMKR1000.pinMode(buzzerPin, PinMode.OUTPUT)
        myMKR1000.digitalWrite(buzzerPin, PinState.HIGH)
        myMKR1000.digitalWrite(buzzerPin, PinState.LOW)

        myMKR1000.pinMode(ledPin, PinMode.OUTPUT)
        myMKR1000.digitalWrite(ledPin, PinState.HIGH)
        myMKR1000.digitalWrite(ledPin, PinState.LOW)

        myMKR1000.pinMode(motionPin, PinMode.INPUT)
        isArduinoReady = True
    End Sub

    Private Sub DogWatcherConnectionEstablished()
        Debug.WriteLine("DogWatcher connection established")
        mySolidColorBrush.Color = Windows.UI.Color.FromArgb(127, 0, 255, 0)
        Shape.Fill = mySolidColorBrush
    End Sub

    Private Async Sub Arduino_DigitalPinUpdated(pin As Byte, pinValue As PinState)
        'Private Sub Arduino_DigitalPinUpdated(pin As Byte, pinValue As PinState)
        Debug.WriteLine("Event handler executing")
        Await Task.Delay(1)
        Try
            Debug.WriteLine(String.Format("Pin {0} changed to {1}", pin, pinValue))
        Catch ex As Exception
            Debug.WriteLine("Error: " & ex.Message)
        End Try
    End Sub


    Private Async Sub TakePhoto()
        Try
            Dim m_mediaCaptureMgr As New Windows.Media.Capture.MediaCapture
            Await m_mediaCaptureMgr.InitializeAsync()

            Dim m_photoStorageFile = Await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync("Intruder.jpg", Windows.Storage.CreationCollisionOption.GenerateUniqueName)
            Dim imageProperties As MediaProperties.ImageEncodingProperties = MediaProperties.ImageEncodingProperties.CreateJpeg()
            Await m_mediaCaptureMgr.CapturePhotoToStorageFileAsync(imageProperties, m_photoStorageFile)

            Dim photoStream = Await m_photoStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read)
            Dim bmpimg = New BitmapImage()
            bmpimg.SetSource(photoStream)
            DoggieLoxImage.Source = bmpimg
        Catch ex As Exception
            Debug.WriteLine("Error: " & ex.Message)
        End Try
    End Sub

    Private Async Sub SendDataToAzure(Msg As String)
        Try
            Dim DeviceClient As DeviceClient = DeviceClient.CreateFromConnectionString(AzureIoTHubConnectionString, TransportType.Http1)
            Dim msgToHub = New Message(Encoding.UTF8.GetBytes(Msg))
            Await DeviceClient.SendEventAsync(msgToHub)
        Catch ex As Exception
            Debug.WriteLine("Error: " & ex.Message)
        End Try
    End Sub

    Public Async Sub ReceiveDataFromAzure()
        Dim receivedMessage As New Message
        Dim messageData As String = ""

        Try
            Dim DeviceClient As DeviceClient = DeviceClient.CreateFromConnectionString(AzureIoTHubConnectionString, TransportType.Http1)
            Do While True
                receivedMessage = Await DeviceClient.ReceiveAsync

                If receivedMessage IsNot Nothing Then
                    messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes())
                    textBox.Text += messageData & vbCrLf
                    If messageData.Contains("DogWatcher: ARM") Then
                        DogWatcherARM()
                    ElseIf messageData.Contains("DogWatcher: disarm") Then
                        DogWatcherDisarm()
                    End If
                    Await DeviceClient.CompleteAsync(receivedMessage)
                End If
            Loop
        Catch ex As Exception
            Debug.WriteLine("Error: " & ex.Message)
        End Try
    End Sub

    Private Sub DogWatcherARM()
        DogWatcherArmStatus = True
        myStrokeColorBrush.Color = Windows.UI.Color.FromArgb(255, 255, 0, 0)
        Shape.Stroke = myStrokeColorBrush
        myMKR1000.digitalWrite(ledPin, PinState.HIGH)
    End Sub

    Private Sub DogWatcherDisarm()
        DogWatcherArmStatus = False
        myStrokeColorBrush.Color = Windows.UI.Color.FromArgb(255, 0, 0, 63)
        Shape.Stroke = myStrokeColorBrush
        myMKR1000.digitalWrite(ledPin, PinState.LOW)
        myMKR1000.digitalWrite(buzzerPin, PinState.LOW)
    End Sub
End Class

Credits

John Abbott

John Abbott

1 project • 3 followers

Comments