Zephyrnet Logo

Interfacing hardware with appliances using Python3

Date:

3. Control switches Over internet using voice commands

In this code, you have to import one more URL library in python code for open or read/write the data on API. This time I use third party API which is easy to use and access.

import pyttsx3
import speech_recognition as sr
import serial
import time
import urllib.request, urllib.parse, urllib.error
if __name__ == '__main__':
while True:
query = takecommand()
if query == "turn on light":
data = urllib.request.urlopen("https://api.thingspeak.com/update?api_key=3R9TIRNOQ&field1=" + str(1));
print("LED turned ON")
speak("LED turned ON")
time.sleep(1)
if query == 'turn off light':
data = urllib.request.urlopen("https://api.thingspeak.com/update?api_key=3RRK249TINOQ&field1=" + str(0));
print("LED turned OFF")
speak("LED turned OFF")
time.sleep(1)

Hardware sketch

we have to access the internet so, we can use the Nodemcu 12-E developing board which can connect your hardware with the internet, and also it is programmed with the Arduino IDE.

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ThingSpeak.h>
const char* ssid = "your SSID";
const char* password = "your password";
int Relay = D1;
int LED = D2;
WiFiClient client;unsigned long myChannelNumber = 1107673; //Your Channel Number (Without Brackets)
const char * myReadAPIKey = "YBBFTDBQ1R1JHNKT"; //Your Write API Key
void setup() {
Serial.begin (115200);
delay (10);
pinMode(Relay, OUTPUT);
digitalWrite(Relay, LOW);
pinMode(LED, OUTPUT);//CONNECT TO WIFI NETWORK
Serial.println();
Serial.println();
Serial.println("connecting to");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED){
delay(300);
digitalWrite(LED, HIGH);
Serial.print(".");
delay(100);
digitalWrite(LED, LOW);
}

Serial.println("");
Serial.println("WiFi connected");
digitalWrite(LED, HIGH);

//Print the IP address
Serial.println("Use this URL to connect:");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");

ThingSpeak.begin(client);
}

void loop(){

long temp = ThingSpeak.readLongField(myChannelNumber, 1, myReadAPIKey);
int statusCode = ThingSpeak.getLastReadStatus();

if(statusCode == 200){
if(temp == 1)
{
digitalWrite(Relay, HIGH);
Serial.println("HIGH");
Serial.println(temp);
}
if (temp == 0)
{
digitalWrite(Relay, LOW);
Serial.println("LOW");
Serial.println(temp);
}
}
else
{
Serial.println("Unable to read channel / No internet connection");
}
delay(100);
}

Source: https://chatbotslife.com/interfacing-hardware-with-appliances-using-python3-41c74218895b?source=rss—-a49517e4c30b—4

spot_img

Latest Intelligence

spot_img

Chat with us

Hi there! How can I help you?