예제 #1
0
파일: main.py 프로젝트: neilnutt/WaterButt
def measure_distance(samples=41):
    sensor = HCSR04(trigger_pin=3, echo_pin=12)
    distances = list()
    for i in range(0, samples - 1):
        reading = sensor.distance_cm() * 10.0
        if reading is not None and reading > 0.0:
            distances.append(reading)
            time.sleep(0.15)

    distances.sort()
    if len(distances) == 0:
        distance = None
    else:
        mean_distance_mm = sum(distances) / len(distances)
        median_distance_mm = distances[int((samples - 1) / 2)]
        ##print(min(distances),mean_distance_mm,median_distance_mm,max(distances))
        distance = median_distance_mm

    if len(distances) < 9:
        q1 = None
        q3 = None
    else:
        g1 = distances[int((samples) / 4)]
        g3 = distances[int(3 * (samples) / 4)]

    return distance, q1, q3
예제 #2
0
def main():
    with open('config.json', 'r') as file:
        config = ujson.load(file)

    # Get main parameters from config file config.json
    IP = config['host']
    PORT = config['port']
    LOG_PORT = config['logPort']
    HOST = '{}:{}/'.format(IP, PORT)
    LOG = '{}:{}/'.format(IP, LOG_PORT)

    # Set main variables for algorithm
    CHIP_ID = machine.unique_id()
    if CHIP_ID == b'upy-non-unique':
        CHIP_ID = 'agent-{}'.format(int(utime.time()))
        GET_VALUE_FUNCTION = lambda *args: func(*args)
    else:
        CHIP_ID = ubinascii.hexlify(machine.unique_id())

        trig_pin = 16
        echo_pin = 0
        sensor = HCSR04(trigger_pin=trig_pin, echo_pin=echo_pin)
        GET_VALUE_FUNCTION = lambda *args: sensor.distance_cm()

    # Run agent program
    run(CHIP_ID, HOST, LOG, GET_VALUE_FUNCTION)
예제 #3
0
def main():

    try:
        connectWifi(SSID, PASSWORD)

    except Exception as e:
        print('Error %s' % e)
    sensor = HCSR04(trigger_pin=16, echo_pin=0)
예제 #4
0
def init():
    i2c = I2C(scl=Pin(19), sda=Pin(18))
    oled = ssd1306.SSD1306_I2C(128, 64, i2c, 0x3c)
    hcsr04 = HCSR04(trigger_pin=32, echo_pin=35, echo_timeout_us=1000000)
    hcsr501Pin = Pin(26, Pin.IN)
    hcsr501Pin.irq(trigger=Pin.IRQ_FALLING, handler=interruptCallbackHandler)
    
    return oled, hcsr04
예제 #5
0
def print_distance(trigger_pin=trigger_pin_num,
                   echo_pin=echo_pin_num,
                   c=sound_speed,
                   interval=sleep_time):
    sensor = HCSR04(trigger_pin, echo_pin, c)
    led = Pin(2, Pin.OUT)
    led.value(0)
    while True:
        led.value(1)
        print(sensor.distance())
        utime.sleep(interval)
