Bruno Santos
Published © CC BY-NC

Pet detector with Seeed Studio Grove Vision AI V2

You have a very energetic young pup. You open the garage door to park your car. He comes very fast and happy to see you. You don't see it.

IntermediateFull instructions provided5 hours245
Pet detector with Seeed Studio Grove Vision AI V2

Things used in this project

Hardware components

Grove Vision AI Module V2
Seeed Studio Grove Vision AI Module V2
×1
Seeed Studio XIAO ESP32S3 Sense
Seeed Studio XIAO ESP32S3 Sense
×2
5 mm LED: Red
5 mm LED: Red
×1
Battery Holder, 3 x AAA
Battery Holder, 3 x AAA
×2
JS Series Switch
C&K Switches JS Series Switch
×1

Software apps and online services

MicroPython
MicroPython
Arduino IDE
Arduino IDE
MQTT
MQTT

Hand tools and fabrication machines

3D Printer (generic)
3D Printer (generic)

Story

Read more

Schematics

Warning Light with the ESP32S3

This is the warning Light that will subscribe the MQTT topic

Grove Vision AI V2 detector

This is the detector part. With the Grove Vision AI V2 to detect our Pet

Code

groveVisionAIV2-Pet_detector

C/C++
This is the code to upload to the Xiao ESP32-C3, that will be physically connected to the Grove Vision AI V2.
#include <Seeed_Arduino_SSCMA.h>
#include <WiFi.h>
#include <PubSubClient.h>


#define DEBUG 0
//#define DEBUG 1

SSCMA AI;

const char* ssid = "<wifi_ssid>";
const char* password = "<wifi_password>";

// time after no detection warning is removed - in minutes
// if no pet detection during this time
// remove warning
const unsigned long warningTime = 1;
unsigned long controlTime = 0; //control variable

unsigned long startTime;

//set score minimal
// only with score above this we say it's detected
const int score = 65;

// MQTT stuff
const char *mqtt_broker = "broker_ip";
const char *mqtt_topic = "topic_to_publish";
const char *mqtt_username = "mqtt_user";
const char *mqtt_password = "mqtt_password";
const int mqtt_port = 1883;


WiFiClient espClient;
PubSubClient clientMqtt (mqtt_broker, mqtt_port, espClient);

// we define a function just to connect to MQTT
// because disconnect time 
// we cant keep a connection openned for too long
void connectMQTT() {
  //clientMqtt.setServer(mqtt_broker, mqtt_port);
  while (!clientMqtt.connected()) {
    String client_id = "Xiao-VisionV2";
    Serial.println("The client %s connects to MQTT broker!");
    if (clientMqtt.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("Connected to MQTT Broker");
    }
    else {
      Serial.print("failed with state: ");
      Serial.println(clientMqtt.state());
    }
  }
}

void setup() {
    AI.begin();
    Serial.begin(9600);
    // Connect to Wi-Fi
  WiFi.mode(WIFI_STA);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
    //start counting time
    startTime = millis();
    if (!AI.invoke()) {
      if (DEBUG) {
        Serial.println("invoke success");
        Serial.print("perf: prepocess=");
        Serial.print(AI.perf().prepocess);
        Serial.print(", inference=");
        Serial.print(AI.perf().inference);
        Serial.print(", postpocess=");
        Serial.println(AI.perf().postprocess);
      }
      for (int i = 0; i < AI.boxes().size(); i++) {
        if (DEBUG) {
            Serial.print("Box[");
            Serial.print(i);
            Serial.print("] target=");
            Serial.print(AI.boxes()[i].target);
            Serial.print(", score=");
            Serial.print(AI.boxes()[i].score);
            Serial.print(", x=");
            Serial.print(AI.boxes()[i].x);
            Serial.print(", y=");
            Serial.print(AI.boxes()[i].y);
            Serial.print(", w=");
            Serial.print(AI.boxes()[i].w);
            Serial.print(", h=");
            Serial.println(AI.boxes()[i].h);
        }
        /*
         * Check if we are detecting a dog
         */
        if (AI.boxes()[i].score >= score) {
          connectMQTT();
          //publish mqtt message
          clientMqtt.publish(mqtt_topic, "1");
          controlTime = startTime; //reset control time
          clientMqtt.disconnect();
        }
      }
    }
    //check if since last detection have passed warningTime
    //so we can safely turn off the warning light
    if ((startTime - controlTime) >= (warningTime * 60000)) {
      connectMQTT();
      //turn the warning off
      Serial.println ("Disabling warning");
      clientMqtt.publish(mqtt_topic, "0");
      //disconnect from MQTT
      clientMqtt.disconnect();
    }
    sleep(2); //sleep 2 seconds
}

main.py

MicroPython
The is the main.py for the MicroPython
import ubinascii
import machine
import time
import _thread
from umqtt.simple import MQTTClient

# Led wiring Pin
led = machine.Pin(9, machine.Pin.OUT)

# this will control if we turn on or off the led
ledValue = 0

# control if we have a warning or not
warning = 0

# MQTT Broker
MQTT_BROKER = "192.168.2.31"
ClientID = ubinascii.hexlify(machine.unique_id())
topic = b"cajuWarning"
user = "mosquittouser"
password = "mosquitto"

# callback function
def warningFunction(topic, msg):
    global warning
    print (f"Received message {msg} on topic {topic}")
    if (msg.decode() == "1"):
        warning = 1
    else:
        warning = 0
    print (f"Warning is: {warning}")

# Warning light
def warningLight():
    led.value(ledValue)
    
#connect
print (f"Connecting to MQTT :: {MQTT_BROKER}")
mqttClient = MQTTClient(ClientID, MQTT_BROKER, 1883, user, password)
mqttClient.set_callback(warningFunction)
mqttClient.connect()
print (f"Connected to :: {MQTT_BROKER}")
mqttClient.subscribe(topic)
while True:
    # wait for messages
    # this is non blocking - we must keep turning on and off the LED
    # there's another alternative that is wait_msg - it's blocking.
    # It will wait for a message and block until then
    mqttClient.check_msg()
    if (ledValue == 0 and warning == 1):
        ledValue = 1
    else:
        ledValue = 0
    warningLight()
    print (f"Warning: {warning}\t Led Value: {ledValue}")
    time.sleep(0.2)

boot.py

MicroPython
The boot code for MicroPython. This will connect it to your WiFi network.
import network

# define connect to wifi
def do_connect():
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print ("Connecting to network...")
        sta_if.active(True)
        sta_if.connect('<ssid>','<password>')
        while not sta_if.isconnected():
            pass

    print ("Network config: ",sta_if.ifconfig())


do_connect()

Credits

Bruno Santos

Bruno Santos

4 projects • 3 followers
Linux and Raspberry PI lover! Systems and Network Administrator, programmer, kind of a Nerd!

Comments