0% found this document useful (0 votes)
47 views8 pages

Pymatafirmatacode

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views8 pages

Pymatafirmatacode

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

from pymata4 import pymata4

import time
board = pymata4.Pymata4()
analog_pin =0
digital_pin = 8
board.set_pin_mode_analog_input(analog_pin)
board.set_pin_mode_digital_input(digital_pin)
while True:
value, time_stamp = board.analog_read(analog_pin)
print(value)
time.sleep(1)

MOISTURE SENSOR

try:
from pyfirmata import Arduino,util
except:
import pip
pip.main(["install",'pyfirmata'])
from pyfirmata import Arduino,util

board=Arduino('COM5')
iterator=util.Iterator(board)
iterator.start()
analog_0 = board.get_pin('a:0:i')
print(analog_0.read())
board.exit()

TEMPERATURE AND HUMIDITY SENSORS USING PYMATA 4

"""

try:
from pyfirmata import Arduino,util
except:
import pip
pip.main(["install",'pyfirmata'])
from pyfirmata import Arduino,util

board=Arduino('COM5')
Moist_pin=0

iterator=util.Iterator(board)
iterator.start()
value=board.analog[Moist_pin].read()

print(value)
"""

import time
import sys
from pymata4 import pymata4

"""
Setup a pin for dht mode
One pin is set for a dht22 and another for dht11
Both polling and callback are being used in this example.
"""

#
POLL_TIME = 5 # number of seconds between polls

# Callback data indices


CB_PIN_MODE = 0
CB_PIN = 1
CB_VALUE = 2
CB_TIME = 3

def the_callback(data):
"""
A callback function to report data changes.
This will print the pin number, its reported value and
the date and time when the change occurred

:param data: [report_type, pin, dht_type, error_value,


humidity, temperature, timestamp]
"""

if not data[3]:
tlist = time.localtime(data[6])
ftime = f'{tlist.tm_year}-{tlist.tm_mon:02}-{tlist.tm_mday:02} ' \
f'{tlist.tm_hour:02}:{tlist.tm_min:0}:{tlist.tm_sec:02}'

print(f'Pin: {data[1]} DHT Type: {data[2]} Humidity:{data[4]}, '


f'Temperature: {data[5]} Timestamp: {ftime}')

def dht(my_board, callback=None):


"""
This function establishes the pin as a
digital input. Any changes on this pin will
be reported through the call back function.

:param my_board: a pymata4 instance


:param callback: callback funtion
"""

# set the pin mode - for pin 6 differential is set explicitly


my_board.set_pin_mode_dht(4, sensor_type=22, differential=.05,
callback=callback)
# my_board.set_pin_mode_dht(9, sensor_type=22, differential=.05,
callback=callback)

# my_board.set_pin_mode_dht(10, sensor_type=22, differential=.05,


callback=callback)
# my_board.set_pin_mode_dht(11, sensor_type=11, differential=.05,
callback=callback)

# a flag to change the differential value after the first 5 seconds


changed = False
while True:
try:
time.sleep(POLL_TIME)

# poll the first dht


value = board.dht_read(4)

# format the time string and then print the data


tlist = time.localtime(value[2])
ftime = f'{tlist.tm_year}-{tlist.tm_mon:02}-{tlist.tm_mday:02} ' \
f'{tlist.tm_hour:02}:{tlist.tm_min:0}:{tlist.tm_sec:02}'
print(f'poll pin 8: humidity={value[0]} temp={value[1]} '
f'time of last report: {ftime}')

# poll the second DHT and print the values


value = board.dht_read(4)
tlist = time.localtime(value[2])
ftime = f'{tlist.tm_year}-{tlist.tm_mon:02}-{tlist.tm_mday:02} ' \
f'{tlist.tm_hour:02}:{tlist.tm_min:0}:{tlist.tm_sec:02}'
print(f'poll pin 9: humidity={value[0]} temp={value[1]} '
f'time of last report: {ftime}')

# poll the third dht

# value = board.dht_read(10)

# format the time string and then print the data


# tlist = time.localtime(value[2])
# ftime = f'{tlist.tm_year}-{tlist.tm_mon:02}-{tlist.tm_mday:02} ' \
# f'{tlist.tm_hour:02}:{tlist.tm_min:0}:{tlist.tm_sec:02}'
# print(f'poll pin 10: humidity={value[0]} temp={value[1]} '
# f'time of last report: {ftime}')

# poll the fourth DHT


# value = board.dht_read(11)
# tlist = time.localtime(value[2])
# ftime = f'{tlist.tm_year}-{tlist.tm_mon:02}-{tlist.tm_mday:02} ' \
# f'{tlist.tm_hour:02}:{tlist.tm_min:0}:{tlist.tm_sec:02}'
# print(f'poll pin 11: humidity={value[0]} temp={value[1]} '
# f'time of last report: {ftime}')
# if not changed:
# explicitly change the differential values

# my_board.set_pin_mode_dht(8, sensor_type=11, differential=2.0,


# callback=callback)
# my_board.set_pin_mode_dht(9, sensor_type=22, differential=20.0,
# callback=callback)
# my_board.set_pin_mode_dht(10, sensor_type=22, differential=20.0,
# callback=callback)
# my_board.set_pin_mode_dht(11, sensor_type=11, differential=2.0,
# callback=callback)
# changed = True
except KeyboardInterrupt:
board.shutdown()
sys.exit(0)

board = pymata4.Pymata4()

try:
dht(board, the_callback)
except KeyboardInterrupt:
board.shutdown()
sys.exit(0)

import serial
Arduino=serial.Serial('COM5',9600)
while true:
if(Arduino.inWaiting()>0)
myData=Arduino.readline()
print(myData)

import serial
import time
import schedule
#arduino = serial.Serial('COM3',9600)