예제 #6
0
def record_dist(prefix='NAME',
                interval_ms=100,
                record_time=10,
                trigger_pin_num=12,
                echo_pin_num=14,
                sound_speed=343,
                write_file=1):
    rtc = RTC()
    sensor = HCSR04(trigger_pin=trigger_pin_num,
                    echo_pin=echo_pin_num,
                    c=sound_speed)
    print('\nUsing sampling interval ', interval_ms, ' milliseconds...')
    print('Recording data for ', record_time, ' seconds...\n')
    ID = hexlify(unique_id()).decode(
        'utf-8')  # Unique ID of the microprocessor
    tmp_file = 'tmp.txt'  # A temporary filename; we will write partial data to this file, and rename only if sampling
    datafile = open(tmp_file, 'w')
    print('\n\n****Beginning Recording ****\n\n')

    timestamp = str(utime.mktime(rtc.datetime()))
    if write_file == 1:
        filename = prefix + '_' + ID + '_' + timestamp + '.txt'
        print('\nCreating data file: ', filename)
    sample_num = (record_time * 1000) / 100

    for sample in range(sample_num + 1):
        t_onboard = rtc.datetime()
        dist = sensor.distance()
        data_str = ''
        print(dist)
        if write_file == 1:
            for t in [sample,t_onboard[0],t_onboard[1],t_onboard[2],t_onboard[4],t_onboard[5], \
                  t_onboard[6],t_onboard[7], dist]:
                data_str += '{} '.format(t)
            if sample == 0:
                datafile = open(tmp_file, 'w')
            else:  # If the first sample, overwrite old tmp_file if it exists
                df = datafile.write(
                    "%s\n" % data_str
                )  # df contains the "result" of the write statement (success or failure)

        else:
            print(sample,t_onboard[0],t_onboard[1],t_onboard[2],t_onboard[3],t_onboard[4],t_onboard[5], \
                 t_onboard[6],t_onboard[7], dist)
        if sample < sample_num:  # Sleep only if another sample is to be taken
            utime.sleep_ms(interval_ms)

        #---------------------------------------
        # Done with the comparison loop; change the temporary filename to the permanent one, now that sampling is complete
    if write_file == 1:  #---------------------------------------
        datafile.close()
        rename(tmp_file, filename)
예제 #7
0
    def __init__(self, io_id, io_user, io_key, frequency, port=1883):
        # Turn sensors on/off
        self.sensor_on = True

        # Save variables passed for use in other methods
        self.io_id = io_id
        self.io_user = io_user
        self.io_key = io_key
        self.update_frequency = frequency
        self.port = port

        self.sensor = HCSR04()
        utime.sleep_ms(100)
        print("Weather MQTT client is ready.")
예제 #8
0
파일: hcsr.py 프로젝트: ignalex/esp
def HCSR(readings=[10, 5], limit=300, echo_timeout_us=500 * 10):
    "[send pulses, min N of positive reply], within limit mm"
    hc = HCSR04(trigger_pin=HCSR_TRIGGER,
                echo_pin=HCSR_SENSOR,
                echo_timeout_us=echo_timeout_us)
    READ = []
    for x in range(0, readings[0]):
        try:
            distance = hc.distance_mm()
            READ.append(distance)  #(int(distance < limit))
        except Exception as e:
            if str(e).find('Out of range') != -1:
                pass
            else:
                print('ERROR getting distance ' + str(e))
    return (len([i for i in READ if i]) >= readings[1], READ)
예제 #9
0
def measure_dist(prefix='ocn351',
                 interval_ms=100,
                 record_time=10,
                 trigger_pin_num=12,
                 echo_pin_num=14,
                 sound_speed=343,
                 write_file=0):
    sensor = HCSR04(trigger_pin=trigger_pin_num,
                    echo_pin=echo_pin_num,
                    c=sound_speed)  # Set up the HCSR04
    print('\nUsing sampling interval ', interval_ms, ' milliseconds...')
    print('Recording data for ', record_time, ' seconds...\n')
    print('\n\n****Beginning Recording ****\n\n')
    runTimer = Timer(-1)  # Initiate a timer
    tmp_file = 'tmp.txt'  # A temporary filename; we will write partial data to this file, and rename only if sampling
    rtc = RTC()  # intiate a real-time clock variable
    ID = hexlify(unique_id()).decode(
        'utf-8')  # Unique ID of the microprocessor
    timestamp = str(utime.mktime(
        rtc.datetime()))  # Create a string time stamp from the real-time clock
    filename = prefix + '_' + ID + '_' + timestamp + '.txt'  # Define a filename to be used if writing a file
    if write_file == 1:  # If writing a file...
        print('\nCreating data file: ', filename, '\n\n')  # Notify user
        datafile = open(
            tmp_file,
            'w')  # Create and open a temporary file for data to be logged to
    else:  # if not writing a file...
        datafile = ''  # Create an empty variable to be passed along
        print('\nNot writing data to file\n')  # Notify user
    # Run a timer that executes our record_dist function periodically, with the interval of the period defined from interval_ms
    runTimer.init(period=interval_ms,
                  mode=Timer.PERIODIC,
                  callback=lambda t: record_dist(sensor, write_file, tmp_file,
                                                 rtc, datafile))
    utime.sleep(
        record_time
    )  # Sleep and let the timer run for the length of time defined by record_time
    runTimer.deinit()  # At the end of our sleep, stop the timer
    if write_file == 1:  # If we've been writing a file...
        datafile.close()  # Close the temporary file
        rename(
            tmp_file, filename
        )  # Rename the temporary file with the filename constructed above
