Skip to content

Instantly share code, notes, and snippets.

@boneskull
Last active November 12, 2021 22:45
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save boneskull/1f5ae354815c6db5b1cb05ad2cb6232b to your computer and use it in GitHub Desktop.
Save boneskull/1f5ae354815c6db5b1cb05ad2cb6232b to your computer and use it in GitHub Desktop.
MicroPython on ESP32: MQTT and DS18B20 temperature sensor full example
def connect():
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect('<YOUR SSID>', '<YOUR PASSWORD>')
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())
def no_debug():
import esp
# this can be run from the REPL as well
esp.osdebug(None)
no_debug()
connect()
import time
from ds18x20 import DS18X20
from machine import Pin
from onewire import OneWire
class TemperatureSensor:
"""
Represents a Temperature sensor
"""
def __init__(self, pin):
"""
Finds address of single DS18B20 on bus specified by `pin`
:param pin: 1-Wire bus pin
:type pin: int
"""
self.ds = DS18X20(OneWire(Pin(pin)))
addrs = self.ds.scan()
if not addrs:
raise Exception('no DS18B20 found at bus on pin %d' % pin)
# save what should be the only address found
self.addr = addrs.pop()
def read_temp(self, fahrenheit=True):
"""
Reads temperature from a single DS18X20
:param fahrenheit: Whether or not to return value in Fahrenheit
:type fahrenheit: bool
:return: Temperature
:rtype: float
"""
self.ds.convert_temp()
time.sleep_ms(750)
temp = self.ds.read_temp(self.addr)
if fahrenheit:
return self.c_to_f(temp)
return temp
@staticmethod
def c_to_f(c):
"""
Converts Celsius to Fahrenheit
:param c: Temperature in Celsius
:type c: float
:return: Temperature in Fahrenheit
:rtype: float
"""
return (c * 1.8) + 32
import json
import time
from temperature import TemperatureSensor
from umqtt.robust import MQTTClient
class TemperatureClient:
"""
Represents an MQTT client which publishes temperature data on an interval
"""
def __init__(self, client_id, server, pin, fahrenheit=True, topic=None,
**kwargs):
"""
Instantiates a TemperatureSensor and MQTTClient; connects to the
MQTT broker.
Arguments `server` and `client_id` are required.
:param client_id: Unique MQTT client ID
:type client_id: str
:param server: MQTT broker domain name / IP
:type server: str
:param pin: 1-Wire bus pin
:type pin: int
:param fahrenheit: Whether or not to publish temperature in Fahrenheit
:type fahrenheit: bool
:param topic: Topic to publish temperature on
:type topic: str
:param kwargs: Arguments for MQTTClient constructor
"""
self.sensor = TemperatureSensor(pin)
self.client = MQTTClient(client_id, server, **kwargs)
if not topic:
self.topic = 'devices/%s/temperature/degrees' % \
self.client.client_id
else:
self.topic = topic
self.fahrenheit = bool(fahrenheit)
self.client.connect()
def publishTemperature(self):
"""
Reads the current temperature and publishes a JSON payload on the
configured topic, e.g., `{"unit": "F", "degrees": 72.5}`
"""
t = self.sensor.read_temp(self.fahrenheit)
payload = dict(degrees=t)
if self.fahrenheit:
payload['unit'] = 'F'
else:
payload['unit'] = 'C'
self.client.publish(self.topic, json.dumps(payload))
def start(self, interval=60):
"""
Begins to publish temperature data on an interval (in seconds).
This function will not exit! Consider using deep sleep instead.
:param interval: How often to publish temperature data (60s default)
:type interval: int
"""
while True:
self.publishTemperature()
time.sleep(interval)
@Avi-TelnT
Copy link

Hi
I am looking to hire an ESP32 Python programmer to help me to develop a firework interface for ESP32 I2S for a mic on I2S ICS-43434 IC and play wav using I2S MAX98357A IC. The target is work needed Google speech recognition and Google text to speech from ESP32.
The development environment must be https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo
If you have an experience on ESP32 MicroPython_ESP32_psRAM_LoBo Python please reply my email nissim@telnt.com
And call my Skype nissim.test
The work is milestone-based and payment will be as milestone below,
We will provide the hardware for that :

  1. Expose to LoBO Python the ESP32-IDE /MicroPython/Tools/esp-idf/components/driver/include/driver/I2S.H and I2S.C by integrate them in machine module so dir(machine) will show the I2S interface and commands to set I2S for recording and playing using the ESP32 DMA.
  2. Use the above machine.I2S to record and play a wav file a digital mic on
    I2S ICS-43434 IC and play wav using MAX98357A IC
  3. Make an audio PTT (Push-To-Talk) instead of PCB button. By detecting the rising level on the recorded audio level, ok voice keyword recognized.
  4. Doing above but record and play from ram with Flak encoding as needed by Google SR AND TTS. See https://cloud.google.com/speech-to-text/docs/encoding
  5. I need to use SR to get the recognized the Mic audio, as text returns from Google back to ESP32, modify the return text with meaningful information and send to be played by Google TTS. Like Siri. With ESP32.
    As:
    You Say to Mic I2S ICS-43434 “What is the temperature now?”
    Get back the text in ESP32 Python “What is the temperature now”
    ESP32 Send to TTS “The temperature now is 30 degree”
    The return wav or Flak been played to using MAX98357A over I2S
  6. So, I believe to expose I2S code from ESP32 C to Python will not be a big work.
    a. Google API use wav Audio Encoding name: FLAC Free Lossless Audio Codec 16-bit or 24-bit required for streams.
    b. So, FLAC can be done in C or Python. But interface must be from Python. See https://goo.gl/mtrwVN
  7. Maybe this is a good source for FLAC in C https://goo.gl/cCYFTh
    Contact :
    Nissim Zur
    nissim@telnt.com
    Skype: nissim.test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment