Exemplo n.º 1
0
def handleInterrupt(tim):
    global addr
    print(esp32.raw_temperature())
    print(esp32.hall_sensor())
    s = usocket.socket()
    s.connect(addr)
    addr = usocket.getaddrinfo('www.thingspeak.com',80)[0][-1]
    #s = usocket.socket()
    imfor = "field1="+str(esp32.raw_temperature())+"&field2="+str(esp32.hall_sensor())
    s.send(b'GET https://api.thingspeak.com/update?api_key=YO282TSJI25DUDBU&{} HTTP/1.0\r\n\r\n'.format(imfor))
    s.close()
Exemplo n.º 2
0
def main():
    ble = bluetooth.BLE()
    remote = BLEHeadrushRemote(ble)

    previous_pot_value = -1
    button_down = None
    button_hall_sensor = False
    button_hall_sensor_down = False
    button_pot = False
    button_pot_down = False
    while True:
        if remote.is_connected():
            # foot switches
            for command, button in _BUTTON_PIN_MAP.items():
                if not button_down == command and button.value() == 0:
                    button_down = command
                    print("sending '{command}'.".format(command=command))
                    # remote.send(struct.pack("I", command))
                    remote.send(command)
                    blink_led(2)
                    break
                elif button_down == command and button.value() == 1:
                    button_down = None

            # POT
            if _BUTTON_POT.value() == 0 and not button_pot_down:
                button_pot = not button_pot
                button_pot_down = True
            elif _BUTTON_POT.value() == 1 and button_pot_down:
                button_pot_down = False
            if button_pot:
                pot_value = int(_POT.read() / 32)
                if previous_pot_value not in [
                        pot_value - 1, pot_value, pot_value + 1
                ]:
                    # wheels: 61, 62, 63
                    number = 61
                    previous_pot_value = pot_value
                    remote.send("POT|{}|{}".format(number, pot_value))
                if _LED_POT_STATUS.value() == 0:
                    _LED_POT_STATUS.value(1)
            else:
                if _LED_POT_STATUS.value() == 1:
                    _LED_POT_STATUS.value(0)

            # Hall sensor
            if _BUTTON_HALL_SENSOR.value(
            ) == 0 and not button_hall_sensor_down:
                button_hall_sensor = not button_hall_sensor
                button_hall_sensor_down = True
            elif _BUTTON_HALL_SENSOR.value() == 1 and button_hall_sensor_down:
                button_hall_sensor_down = False
            if button_hall_sensor:
                hall_vallue = esp32.hall_sensor()
                print(hall_vallue)
                if _LED_HALL_SENSOR.value() == 0:
                    _LED_HALL_SENSOR.value(1)
            else:
                if _LED_HALL_SENSOR.value() == 1:
                    _LED_HALL_SENSOR.value(0)
Exemplo n.º 3
0
def mqtt_publish(t):
    client.publish("test/{}/alive".format(mqtt_client_settings["client_id"]),
                   str(alive))
    client.publish("test/{}/hall".format(mqtt_client_settings["client_id"]),
                   str(esp32.hall_sensor()))
    client.publish("test/{}/temp".format(mqtt_client_settings["client_id"]),
                   str((esp32.raw_temperature() - 32) / 1.8))
def thingspeak():
    int_temp = esp32.raw_temperature()
    hall_val = esp32.hall_sensor()
    print()
    print("Internal Temperature: " + str(int_temp) + " Degrees Fahrenheit")
    print("Hall: " + str(hall_val))

    #send temperature info
    s = socket.socket()
    address = socket.getaddrinfo("thingspeak.com", 80)[0][-1]
    s.connect(address)
    s.send(
        b"GET https://api.thingspeak.com/update?api_key=0P5Y117MOWZABDHV&field1="
        + str(int_temp) + " HTTP/1.0\r\n\r\n")
    s.close()
    time.sleep(18)

    #send hall info
    s = socket.socket()
    address = socket.getaddrinfo("thingspeak.com", 80)[0][-1]
    s.connect(address)
    s.send(
        "GET https://api.thingspeak.com/update?api_key=0P5Y117MOWZABDHV&field2="
        + str(hall_val) + " HTTP/1.0\r\n\r\n")
    s.close()
Exemplo n.º 5
0
def button_pressed():
    iotine.publish([{
        "name": "CORE_TEMP_ESP",
        "value": esp32.raw_temperature()
    }, {
        "name": "CORE_HALL",
        "value": esp32.hall_sensor()
    }], on_pub)