예제 #10
0
파일: Sweet.py 프로젝트: Fa2y/Sweet_Home
def Grab_DATA_Devices_Send():
    from dht import DHT11
    from hcsr04 import HCSR04
    import MQ2
    global Devices_Data, Mqtt_User, MQTT_Client
    while True:
        sleep(5)

        #dht:[pin,[],[]]
        for i in Devices["DHT"]:
            DHT = DHT11(Pin(i, Pin.IN, Pin.PULL_UP))
            DHT.measure()
            Devices_Data["DHT"].append([i, DHT.temperature, DHT.humidity])

        # for i in Devices["GSense"]:
        #         GS = MQ2(pinData = i, baseVoltage = 5)
        #         GS.calibrate()
        #         Devices_Data["GSense"].append([i,GS.readSmoke(), GS.readLPG(), GS.readMethane(), readHydrogen()])
        #         #checking smoke (recheck the values online!!!)
        #         if Devices_Data["GSense"][j][0]>500 or Devices_Data["GSense"][j][1]>500:
        #                 Alarm = True
        #                 Fire_Gas_Alarm()

        j = 0
        for i in Devices["Ultrason"]:
            US = HCSR04(trigger_pin=i[0], echo_pin=i[1])
            if US.distance_cm() > 3.0:
                #Door id and the second value is bool either open or not
                Devices_Data["Ultrason"][j] = [i[0], {"value": True}]
            else:
                Devices_Data["Ultrason"][j] = [i[0], {"value": False}]
            j += 1

        try:
            MQTT_Client.publish(
                bytes(Mqtt_User + "/Values", "UTF-8"),
                bytes(
                    "{'data':" + str(Devices_Data) + ",'clientid':" +
                    MQTT_ClientID + "}", "UTF-8"))
        except OSError as e:
            restart_and_reconnect()
예제 #11
0
 def __init__(self, config, verbose=0):
     self.verbose = verbose
     self.source = 'WaterLevel'
     self.channel = 'WaterLevel'
     self.config = config
     self.ultrasound = HCSR04(
         trigger_pin=config['pinout']['ultrasound']['trig_pin'],
         echo_pin=config['pinout']['ultrasound']['echo_pin'])
     self.tank_model = config['device']['tank']['model']
     self.tank_height = config['device']['tank']['height']
     self.tank_volume = config['device']['tank']['volume']
     self.lid_inclination = config['device']['tank']['lid_inclination']
     self.read_interval = config['device']['level_read_interval']
     self.start = None
     self.level_queue = []
     self.queue_depth = 10
     self.calibration_depth = 100
     self._calibrated = False
     self.level_average = 0
     self.level_percentile = 0.0
     self.level_volume = 0
     self.level_readings = 0
예제 #12
0
def measure_dist(prefix='ocn351',
                 interval_ms=100,
                 record_time=5,
                 trigger_pin_num=12,
                 echo_pin_num=13,
                 sound_speed=343,
                 write_file=0):
    global startSampleFlag
    startSampleFlag = 0
    sensor = HCSR04(trigger_pin=trigger_pin_num,
                    echo_pin=echo_pin_num,
                    c=sound_speed)  # Set up the HCSR04
    print('\nUsing sampling interval ', interval_ms, ' milliseconds...')
    print('Recording data for ', record_time, ' seconds...\n')
    print('\n\n****Beginning Recording ****\n\n')
    runTimer = Timer(-1)  # Initiate a timer
    tmp_file = 'tmp.txt'  # A temporary filename; we will write partial data to this file, and rename only if sampling
    rtc = RTC()  # intiate a real-time clock variable
    ID = hexlify(unique_id()).decode(
        'utf-8')  # Unique ID of the microprocessor
    timestamp = str(utime.mktime(
        rtc.datetime()))  # Create a string time stamp from the real-time clock
    filename = prefix + '_' + ID + '_' + timestamp + '.txt'  # Define a filename to be used if writing a file
    if write_file == 1:  # If writing a file...
        print('\nCreating data file: ', filename, '\n\n')  # Notify user
        datafile = open(
            tmp_file,
            'w')  # Create and open a temporary file for data to be logged to
    else:  # if not writing a file...
        datafile = ''  # Create an empty variable to be passed along
        print('\nNot writing data to file\n')  # Notify user
    # Run a timer that executes our record_dist function periodically, with the interval of the period defined from interval_ms
    print('\nWaiting For Trigger\n')
    while True:
        if startSampleFlag == 1:
            startSampleFlag = 0
            init_record(runTimer, record_time, interval_ms, sensor, write_file,
                        tmp_file, rtc, datafile, filename)