def dht():
arduino = serial.Serial('COM3',9600);
print("Established serial connection to Arduino")
arduino_data = arduino.readline()
decoded_values = str(arduino_data[0:len(arduino_data)].decode("utf-8"))
list_values = decoded_values.split('x')

for item in list_values:


list_in_floats.append(str(item))

print(f'collected readings from Arduino: {list_in_floats}')

arduino_data=0
list_in_floats.clear()
list_values.clear()
#arduino.close()
print('Connection closed')
print('<---------------->')

#MAIN CODE

list_values = []
list_in_floats = []

print('Program started')

schedule.every(5).seconds.do(dht)
while True:
schedule.run_pending()
#time.sleep(1)

LDR SENSOR

light = 100 * float(board.analog_read(analog_pin)[0]) / 1024

return {'light': round(light, 1)}

int WATERPUMP = 13; //motor pump connected to pin 13


int sensor = 8; //sensor digital pin vonnected to pin 8
int val; //This variable stores the value received from Soil moisture sensor.

void setup() {

pinMode(13,OUTPUT); //Set pin 13 as OUTPUT pin


pinMode(8,INPUT); //Set pin 8 as input pin, to receive data from Soil moisture
sensor.
//Initialize serial and wait for port to open:
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
while (! Serial);// wait for serial port to connect. Needed for native USB
Serial.println("Speed 0 to 255");
}

void loop()
{
if (Serial.available()) //loop to operate motor
{
int speed = Serial.parseInt(); // to read the number entered as text in the
Serial Monitor
if (speed >= 0 && speed <= 255)
{
analogWrite(WATERPUMP, speed);// tuns on the motor at specified speed
}
}
val = digitalRead(8); //Read data from soil moisture sensor
if(val == LOW)
{
digitalWrite(13,LOW); //if soil moisture sensor provides LOW value send LOW value
to motor pump and motor pump goes off
}
else
{
digitalWrite(13,HIGH); //if soil moisture sensor provides HIGH value send HIGH
value to motor pump and motor pump get on
}
delay(400); //Wait for few second and then continue the loop.
}
WIFI

"""
Copyright (c) 2020 Alan Yorinks All rights reserved.

This program is free software; you can redistribute it and/or


modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
Version 3 as published by the Free Software Foundation; either
or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.

You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
import sys
import time

from pymata4 import pymata4

"""
This program tests an ESP-8266 using StandardFirmataWiFi.
It will toggle the on-board LED 4 times.

Change the IP address and IP port to match that in the


StandardFirmataWiFi config file.
"""

# some globals
DIGITAL_PIN = 16 # arduino pin number
IP_ADDRESS = "192.168.2.189"
IP_PORT = 3030

def blink(my_board, pin):


"""
This function will to toggle a digital pin.

:param my_board: an PymataExpress instance


:param pin: pin to be controlled
"""

# set the pin mode


my_board.set_pin_mode_digital_output(pin)
my_board.digital_write(pin, 1)

# toggle the pin 4 times and exit


for x in range(4):
print('ON')
my_board.digital_write(pin, 1)
time.sleep(1)
print('OFF')
my_board.digital_write(pin, 0)
time.sleep(1)

my_board.shutdown()

board = pymata4.Pymata4(ip_address=IP_ADDRESS, ip_port=IP_PORT)


try:
blink(board, DIGITAL_PIN)
except KeyboardInterrupt:
board.shutdown()
sys.exit(0)

wifi using serial #!/usr/bin/python


# -*- coding: iso-8859-15 -*-

import logging
import sys, serial
from time import *
import datetime, string

def enum(**enums):
return type('Enum', (), enums)

Status = enum(ERR='ERROR', OK=['OK', 'ready', 'no change'], BUSY='busy')


logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

# modified code from: http://www.instructables.com/id/Easy-ESP8266-WiFi-Debugging-


with-Python/step2/Software/
def send_cmd( sCmd, waitTm=1, retry=5 ):
lp = 0
ret = ""

logging.info( "Sending command: %s" % sCmd )

for i in range(retry):
ser.flushInput()
ser.write( sCmd + "\r\n" )
ret = ser.readline() # Eat echo of command.
sleep( 0.2 )
while( lp < waitTm or 'busy' in ret):
while( ser.inWaiting() ):
ret = ser.readline().strip( "\r\n" )
logging.debug( ret )
lp = 0
if( ret in Status.OK ): break
#if( ret == 'ready' ): break
if( ret == Status.ERR ): break
sleep( 1 )
lp += 1

sleep(1)
if( ret in Status.OK ): break
logging.info( "Command result: %s" % ret )
return ret

if len(sys.argv) != 5:
print "Usage: esp8266test.py port baud_rate ssid password"
sys.exit()

port = sys.argv[1]
#Baud rate should be: 9600 or 115200
speed = sys.argv[2]
ssid = sys.argv[3]
pwd = sys.argv[4]

ser = serial.Serial(port,speed)
if ser.isOpen():
ser.close()
ser.open()
ser.isOpen()

send_cmd( "AT" )
# send_cmd( "AT+RST", 5 ) # NOTE: seems to cause problems that require manually
reset (pulling down the RST pin)
# sleep(3)
send_cmd( "AT+CWMODE=1" ) # set device mode (1=client, 2=AP, 3=both)
#The mode will be changed on Olimex MOD-WIFI-ESP8266-DEV only after a reset
#The command below will reset the device
send_cmd( "AT+RST");
send_cmd( "AT+CWLAP", 10) # scan for WiFi hotspots
send_cmd( "AT+CWJAP=\""+ssid+"\",\""+pwd+"\"", 5 ) # connect
addr = send_cmd( "AT+CIFSR", 5) # check IP address

ser.close()

You might also like