def calibrateHallSensor():  
  
  local_magnetism=[]
  for i in range(1000): #Why 1000? idk just some big random number
      #time.sleep_ms(0) #Set calibration frequency
      local_magnetism.append(esp32.hall_sensor())
  #Set high-low filter boundary values
  local_magnetism_high=round(max(local_magnetism),2)
  local_magnetism_low=round(min(local_magnetism),2)
  return local_magnetism_high,local_magnetism_low
Exemplo n.º 7
0
def _httpHandlerSensors(httpClient, httpResponse):
    data = 'Hall: {0:.1f} <br> CPU: {1:.1f}&deg;C'.format(
        esp32.hall_sensor(), esp32.raw_temperature())
    # es funktionieren keine \n im string.
    httpResponse.WriteResponseOk(headers=({
        'Cache-Control': 'no-cache'
    }),
                                 contentType='text/event-stream',
                                 contentCharset='UTF-8',
                                 content='data: {0}\n\n'.format(data))
Exemplo n.º 8
0
def hardDispTime(timer):
    t = esp32.raw_temperature()
    h = esp32.hall_sensor()
    print("temperature (°F): " + str(t))
    print("hall sensor: " + str(h))

    base_url = 'https://api.thingspeak.com/update'
    API_key = '?api_key=R1N8YAFNXLY6MMWM'
    fieldanddata = "&field1=" + str(t) + "&field2=" + str(h)
    url = base_url + API_key + fieldanddata
    http_get(url)
Exemplo n.º 9
0
    def hall_sensor(self):
        import esp32

        value = 0
        while True:
            new_value = esp32.hall_sensor()
            if new_value != value:
                print(new_value)

            value = new_value
            time.sleep(0.1)
Exemplo n.º 10
0
def send_sensor_values_mqtt():
    # send cpu temperature
    mqtt.publish('cpu_temp', str(esp32.raw_temperature()))
    # send hall_sensor
    mqtt.publish('hall_sensor', str(esp32.hall_sensor()))
    #send bme280 values
    mqtt.publish('temperature', str(bme.temperature_float))
    mqtt.publish('humidity', str(bme.humidity_float))
    mqtt.publish('pressure', str(bme.pressure_float))
    #analog tmp sensor
    mqtt.publish('analog_tmp', str(tmp_sensor.read()))
    mqtt.publish('ip_address', str(wifi.get_ip()))
def send(lora):
    counter = 0
    print("LoRa Sender")

    while True:
        data = esp32.hall_sensor()
        payload = 'Hal {0}'.format(data)
        print("Sending packet: \n{}\n".format(payload))
        lora.println(payload)
        lora.show_text("Send %i" % counter)
        counter += 1
        sleep(5)
Exemplo n.º 12
0
def hall_sensor_handler():
    value = esp32.hall_sensor()
    if len(oleds) > 0:
        oled0 = oleds[0]
        oled0.fill_rect(0, 32, 48, 8, 0)
        oled0.text(str(value), 0, 32)  # 50 - 1800
        if value < 0: value = -value
        value = map_value(value, 50, 150, 0, 128)
        oled0.fill_rect(0, 48, 128, 16, 0)
        oled0.fill_rect(0, 48, value, 16, 1)
        oled0.show()
    else:
        print("Hall sensor: " + str(value), end="    \r")
Exemplo n.º 13
0
def btn_callback(p):
    if (display.menu_page == 0):
        display.write('Temp: ' + bme.temperature, 'Humidity: ' + bme.humidity,
                      'Pressure: ' + bme.pressure)
        display.next_page()
    elif (display.menu_page == 1):
        display.write('Internal', 'IP:' + wifi.get_ip(),
                      'Hall:' + str(esp32.hall_sensor()),
                      'CPU:' + str(esp32.raw_temperature()))
        display.next_page()
    elif (display.menu_page == 2):
        display.write('last page')
        display.wrap()
Exemplo n.º 14
0
def getdata(counter, flag):
    if (counter < 30) & (flag == 1):
        temp = esp32.raw_temperature()
        hall = esp32.hall_sensor()
        print('Hall:'+str(hall), 'Temperature:'+str(temp))
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sockaddr = socket.getaddrinfo('api.thingspeak.com', 80)[0][-1]
        sock.connect(sockaddr)
        sock.sendall("GET https://api.thingspeak.com/update?api_key=4XEMEDRHEKUNEHHQ&field1="+str(temp)+"&field2="+str(hall)+"HTTP/1.0\r\n\r\n")
        sock.recv(1024)
        sock.close()
    elif(counter == 30):
        flag = 0