예제 #13
0
def coleta():

    sensor = HCSR04(trigger_pin=16, echo_pin=0)
    servo = machine.PWM(machine.Pin(12), freq=50)
    distance = sensor.distance_cm()

    i = 30
    servo.duty(30)

    while i < 115:  #Giro do servo

        servo.duty(i)
        time.sleep(0.5)
        distance = sensor.distance_cm()  #Leitura do sensor
        time.sleep(0.5)
        if distance > 60:
            print('60,', end='')
        else:
            print(distance, ',', end='')
        time.sleep(0.5)
        i = i + 14  #Logica de rotação em 30 gráus
    print(' ')
    print('---x-----x----')
    time.sleep(1)
예제 #14
0
from hcsr04 import HCSR04
from machine import Pin,I2C
import ssd1306
import time
 
i2c = I2C(0)      #i2c hardware olarak baslatildi ESP32 icin scl=18, sda=19 
oled=ssd1306.SSD1306_I2C(128,64,i2c) 
 
sensor = HCSR04(trigger_pin=13, echo_pin=15,echo_timeout_us=1000000)
 
try:
  while True:
    distance = sensor.distance_cm()
    print(distance)
    oled.fill(0)
    oled.text("Distance:",30,20) 
    oled.text(str(distance),30,40)
    oled.show()
    time.sleep(0.1)
except KeyboardInterrupt:
       pass    
예제 #15
0
# TRIG      13
# ECHO      15
# GND       G

from hcsr04 import HCSR04  # import hcsr04
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import time

import neopixel
led_sayisi = 8
np = neopixel.NeoPixel(Pin(4), led_sayisi)

oled = SSD1306_I2C(128, 64, I2C(0))  #i2c hardware olarak kullaniliyor

MesafeSensoru = HCSR04(trigger_pin=13, echo_pin=15, echo_timeout_us=1000000)

while True:
    mesafe = int(MesafeSensoru.distance_cm())

    print(mesafe, " cm")

    oled.fill(0)
    oled.text("Mesafe", 30, 20)
    oled.text(str(mesafe), 30, 40)  # degiskenler once string'e cevirilmelidir
    oled.show()

    if mesafe < 10:
        for n in range(led_sayisi):
            np[n] = (32, 0, 0)
예제 #16
0
from hcsr04 import HCSR04

sensor = HCSR04(trigger_pin=16, echo_pin=0)

distance = sensor.distance_cm()

print('Distance:', distance, 'cm')

distance = sensor.distance_mm()

print('Distance:', distance, 'mm')

############################

from hcsr04 import HCSR04

sensor = HCSR04(trigger_pin=16, echo_pin=0, echo_timeout_us=1000000)

distance = sensor.distance_cm()

print('Distance:', distance, 'cm')
############################

from hcsr04 import HCSR04

sensor = HCSR04(trigger_pin=16, echo_pin=0, echo_timeout_us=10000)

try:
    distance = sensor.distance_cm()
    print('Distance:', distance, 'cm')
except OSError as ex:
예제 #17
0
 def __init__(self, trigger_pin, echo_pin, bottle_height_cm, ml_per_cm):
     self.sensor = HCSR04(trigger_pin=trigger_pin, echo_pin=echo_pin)
     self.bottle_height_cm = bottle_height_cm
     self.ml_per_cm = ml_per_cm
