├── CODE_OF_CONDUCT.md ├── README.rst ├── adafruit_dht.py ├── api.rst ├── conf.py ├── examples └── dhttoleddisplay.py ├── readthedocs.yml └── requirements.txt /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at support@adafruit.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | 2 | Introduction 3 | ============ 4 | 5 | .. image:: https://readthedocs.org/projects/adafruit-circuitpython-dht/badge/?version=latest 6 | :target: https://circuitpython.readthedocs.io/projects/dht/en/latest/ 7 | :alt: Documentation Status 8 | 9 | .. image :: https://badges.gitter.im/adafruit/circuitpython.svg 10 | :target: https://gitter.im/adafruit/circuitpython?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge 11 | :alt: Gitter 12 | 13 | CircuitPython support for the DHT11 and DHT22 temperature and humidity devices. 14 | 15 | Dependencies 16 | ============= 17 | This driver depends on: 18 | 19 | * `Adafruit CircuitPython `_ 20 | 21 | Please ensure all dependencies are available on the CircuitPython filesystem. 22 | This is easily achieved by downloading 23 | `the Adafruit library and driver bundle `_. 24 | 25 | Usage Example 26 | ============= 27 | 28 | Hardware Set-up 29 | --------------- 30 | 31 | The DHT11 and DHT22 devices both need a pull-resistor on the data signal wire. 32 | This resistor is in the range of 1k to 5k. Please check your device datasheet for the 33 | appropriate value. 34 | 35 | Basics 36 | ------ 37 | 38 | Of course, you must import the library to use it: 39 | 40 | .. code:: python 41 | 42 | import adafruit_dht 43 | 44 | The DHT type devices use single data wire, so import the board pin 45 | 46 | .. code:: python 47 | 48 | from board import 49 | 50 | Now, to initialize the DHT11 device: 51 | 52 | .. code:: python 53 | 54 | dht_device = adafruit_dht.DHT11() 55 | 56 | OR initialize the DHT22 device: 57 | 58 | .. code:: python 59 | 60 | dht_device = adafruit_dht.DHT22() 61 | 62 | Read temperature and humidity 63 | ---------------------------- 64 | 65 | Now get the temperature and humidity values 66 | 67 | .. code:: python 68 | 69 | temperature = dht_device.temperature 70 | humidity = dht_device.humidity 71 | 72 | These properties may raise an exception if a problem occurs. You should use try/raise 73 | logic and catch RuntimeError and then retry getting the values after 1/2 second. 74 | 75 | Contributing 76 | ============ 77 | 78 | Contributions are welcome! Please read our `Code of Conduct 79 | `_ 80 | before contributing to help this project stay welcoming. 81 | 82 | API Reference 83 | ============= 84 | 85 | .. toctree:: 86 | :maxdepth: 2 87 | 88 | api 89 | -------------------------------------------------------------------------------- /adafruit_dht.py: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | # 3 | # Copyright (c) 2017 Mike McWethy for Adafruit Industries 4 | # 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | # 12 | # The above copyright notice and this permission notice shall be included in 13 | # all copies or substantial portions of the Software. 14 | # 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | # THE SOFTWARE. 22 | """ 23 | :mod:`adafruit_dhtlib` 24 | ====================== 25 | 26 | CircuitPython support for the DHT11 and DHT22 temperature and humidity devices. 27 | 28 | * Author(s): Mike McWethy 29 | """ 30 | 31 | import array 32 | import time 33 | try: 34 | import pulseio 35 | except ImportError as excpt: 36 | print("adafruit_dht requires the pulseio library, but it failed to load."+ 37 | " Note that CircuitPython does not support pulseio on all boards.") 38 | raise excpt 39 | 40 | class DHTBase: 41 | """ base support for DHT11 and DHT22 devices 42 | """ 43 | 44 | __hiLevel = 51 45 | 46 | def __init__(self, dht11, pin, trig_wait): 47 | """ 48 | :param boolean dht11: True if device is DHT11, otherwise DHT22. 49 | :param ~board.Pin pin: digital pin used for communication 50 | :param int trig_wait: length of time to hold trigger in LOW state (microseconds) 51 | """ 52 | self._dht11 = dht11 53 | self._pin = pin 54 | self._trig_wait = trig_wait 55 | self._last_called = 0 56 | self._humidity = None 57 | self._temperature = None 58 | 59 | 60 | def _pulses_to_binary(self, pulses, start, stop): 61 | """Takes pulses, a list of transition times, and converts 62 | them to a 1's or 0's. The pulses array contains the transition times. 63 | pulses starts with a low transition time followed by a high transistion time. 64 | then a low followed by a high and so on. The low transition times are 65 | ignored. Only the high transition times are used. If the high 66 | transition time is greater than __hiLevel, that counts as a bit=1, if the 67 | high transition time is less that __hiLevel, that counts as a bit=0. 68 | 69 | start is the starting index in pulses to start converting 70 | 71 | stop is the index to convert upto but not including 72 | 73 | Returns an integer containing the converted 1 and 0 bits 74 | """ 75 | 76 | binary = 0 77 | hi_sig = False 78 | for bit_inx in range(start, stop): 79 | if hi_sig: 80 | bit = 0 81 | if pulses[bit_inx] > self.__hiLevel: 82 | bit = 1 83 | binary = binary<<1 | bit 84 | 85 | hi_sig = not hi_sig 86 | 87 | return binary 88 | 89 | def _get_pulses(self): 90 | """ _get_pulses implements the communication protcol for 91 | DHT11 and DHT22 type devices. It sends a start signal 92 | of a specific length and listens and measures the 93 | return signal lengths. 94 | 95 | return pulses (array.array uint16) contains alternating high and low 96 | transition times starting with a low transition time. Normally 97 | pulses will have 81 elements for the DHT11/22 type devices. 98 | """ 99 | pulses = array.array('H') 100 | tmono = time.monotonic() 101 | 102 | # create the PulseIn object using context manager 103 | with pulseio.PulseIn(self._pin, 81, True) as pulse_in: 104 | 105 | # The DHT type device use a specialize 1-wire protocol 106 | # The microprocessor first sends a LOW signal for a 107 | # specific length of time. Then the device sends back a 108 | # series HIGH and LOW signals. The length the HIGH signals 109 | # represents the device values. 110 | pulse_in.pause() 111 | pulse_in.clear() 112 | pulse_in.resume(self._trig_wait) 113 | 114 | # loop until we get the return pulse we need or 115 | # time out after 1/2 seconds 116 | while True: 117 | if len(pulse_in) >= 80: 118 | break 119 | if time.monotonic()-tmono > 0.5: # time out after 1/2 seconds 120 | break 121 | 122 | pulse_in.pause() 123 | while len(pulse_in): 124 | pulses.append(pulse_in.popleft()) 125 | pulse_in.resume() 126 | 127 | return pulses 128 | 129 | def measure(self): 130 | """ measure runs the communications to the DHT11/22 type device. 131 | if successful, the class properties temperature and humidity will 132 | return the reading returned from the device. 133 | 134 | Raises RuntimeError exception for checksum failure and for insuffcient 135 | data returned from the device (try again) 136 | """ 137 | if time.monotonic()-self._last_called > 0.5: 138 | self._last_called = time.monotonic() 139 | 140 | pulses = self._get_pulses() 141 | ##print(pulses) 142 | 143 | if len(pulses) >= 80: 144 | buf = array.array('B') 145 | for byte_start in range(0, 80, 16): 146 | buf.append(self._pulses_to_binary(pulses, byte_start, byte_start+16)) 147 | #print(buf) 148 | 149 | # humidity is 2 bytes 150 | if self._dht11: 151 | self._humidity = buf[0] 152 | else: 153 | self._humidity = ((buf[0]<<8) | buf[1]) / 10 154 | 155 | # tempature is 2 bytes 156 | if self._dht11: 157 | self._temperature = buf[2] 158 | else: 159 | self._temperature = ((buf[2]<<8) | buf[3]) / 10 160 | 161 | # calc checksum 162 | chk_sum = 0 163 | for b in buf[0:4]: 164 | chk_sum += b 165 | 166 | # checksum is the last byte 167 | if chk_sum & 0xff != buf[4]: 168 | # check sum failed to validate 169 | raise RuntimeError("Checksum did not validate. Try again.") 170 | #print("checksum did not match. Temp: {} Humidity: {} Checksum:{}".format(self._temperature,self._humidity,bites[4])) 171 | 172 | # checksum matches 173 | #print("Temp: {} C Humidity: {}% ".format(self._temperature, self._humidity)) 174 | 175 | else: 176 | raise RuntimeError("A full buffer was not returned. Try again.") 177 | #print("did not get a full return. number returned was: {}".format(len(r))) 178 | 179 | @property 180 | def temperature(self): 181 | """ temperature current reading. It makes sure a reading is available 182 | 183 | Raises RuntimeError exception for checksum failure and for insuffcient 184 | data returned from the device (try again) 185 | """ 186 | self.measure() 187 | return self._temperature 188 | 189 | @property 190 | def humidity(self): 191 | """ humidity current reading. It makes sure a reading is available 192 | 193 | Raises RuntimeError exception for checksum failure and for insuffcient 194 | data returned from the device (try again) 195 | """ 196 | self.measure() 197 | return self._humidity 198 | 199 | class DHT11(DHTBase): 200 | """ Support for DHT11 device. 201 | 202 | :param ~board.Pin pin: digital pin used for communication 203 | """ 204 | def __init__(self, pin): 205 | super().__init__(True, pin, 18000) 206 | 207 | 208 | class DHT22(DHTBase): 209 | """ Support for DHT22 device. 210 | 211 | :param ~board.Pin pin: digital pin used for communication 212 | """ 213 | def __init__(self, pin): 214 | super().__init__(False, pin, 1000) 215 | -------------------------------------------------------------------------------- /api.rst: -------------------------------------------------------------------------------- 1 | 2 | DHT Libary Documentation 3 | ============================ 4 | 5 | .. automodule:: adafruit_dht 6 | :members: 7 | -------------------------------------------------------------------------------- /conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import os 4 | import sys 5 | sys.path.insert(0, os.path.abspath('.')) 6 | 7 | # -- General configuration ------------------------------------------------ 8 | 9 | # Add any Sphinx extension module names here, as strings. They can be 10 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 11 | # ones. 12 | extensions = [ 13 | 'sphinx.ext.autodoc', 14 | 'sphinx.ext.intersphinx', 15 | 'sphinx.ext.viewcode', 16 | ] 17 | 18 | intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None), 19 | 'BusDevice': ('https://circuitpython.readthedocs.io/projects/bus_device/en/latest/', None), 20 | 'Register': ('https://circuitpython.readthedocs.io/projects/register/en/latest/', None), 21 | 'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} 22 | 23 | autodoc_mock_imports = ["pulseio"] 24 | 25 | # Add any paths that contain templates here, relative to this directory. 26 | templates_path = ['_templates'] 27 | 28 | source_suffix = '.rst' 29 | 30 | # The master toctree document. 31 | master_doc = 'README' 32 | 33 | # General information about the project. 34 | project = u'Adafruit CircuitPython DHT Library' 35 | copyright = u'2017 Mike McWethy' 36 | author = u'Mike McWethy' 37 | 38 | # The version info for the project you're documenting, acts as replacement for 39 | # |version| and |release|, also used in various other places throughout the 40 | # built documents. 41 | # 42 | # The short X.Y version. 43 | version = u'1.0' 44 | # The full version, including alpha/beta/rc tags. 45 | release = u'1.0' 46 | 47 | # The language for content autogenerated by Sphinx. Refer to documentation 48 | # for a list of supported languages. 49 | # 50 | # This is also used if you do content translation via gettext catalogs. 51 | # Usually you set "language" from the command line for these cases. 52 | language = None 53 | 54 | # List of patterns, relative to source directory, that match files and 55 | # directories to ignore when looking for source files. 56 | # This patterns also effect to html_static_path and html_extra_path 57 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 58 | 59 | # The reST default role (used for this markup: `text`) to use for all 60 | # documents. 61 | # 62 | default_role = "any" 63 | 64 | # If true, '()' will be appended to :func: etc. cross-reference text. 65 | # 66 | add_function_parentheses = True 67 | 68 | # The name of the Pygments (syntax highlighting) style to use. 69 | pygments_style = 'sphinx' 70 | 71 | # If true, `todo` and `todoList` produce output, else they produce nothing. 72 | todo_include_todos = False 73 | 74 | 75 | # -- Options for HTML output ---------------------------------------------- 76 | 77 | # The theme to use for HTML and HTML Help pages. See the documentation for 78 | # a list of builtin themes. 79 | # 80 | on_rtd = os.environ.get('READTHEDOCS', None) == 'True' 81 | 82 | if not on_rtd: # only import and set the theme if we're building docs locally 83 | try: 84 | import sphinx_rtd_theme 85 | html_theme = 'sphinx_rtd_theme' 86 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.'] 87 | except: 88 | html_theme = 'default' 89 | html_theme_path = ['.'] 90 | else: 91 | html_theme_path = ['.'] 92 | 93 | # Add any paths that contain custom static files (such as style sheets) here, 94 | # relative to this directory. They are copied after the builtin static files, 95 | # so a file named "default.css" will overwrite the builtin "default.css". 96 | html_static_path = ['_static'] 97 | 98 | # Output file base name for HTML help builder. 99 | htmlhelp_basename = 'AdafruitCircuitPythonDHTLibrarydoc' 100 | 101 | # -- Options for LaTeX output --------------------------------------------- 102 | 103 | latex_elements = { 104 | # The paper size ('letterpaper' or 'a4paper'). 105 | # 106 | # 'papersize': 'letterpaper', 107 | 108 | # The font size ('10pt', '11pt' or '12pt'). 109 | # 110 | # 'pointsize': '10pt', 111 | 112 | # Additional stuff for the LaTeX preamble. 113 | # 114 | # 'preamble': '', 115 | 116 | # Latex figure (float) alignment 117 | # 118 | # 'figure_align': 'htbp', 119 | } 120 | 121 | # Grouping the document tree into LaTeX files. List of tuples 122 | # (source start file, target name, title, 123 | # author, documentclass [howto, manual, or own class]). 124 | latex_documents = [ 125 | (master_doc, 'AdafruitCircuitPythonDHTLibrary.tex', u'Adafruit CircuitPython DHT Library Documentation', 126 | author, 'manual'), 127 | ] 128 | 129 | # -- Options for manual page output --------------------------------------- 130 | 131 | # One entry per manual page. List of tuples 132 | # (source start file, name, description, authors, manual section). 133 | man_pages = [ 134 | (master_doc, 'adafruitCircuitPythonDHTlibrary', u'Adafruit CircuitPython DHT Library Documentation', 135 | [author], 1) 136 | ] 137 | 138 | # -- Options for Texinfo output ------------------------------------------- 139 | 140 | # Grouping the document tree into Texinfo files. List of tuples 141 | # (source start file, target name, title, author, 142 | # dir menu entry, description, category) 143 | texinfo_documents = [ 144 | (master_doc, 'AdafruitCircuitPythonDHTLibrary', u'Adafruit CircuitPython DHT Library Documentation', 145 | author, 'AdafruitCircuitPythonDHTLibrary', 'One line description of project.', 146 | 'Miscellaneous'), 147 | ] 148 | -------------------------------------------------------------------------------- /examples/dhttoleddisplay.py: -------------------------------------------------------------------------------- 1 | """ 2 | example of reading temperature and humidity from a DHT device 3 | and displaying results to the serial port and a 8 digit 7-segment display 4 | the DHT device data wire is connected to board.D2 5 | """ 6 | # import for dht devices 7 | import time 8 | import adafruit_dht 9 | from board import D2 10 | 11 | #imports for 7-segment display device 12 | from adafruit_max7219 import bcddigits 13 | from board import TX, RX, A2 14 | import busio 15 | import digitalio 16 | 17 | clk = RX 18 | din = TX 19 | cs = digitalio.DigitalInOut(A2) 20 | spi = busio.SPI(clk, MOSI=din) 21 | display = bcddigits.BCDDigits(spi, cs, nDigits=8) 22 | display.brightness(5) 23 | 24 | #initial the dht device 25 | dhtDevice = adafruit_dht.DHT22(D2) 26 | 27 | while True: 28 | try: 29 | # show the values to the serial port 30 | temperature = dhtDevice.temperature*9/5+32 31 | humidity = dhtDevice.humidity 32 | #print("Temp: {:.1f} F Humidity: {}% ".format(temperature, humidity)) 33 | 34 | # now show the values on the 8 digit 7-segment display 35 | display.clear_all() 36 | display.show_str(0,'{:5.1f}{:5.1f}'.format(temperature, humidity)) 37 | display.show() 38 | 39 | except RuntimeError as error: 40 | print(error.args) 41 | 42 | time.sleep(2.0) 43 | -------------------------------------------------------------------------------- /readthedocs.yml: -------------------------------------------------------------------------------- 1 | requirements_file: requirements.txt 2 | 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrmcwethy/Adafruit_CircuitPython_DHT/f78ad3af16a15e5a135b3649f99edf7aa42e1442/requirements.txt --------------------------------------------------------------------------------