Exemplo n.º 15
0
    def detect_magnetism():

        i = 0
        local_magnetism = []
        while i < 1000:
            i += 1
            time.sleep_ms(0)
            local_magnetism.append(esp32.hall_sensor())

            #print(local_magnetism,'\n')
        m_avg = sum(local_magnetism) / len(local_magnetism)
        print('Local magnetism measure =', m_avg)
        return m_avg, local_magnetism
Exemplo n.º 16
0
    def display_info(self):
        gc.collect()
        output = dict(
            freq=int(machine.freq() / 1_000_000),
            flash=esp.flash_size(),
            hall=esp32.hall_sensor(),
            temp=int((esp32.raw_temperature() - 32) / 1.8),
            mac=self.network.mac,
            ip=self.network.ip,
            ram=gc.mem_free(),
        )

        output = ["%s: %s" % (key, val) for key, val in output.items()]

        self.screen.display_lines(output)
Exemplo n.º 17
0
def fullSend(counter):
    temperature = str(esp32.raw_temperature())
    hall_sensor = str(esp32.hall_sensor())
    print("Temperature is " + temperature)
    print("Hall is " + hall_sensor)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    address = socket.getaddrinfo('api.thingspeak.com', 80)[0][-1]
    s.connect(address)
    s.send(
        "GET http://api.thingspeak.com/update?api_key=3VDFM8XC3RT41CEJ&field1="
        + temperature + "&field2=" + hall_sensor + "HTTP/1.0\r\n\r\n")
    counter += 1
    print(s.recv(1024))
    s.close()
Exemplo n.º 18
0
def measure():
    HALL = esp32.hall_sensor()
    TEMP = esp32.raw_temperature()
    print("Temp: " + str(TEMP))
    print("Hall: " + str(HALL))
    api_key = 'F1Z7M4ES4TCB1UFO'
    host = 'api.thingspeak.com'
    path = 'update?api_key=' + api_key + '&field1=' + str(TEMP) + '&field2=' + str(HALL)
    try:
        addr = socket.getaddrinfo(host, 80)[0][-1]
        s = socket.socket()
        s.connect(addr)
        s.send(bytes('GET /' + path + ' HTTP/1.0\r\n\r\n', 'utf8'))
        s.close()
        sleep(0.1)
    except Exception as e: # Here it catches any error.
        print(e)
def measureLocalMagnetism(number_of_measurements,frequency,led=led):  
  local_magnetism_high,local_magnetism_low=calibrateHallSensor()
  i=0
  while i<number_of_measurements:
    i+=1
    time.sleep(frequency) 
    #Start internal esp32 sensors measurements
    local_magnetism= esp32.hall_sensor()
    temp=getInternalTemperature()
    #Check if local_magnetism passes high-low filter
    if local_magnetism > local_magnetism_high:
      print(local_magnetism-local_magnetism_high,temp) #it seems the integrated hall sensor has high variance
      flash(3*log(local_magnetism),led,0.02)
    elif local_magnetism < local_magnetism_low:
      print(local_magnetism-local_magnetism_low,temp)
      flash(3*log(local_magnetism),led,0.02)
    else:
      print(0.0,temp)
Exemplo n.º 20
0
 async def sys_monitor():
     row1 = "4. System monitor"
     row1_colour = 'black'
     row2 = "Uptime: %s" % (time() - net.startup_time)
     row2_colour = 'blue'
     row3 = "Mem free: %s" % gc.mem_free()
     row3_colour = 'blue'
     row4 = "Mem allocated: %s" % gc.mem_alloc()
     row4_colour = 'blue'
     row5 = "Flash size: %s " % esp.flash_size()
     row5_colour = 'blue'
     row6 = "MCU Temp: %sC" % ("{:.1f}".format(((float(esp32.raw_temperature())-32.0) * 5/9)))
     row6_colour = 'blue'
     row7 = "Hall sensor %s" % esp32.hall_sensor()
     row7_colour = 'blue'
     rows = row1, row2, row3, row4, row5, row6, row7
     row_colours = row1_colour, row2_colour, row3_colour, row4_colour, row5_colour, row6_colour, row7_colour
     return rows, row_colours