예제 #18
0
RANDOM_TURN_MAX = 1000  # ms
COLLISION_THRESHOLD = 30  # cm
APPROACH_THRESHOLD = 100  #cm
MAX_SPEED_THRESHOLD = 250  #cm
LR_COMPENSATION = +10  # %, -10 slows L motor comared to R
ULTRASONIC_SAMPLING = 1000  # ms, how often detect obstacle

moto_L1 = Pin(pinout.MOTOR_1A, Pin.OUT)
moto_L2 = Pin(pinout.MOTOR_2A, Pin.OUT)
moto_L = PWM(Pin(pinout.MOTOR_12EN, Pin.OUT), freq=500, duty=0)

moto_R3 = Pin(pinout.MOTOR_3A, Pin.OUT)
moto_R4 = Pin(pinout.MOTOR_4A, Pin.OUT)
moto_R = PWM(Pin(pinout.MOTOR_34EN, Pin.OUT), freq=500, duty=0)

echo = HCSR04(trigger_pin=pinout.PWM2_PIN, echo_pin=pinout.PWM1_PIN)


def compensate_speed_left(speed):
    return speed + int(speed / 100 * LR_COMPENSATION / 2)


def compensate_speed_right(speed):
    return speed - int(speed / 100 * LR_COMPENSATION / 2)


def forward(speed):
    moto_L1.value(0)
    moto_L2.value(1)

    moto_R3.value(0)
예제 #19
0
import urequests
import socket

#driver for distance_cm()
from hcsr04 import HCSR04

CFG_BSSID='SRRU-IoT'
CFG_BSSID_PASS='******'

FRONT_LED = machine.Pin(2, machine.Pin.OUT)
P1 = machine.Pin(16, machine.Pin.OUT)
P2 = machine.Pin(5, machine.Pin.OUT)
P3 = machine.Pin(4, machine.Pin.OUT)
P4 = machine.Pin(0, machine.Pin.OUT)

FRONT = HCSR04(trigger_pin=12, echo_pin=14, echo_timeout_us=1000000)

def __init__():
    print("INIT")
    print('Frequency ', machine.freq())
    FRONT_LED.value(1)
    ap = network.WLAN(network.AP_IF)
    ap.active(False)

def stop():
    print("stop")
    FRONT_LED.value(0)
    P1.on()
    P2.on()
    P3.on()
    P4.on()
예제 #20
0
from hcsr04 import HCSR04
import time

sensor = HCSR04(trigger_pin=26, echo_pin=25)

while 1:
    distance = sensor.distance_cm()

    print('Distance:', distance, 'cm')

    time.sleep(.3)
예제 #21
0
import time
import RPi.GPIO as GPIO
import threading
from hx711 import HX711
from hcsr04 import HCSR04

GPIO.setwarnings(False)
hx = HX711(5, 6)
hx.set_reading_format("MSB", "MSB")
hx.set_reference_unit(95.20)
hx.reset()
hx.tare()

hc = HCSR04(18, 24)


def measure_dist():
    d = hc.distance()
    return d


def measure_wt():
    val = max(0, int(hx.get_weight(5)))
    return val


while True:
    time.sleep(0.1)
    x = measure_dist()
    time.sleep(0.1)
    y = measure_wt()
예제 #22
0
 def __init__(self):
     self.hcsr04 = HCSR04(trigger_pin=Pin.P14, echo_pin=Pin.P15)
예제 #23
0
 def __init__(self, *args, **kwargs):
     print("Initializing distance")
     super().__init__(*args, **kwargs)
     self.sensor = HCSR04(trigger_pin=self.settings["trigger_pin"], echo_pin=self.settings["echo_pin"])
예제 #24
0
from hcsr04 import HCSR04
from time import sleep_ms

sensor = HCSR04(trigger_pin=19, echo_pin=18)

while True:
    print(sensor.distance_cm())
    sleep_ms(50)
예제 #25
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     from hcsr04 import HCSR04
     self.sensor = HCSR04(trigger_pin=self.settings["trig_pin"],
                          echo_pin=self.settings["echo_pin"])