Exemplo n.º 21
0
async def sivu_3():
    """ Statussivulla näytetään yleisiä tietoja """
    await naytin.teksti_riville("STATUS", 0, 5)
    await naytin.piirra_alleviivaus(0, 6)
    await naytin.teksti_riville("Up s.: %s" % (utime.time() - aloitusaika), 1,
                                5)
    await naytin.teksti_riville(
        "AP: %s" % network.WLAN(network.STA_IF).config('essid'), 2, 5)
    await naytin.teksti_riville(
        "rssi: %s" % network.WLAN(network.STA_IF).status('rssi'), 3, 5)
    await naytin.teksti_riville("Memfree: %s" % gc.mem_free(), 4, 5)
    await naytin.teksti_riville("Hall: %s" % esp32.hall_sensor(), 5, 5)
    await naytin.kaanna_180_astetta(True)
    #  Himmennetään näyttöä yöksi
    if (ratkaise_aika()[1] > '20:00:00') and (ratkaise_aika()[1] < '08:00:00'):
        await naytin.kontrasti(2)
    else:
        await naytin.kontrasti(100)
    await naytin.aktivoi_naytto()
    await asyncio.sleep_ms(100)
Exemplo n.º 22
0
def send_data(timer):    
    html = """
    POST /update HTTP/1.1
    Host: api.thingspeak.com
    Connection: close
    X-THINGSPEAKAPIKEY: 3ODNWZEY2LM86CTX
    Content-Type: application/x-www-form-urlencoded
    Content-Length: %d
    %s
    """
    temp = esp32.raw_temperature()
    hall = esp32.hall_sensor()
    print('Temperature: '+str(temp)+', Hall: '+str(hall))
    s = socket.socket()
    s.connect(addr)
    s = ssl.wrap_socket(s)
    data = 'field1=%.2f&field2=%.2f' % (temp, hall)
    http = html & (len(data), data)
    s.write(http.encode())
    s.close()
Exemplo n.º 23
0
def main_routine():
    # Gather Data
    dt = {
        "uid": unique_id(),
        "ssid": cnf.ssid,
        "addr": net_if.station_interface.ifconfig()[0],
        "localtime": localtime(),
        "cpu_temp": str(int((raw_temperature() - 32) / 1.8)),
        "hall": hall_sensor()
    }

    # Send Inform
    inform_client.send(dumps(dt))

    # Display On LCD
    lcd.network(dt["ssid"], dt["addr"])
    sleep_ms(1000)
    lcd.time(dt["localtime"])
    sleep_ms(1000)
    lcd.sensor(dt["cpu_temp"], dt["hall"])
    sleep_ms(1000)
Exemplo n.º 24
0
def getSystemInfo(NetworkInfo, uart):
    CPU_freq = machine.freq(
    )  # frequency must be 20MHz, 40MHz, 80Mhz, 160MHz or 240MHz
    CPU_temper = esp32.raw_temperature(
    )  # TSENS 值是一个字节,范围是 0 - 255,其数值变化和环境温度变化近似成线性关系,用户需要自己定义和测量其对应的外界温度值。
    hall = esp32.hall_sensor()  # 霍尔传感器的原始值
    allocRAM = gc.mem_alloc()
    freeRAM = gc.mem_free()
    systemInfo = {
        'networkinfo': NetworkInfo,
        'config': config,
        'sys': {
            'freq': CPU_freq,
            'temper': CPU_temper,
            'hall': hall,
            'alloc': allocRAM,
            'free': freeRAM
        },
        'log': {
            'OK200': [request.requestCount, request.requestSuccess],
            'uart': uart
        }
    }
    return json.dumps(systemInfo)
Exemplo n.º 25
0
def hallSensor(number_of_measurements, frequency):
    from machine import I2C, Pin
    import esp32
    import time
    """The library to write to the OLED display isn’t 
  part of the standard MicroPython library by default. 
  So, you need to upload the library to your ESP32/ESP8266 board. """
    import ssd1306

    oled_rst = Pin(16, Pin.OUT)
    oled_rst.value(1)

    esp32.hall_sensor()  #Measure Hall effect

    # ESP32 Pin assignment
    i2c = I2C(-1, Pin(15), Pin(4))
    #Configure your OLED display using the appropiate pixel resolution
    oled_width = 128
    oled_height = 64
    text_row = []
    for n in range(7):
        text_row.append(
            n * 10 + 4
        )  #this will give you 6 lines with the default text size. print(text_row[n])
    #Create a display object where you will drwa your shapes.
    display = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
    #Optional: Set all pixels off
    display.fill(0)
    #Vertically centered text
    display.text('Hall', 19, text_row[2])
    display.text('Effect', 19, text_row[3])
    display.show()

    #the esp32 is just too slow to execute this function
    """
    def displayText(string1,string2):
  
    def __init__():
      string1=''
      string2=''
  
    i2c = I2C(-1, Pin(15), Pin(4))
    display = ssd1306.SSD1306_I2C(128, 64, i2c)
    display.fill(0)
    #Set the appropiate parameters for x,y coordinated according to font size
    display.text(str(string1), 0,5)
    display.text(str(string2), 0,15)
    display.show()
"""

    #Calibrate the sensor to neglect local magnestism
    def detect_magnetism():

        i = 0
        local_magnetism = []
        while i < 1000:
            i += 1
            time.sleep_ms(0)
            local_magnetism.append(esp32.hall_sensor())

            #print(local_magnetism,'\n')
        m_avg = sum(local_magnetism) / len(local_magnetism)
        print('Local magnetism measure =', m_avg)
        return m_avg, local_magnetism

    m_avg, local_magnetism = detect_magnetism()

    #Set high-low filter boundary values
    high = round(max(local_magnetism), 2)
    low = round(min(local_magnetism), 2)

    #Activate sensor readings
    i = 0
    j = 0
    while i < number_of_measurements:
        i += 1
        time.sleep(frequency)

        if esp32.hall_sensor() > high or esp32.hall_sensor() < low:
            j += 1
            print(i, 1)  #it seems the integrated hall sensor has high variance

            for n in range(80, 120):
                for m in range(25, 45):
                    display.pixel(n, m, 0)
            display.text(str(j), 90, text_row[3])
            display.show()

        else:
            print(i, 0)
Exemplo n.º 26
0
def hall():
    # read the internal hall sensor
    return esp32.hall_sensor()
Exemplo n.º 27
0
    val = ''
    data = cl.recv(1024)
    val += str(data, 'utf8')
    try:
        action = val.split(' HTTP')[0].split('?')[1]
        if action == 'red_led=on':
            led_red.value(1)
        elif action == 'red_led=off':
            led_red.value(0)
        elif action == 'green_led=on':
            led_grn.value(1)
        elif action == 'green_led=off':
            led_grn.value(0)
    except:
        pass

    HALL = esp32.hall_sensor()
    TEMP = esp32.raw_temperature()
    if button_0.value():
        b0 = 'ON'
    else:
        b0 = 'OFF'
    if button_1.value():
        b1 = 'ON'
    else:
        b1 = 'OFF'
    pg = web_page(TEMP, HALL, led_red.value(), led_grn.value(), b0, b1)
    cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
    cl.send(pg)
    cl.close()
Exemplo n.º 28
0
    
if __name__ == "__main__":
    connect_wifi()
    
    p12 = Pin(12, Pin.OUT)
    p25 = Pin(25, Pin.OUT)
    if p12.value() == 0:
        RED_LED_STATE = "OFF"
    else:
        RED_LED_STATE = "ON"
    if p25.value() == 0:
        GREEN_LED_STATE = "OFF"
    else:
        GREEN_LED_STATE = "ON"
    temperature = str(esp32.raw_temperature())
    hall_sensor = str(esp32.hall_sensor())
    htmlwebpage = web_page(temperature, hall_sensor, RED_LED_STATE, GREEN_LED_STATE)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 80))
    s.listen(5)
    while(True):
        conn, addr = s.accept()
        print('Got a connection from %s' % str(addr))
        request = conn.recv(1024)
        request = str(request)
        print('Content = %s' % request)
        redled_on = request.find('/?red_led=on')
        redled_off = request.find('/?red_led=off')
        greenled_on = request.find('/?green_led=on')
        greenled_off = request.find('/?green_led=off')
        if redled_on == 6:
Exemplo n.º 29
0
import esp32
import time
from machine import Pin

led = Pin(5, Pin.OUT)

while True:
    hall_sensor = esp32.hall_sensor()
    print(hall_sensor)
    #print("Temperature:")
    #print(esp32.raw_temperature())
    if (hall_sensor > 100):
        led.value(False)
    else:
        led.value(True)
    #led.value(not led.value())
    time.sleep(1)
Exemplo n.º 30
0
# author: h.serimer 03.2021 https://github.com/eproje/uPy_Course
# Board: Lolin32 Lite
# read internal HALL sensor from esp32 chip
# REF: https://docs.micropython.org/en/latest/library/esp32.html

from time import sleep
import esp32

#ref
#esp32.hall_sensor()     # read the internal hall sensor
#esp32.raw_temperature() # read the internal temperature of the MCU, in Farenheit
#esp32.ULP()             # access to the Ultra-Low-Power Co-processor

while True:
    print(esp32.hall_sensor())
    sleep(0.1)