예제 #26
0
import json
import time
# libraries used for sensors for RPi
import RPi.GPIO as GPIO
import threading
from hx711 import HX711
from hcsr04 import HCSR04

GPIO.setwarnings(False)
hx = HX711(5, 6)  # GPIO pins from RPI used for the load-cell sensor
hx.set_reading_format("MSB", "MSB")
hx.set_reference_unit(95.20)  # calibrating load cell
hx.reset()
hx.tare()

hc = HCSR04(18, 24)  # GPIO pins from RPI used for the ultra-sonic sensor


# allows data to be read over groups think-speak channel
def readData():
    URl = 'https://api.thingspeak.com/channels/1173908/feeds.json?api_key=6G647UFZ4V0F7XL2&results=2'
    KEY = '6G647UFZ4V0F7XL2'
    HEADER = '&results=1'
    NEW_URL = URl + KEY + HEADER
    #print(NEW_URL)

    get_data = requests.get(NEW_URL).json()
    #print(get_data)

    channel_id = get_data['channel']['id']
예제 #27
0
    wlan = None
    s = None

    mySensorArray1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    mySensorArray2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    mySensorArray3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    mySensorArray4 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    mySensorArray5 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

    hitCount1 = 0
    hitCount2 = 0
    hitCount3 = 0
    hitCount4 = 0
    hitCount5 = 0

    mySensor1 = HCSR04(trigger_pin=12, echo_pin=4)
    mySensor2 = HCSR04(trigger_pin=14, echo_pin=16)
    mySensor3 = HCSR04(trigger_pin=27, echo_pin=17)
    mySensor4 = HCSR04(trigger_pin=26, echo_pin=5)
    mySensor5 = HCSR04(trigger_pin=25, echo_pin=18)

    mySensorBaseAvg = 270  ##REMEMBER TO SET TO ACTUAL VALUE!

    for x in range(9):
        mySensorArray1[x] = mySensorBaseAvg
    for x in range(9):
        mySensorArray2[x] = mySensorBaseAvg
    for x in range(9):
        mySensorArray3[x] = mySensorBaseAvg
    for x in range(9):
        mySensorArray4[x] = mySensorBaseAvg
예제 #28
0
    print("Received disconnect message.  Shutting down.")
    sys.exit()


## For H-bridge
pin1a = machine.PWM(machine.Pin(27), freq=1000)
pin1b = machine.PWM(machine.Pin(14), freq=1000)
pin2a = machine.PWM(machine.Pin(12), freq=1000)
pin2b = machine.PWM(machine.Pin(13), freq=1000)

set_zero()
## set pin 26 as a pwm pin for servo rotation
servo_pin = machine.PWM(machine.Pin(26), freq=50)
servo_pin.duty(77)
## For HCSR04
sensor = HCSR04(trigger_pin=25, echo_pin=33, echo_timeout_us=3000)
# set pin 25 and 33 as as trigger and echo pin

event = None

localIP = '0.0.0.0'
localPort = 3000
bufferSize = 1024

msgFromServer = "Hello UDP Client"

##bytesToSend         = str.encode(msgFromServer)
UDPServerSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

UDPServerSocket.bind((localIP, localPort))
UDPServerSocket.settimeout(0.01)
예제 #29
0
def init():
    i2c = I2C(scl=Pin(19), sda=Pin(18))
    oled = ssd1306.SSD1306_I2C(128, 64, i2c, 0x3c)
    sensor = HCSR04(trigger_pin=32, echo_pin=35, echo_timeout_us=1000000)

    return oled, sensor
예제 #30
0
from hcsr04 import HCSR04
import time
from payloader import Payloader
import utime
import urequests as u
import ujson
while True:
    sensor = HCSR04(trigger_pin=5, echo_pin=4)
    distance = sensor.distance_cm()
    data = {
        "jarak-1": distance,
        "jarak-2": distance
    }  #di bagian ini diisi dengan data yang dikirim
    #jika data ada banyak maka perlu di format menggunakan bentuk JSON dengan data menjadi nilai-nya
    col = 'ultrasonik'  #nama collection diisi dengan nama identifikasi sensor
    p = Payloader(data, col)
    p.send()
    utime.sleep_ms(1000)