├── Adafruit_I2C.py ├── LICENSE ├── README.md ├── __init__.py ├── blinkled.py ├── blinky ├── blinky.py └── ds18b20.py ├── burnraspian.sh ├── ds18b20.py ├── ds18b20.pyc ├── google.py ├── luxreader.py ├── mini.jpg ├── readings.py ├── sensortests ├── AM2302 │ ├── AdafruitDHT.py │ ├── google_spreadsheet.py │ ├── simpletest.py │ └── test.sh ├── BMP180 │ └── simpletest.py ├── DS18B20 │ ├── check.sh │ └── test.py └── TSL2561 │ ├── Adafruit_I2C.py │ ├── Adafruit_I2C.pyc │ └── test.py └── texty ├── ds18b20.py └── texty.py /Adafruit_I2C.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import re 3 | import smbus 4 | 5 | # =========================================================================== 6 | # Adafruit_I2C Class 7 | # =========================================================================== 8 | 9 | class Adafruit_I2C(object): 10 | 11 | @staticmethod 12 | def getPiRevision(): 13 | "Gets the version number of the Raspberry Pi board" 14 | # Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History 15 | try: 16 | with open('/proc/cpuinfo', 'r') as infile: 17 | for line in infile: 18 | # Match a line of the form "Revision : 0002" while ignoring extra 19 | # info in front of the revsion (like 1000 when the Pi was over-volted). 20 | match = re.match('Revision\s+:\s+.*(\w{4})$', line) 21 | if match and match.group(1) in ['0000', '0002', '0003']: 22 | # Return revision 1 if revision ends with 0000, 0002 or 0003. 23 | return 1 24 | elif match: 25 | # Assume revision 2 if revision ends with any other 4 chars. 26 | return 2 27 | # Couldn't find the revision, assume revision 0 like older code for compatibility. 28 | return 0 29 | except: 30 | return 0 31 | 32 | @staticmethod 33 | def getPiI2CBusNumber(): 34 | # Gets the I2C bus number /dev/i2c# 35 | return 1 if Adafruit_I2C.getPiRevision() > 1 else 0 36 | 37 | def __init__(self, address, busnum=-1, debug=False): 38 | self.address = address 39 | # By default, the correct I2C bus is auto-detected using /proc/cpuinfo 40 | # Alternatively, you can hard-code the bus version below: 41 | # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's) 42 | # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's) 43 | self.bus = smbus.SMBus(busnum if busnum >= 0 else Adafruit_I2C.getPiI2CBusNumber()) 44 | self.debug = debug 45 | 46 | def reverseByteOrder(self, data): 47 | "Reverses the byte order of an int (16-bit) or long (32-bit) value" 48 | # Courtesy Vishal Sapre 49 | byteCount = len(hex(data)[2:].replace('L','')[::2]) 50 | val = 0 51 | for i in range(byteCount): 52 | val = (val << 8) | (data & 0xff) 53 | data >>= 8 54 | return val 55 | 56 | def errMsg(self): 57 | print "Error accessing 0x%02X: Check your I2C address" % self.address 58 | return -1 59 | 60 | def write8(self, reg, value): 61 | "Writes an 8-bit value to the specified register/address" 62 | try: 63 | self.bus.write_byte_data(self.address, reg, value) 64 | if self.debug: 65 | print "I2C: Wrote 0x%02X to register 0x%02X" % (value, reg) 66 | except IOError, err: 67 | return self.errMsg() 68 | 69 | def write16(self, reg, value): 70 | "Writes a 16-bit value to the specified register/address pair" 71 | try: 72 | self.bus.write_word_data(self.address, reg, value) 73 | if self.debug: 74 | print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" % 75 | (value, reg, reg+1)) 76 | except IOError, err: 77 | return self.errMsg() 78 | 79 | def writeRaw8(self, value): 80 | "Writes an 8-bit value on the bus" 81 | try: 82 | self.bus.write_byte(self.address, value) 83 | if self.debug: 84 | print "I2C: Wrote 0x%02X" % value 85 | except IOError, err: 86 | return self.errMsg() 87 | 88 | def writeList(self, reg, list): 89 | "Writes an array of bytes using I2C format" 90 | try: 91 | if self.debug: 92 | print "I2C: Writing list to register 0x%02X:" % reg 93 | print list 94 | self.bus.write_i2c_block_data(self.address, reg, list) 95 | except IOError, err: 96 | return self.errMsg() 97 | 98 | def readList(self, reg, length): 99 | "Read a list of bytes from the I2C device" 100 | try: 101 | results = self.bus.read_i2c_block_data(self.address, reg, length) 102 | if self.debug: 103 | print ("I2C: Device 0x%02X returned the following from reg 0x%02X" % 104 | (self.address, reg)) 105 | print results 106 | return results 107 | except IOError, err: 108 | return self.errMsg() 109 | 110 | def readU8(self, reg): 111 | "Read an unsigned byte from the I2C device" 112 | try: 113 | result = self.bus.read_byte_data(self.address, reg) 114 | if self.debug: 115 | print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % 116 | (self.address, result & 0xFF, reg)) 117 | return result 118 | except IOError, err: 119 | return self.errMsg() 120 | 121 | def readS8(self, reg): 122 | "Reads a signed byte from the I2C device" 123 | try: 124 | result = self.bus.read_byte_data(self.address, reg) 125 | if result > 127: result -= 256 126 | if self.debug: 127 | print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % 128 | (self.address, result & 0xFF, reg)) 129 | return result 130 | except IOError, err: 131 | return self.errMsg() 132 | 133 | def readU16(self, reg, little_endian=True): 134 | "Reads an unsigned 16-bit value from the I2C device" 135 | try: 136 | result = self.bus.read_word_data(self.address,reg) 137 | # Swap bytes if using big endian because read_word_data assumes little 138 | # endian on ARM (little endian) systems. 139 | if not little_endian: 140 | result = ((result << 8) & 0xFF00) + (result >> 8) 141 | if (self.debug): 142 | print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) 143 | return result 144 | except IOError, err: 145 | return self.errMsg() 146 | 147 | def readS16(self, reg, little_endian=True): 148 | "Reads a signed 16-bit value from the I2C device" 149 | try: 150 | result = self.readU16(reg,little_endian) 151 | if result > 32767: result -= 65536 152 | return result 153 | except IOError, err: 154 | return self.errMsg() 155 | 156 | if __name__ == '__main__': 157 | try: 158 | bus = Adafruit_I2C(address=0) 159 | print "Default I2C bus is accessible" 160 | except: 161 | print "Error accessing default I2C bus" 162 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Raspberry Pi Mini Weather Station 2 | 3 | 4 | 5 | ## Raspberry Pi Weather Station 6 | 7 | Measures: 8 | 9 | * Temperature 10 | * Humidity 11 | * Atmospheric Pressure 12 | * Lux 13 | 14 | [Check out the dashboard!](http://jeremymorgan.github.io/Raspberry_Pi_Weather_Station/#/) 15 | 16 | ## Parts you'll need: 17 | 18 | * AM2302 Temperature / Humidity Sensor 19 | * BMP180 Temperature / Barometric Pressure Sensor 20 | * DS18B20 Waterproof Temperature Sensor 21 | * TSL2561 Digital Lumosity Sensor 22 | 23 | ## Installation Instructions: 24 | 25 | These instructions have been tested with the latest version of Raspian, however they should run in most distributions of Linux fairly easily. 26 | 27 | Wire up the sensors as shown here: 28 | 29 | 30 | ### Set up the AM302 31 | 32 | Here we set up the AM2302 Humidity Sensor. 33 | 34 | Clone the Adafruit Python DHT Library 35 | ``` 36 | git clone https://github.com/adafruit/Adafruit_Python_DHT.git 37 | ``` 38 | Build some tools 39 | 40 | ``` 41 | sudo apt-get update 42 | 43 | sudo apt-get install build-essential python-dev python-openssl 44 | 45 | sudo python setup.py install 46 | ``` 47 | 48 | ### Set up the DSB18B20 49 | 50 | You will need to add One Wire Support: 51 | 52 | ``` 53 | sudo nano /boot/config.txt 54 | ``` 55 | 56 | Add the following line: 57 | ``` 58 | dtoverlay=w1-gpio 59 | ``` 60 | 61 | Reboot the Pi: 62 | 63 | ``` 64 | sudo reboot 65 | ``` 66 | 67 | Add smbus and i2c tools: 68 | 69 | ``` 70 | sudo apt-get install python-smbus 71 | sudo apt-get install i2c-tools 72 | ``` 73 | 74 | You may get "already installed" Messages from this 75 | 76 | ``` 77 | sudo nano /etc/modules 78 | ``` 79 | 80 | Add the following: 81 | 82 | ``` 83 | i2c-bcm2708 84 | i2c-dev 85 | ``` 86 | Modify boot config: 87 | 88 | ``` 89 | sudo nano /boot/config.txt 90 | ``` 91 | 92 | Add the following lines: 93 | 94 | ``` 95 | dtparam=i2c1=on 96 | dtparam=i2c_arm=on 97 | ``` 98 | Reboot the Pi: 99 | 100 | ``` 101 | sudo reboot 102 | ``` 103 | 104 | ### Set up the TSL2561 105 | 106 | cd ~/sources 107 | 108 | ``` 109 | wget https://raw.githubusercontent.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/master/Adafruit_I2C/Adafruit_I2C.py 110 | wget https://raw.githubusercontent.com/seanbechhofer/raspberrypi/master/python/TSL2561.py 111 | ``` 112 | 113 | (Thanks to Sean!) 114 | 115 | ### Set up the BMP 180 116 | 117 | ``` 118 | git clone https://github.com/adafruit/Adafruit_Python_BMP.git 119 | cd Adafruit_Python_BMP 120 | sudo python setup.py install 121 | ``` 122 | 123 | ### Test the sensors 124 | 125 | ``` 126 | git clone https://github.com/JeremyMorgan/Raspberry_Pi_Weather_Station.git reader 127 | cd reader 128 | sudo python readings.py dryrun 129 | ``` 130 | 131 | 132 | 133 | 134 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'jeremymorgan' 2 | -------------------------------------------------------------------------------- /blinkled.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO ## Import GPIO Library 2 | import time ## Import 'time' library (for 'sleep') 3 | 4 | pin = 16 ## These are our LEDs 5 | ourdelay = 3 ## Delay 6 | # pins 4,17,18,21,22,23,24,25 7 | 8 | GPIO.setmode(GPIO.BOARD) ## Use BOARD pin numbering 9 | GPIO.setup(pin, GPIO.OUT) ## set output 10 | 11 | ## function to save code 12 | 13 | def activateLED( pin, delay ): 14 | GPIO.output(pin, GPIO.HIGH) ## set HIGH (LED ON) 15 | time.sleep(delay) ## wait 16 | GPIO.output(pin, GPIO.LOW) ## set LOW (LED OFF) 17 | return; 18 | 19 | activateLED(pin,ourdelay) 20 | 21 | GPIO.cleanup() ## close down library 22 | -------------------------------------------------------------------------------- /blinky/blinky.py: -------------------------------------------------------------------------------- 1 | import os 2 | import RPi.GPIO as GPIO 3 | import time 4 | from ds18b20 import ds18b20_read_temp 5 | from twilio.rest import TwilioRestClient 6 | 7 | # put your own credentials here 8 | ACCOUNT_SID = "AC659a0e8b39db4bb242e9b4670ae0e3f2" 9 | AUTH_TOKEN = "[AuthToken]" 10 | 11 | 12 | pin = 16 ## These are our LEDs 13 | ourdelay = .1 ## Delay 14 | # pins 4,17,18,21,22,23,24,25 15 | 16 | threshold = 80 17 | 18 | GPIO.setmode(GPIO.BOARD) ## Use BOARD pin numbering 19 | GPIO.setup(pin, GPIO.OUT) ## set output 20 | 21 | ## function to save code 22 | 23 | def activateLED( pin, delay ): 24 | GPIO.output(pin, GPIO.HIGH) ## set HIGH (LED ON) 25 | time.sleep(delay) ## wait 26 | GPIO.output(pin, GPIO.LOW) ## set LOW (LED OFF) 27 | return 28 | 29 | led = False 30 | os.system("clear") 31 | 32 | while True: 33 | temp = 9.0/5.0 * ds18b20_read_temp() + 32 34 | print(temp) 35 | 36 | if ((temp > threshold) & (led == False)): 37 | activateLED(pin,ourdelay) 38 | led = True 39 | else: 40 | if ((led == True) &(temp < threshold)): 41 | led = False 42 | activateLED(pin,ourdelay) 43 | 44 | time.sleep(1) 45 | 46 | 47 | GPIO.cleanup() ## close down library 48 | -------------------------------------------------------------------------------- /blinky/ds18b20.py: -------------------------------------------------------------------------------- 1 | import time 2 | import glob 3 | 4 | base_dir = '/sys/bus/w1/devices/' 5 | device_folder = glob.glob(base_dir + '28*')[0] 6 | device_file = device_folder + '/w1_slave' 7 | 8 | def ds18b20_read_temp_raw(): 9 | f = open(device_file, 'r') 10 | lines = f.readlines() 11 | f.close() 12 | return lines 13 | 14 | def ds18b20_read_temp(): 15 | lines = ds18b20_read_temp_raw() 16 | while lines[0].strip()[-3:] != 'YES': 17 | time.sleep(0.2) 18 | lines = ds18b20_read_temp_raw() 19 | equals_pos = lines[1].find('t=') 20 | if equals_pos != -1: 21 | temp_string = lines[1][equals_pos+2:] 22 | temp_c = float(temp_string) / 1000.0 23 | temp_f = temp_c * 9.0 / 5.0 + 32.0 24 | return temp_c -------------------------------------------------------------------------------- /burnraspian.sh: -------------------------------------------------------------------------------- 1 | 2 | 3 | //sha1sum 2015-05-05-raspbian-wheezy.img 4 | //cb799af077930ff7cbcfaa251b4c6e25b11483de 5 | 6 | dd bs=4M if=2015-05-05-raspbian-wheezy.img of=/dev/sdb -------------------------------------------------------------------------------- /ds18b20.py: -------------------------------------------------------------------------------- 1 | import time 2 | import glob 3 | 4 | base_dir = '/sys/bus/w1/devices/' 5 | device_folder = glob.glob(base_dir + '28*')[0] 6 | device_file = device_folder + '/w1_slave' 7 | 8 | def ds18b20_read_temp_raw(): 9 | f = open(device_file, 'r') 10 | lines = f.readlines() 11 | f.close() 12 | return lines 13 | 14 | def ds18b20_read_temp(): 15 | lines = ds18b20_read_temp_raw() 16 | while lines[0].strip()[-3:] != 'YES': 17 | time.sleep(0.2) 18 | lines = ds18b20_read_temp_raw() 19 | equals_pos = lines[1].find('t=') 20 | if equals_pos != -1: 21 | temp_string = lines[1][equals_pos+2:] 22 | temp_c = float(temp_string) / 1000.0 23 | temp_f = temp_c * 9.0 / 5.0 + 32.0 24 | return temp_c -------------------------------------------------------------------------------- /ds18b20.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeremyMorgan/Raspberry_Pi_Weather_Station/c62914ef26f19fda478467b989abeba9386179c3/ds18b20.pyc -------------------------------------------------------------------------------- /google.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import json 4 | import sys 5 | import time 6 | import datetime 7 | 8 | # libraries 9 | import sys 10 | import urllib2 11 | import json 12 | import Adafruit_DHT 13 | import Adafruit_BMP.BMP085 as BMP085 14 | import gspread 15 | from oauth2client.client import SignedJwtAssertionCredentials 16 | 17 | # custom functions 18 | from ds18b20 import ds18b20_read_temp 19 | import luxreader 20 | 21 | # Instance of TSL2561 Class 22 | luxrdr = luxreader.TSL2561() 23 | 24 | # Config 25 | am2302Pin = 22 26 | 27 | # Oauth JSON File 28 | GDOCS_OAUTH_JSON = 'Mini Weather Station-f68343d4a35a.json' 29 | 30 | # Google Docs spreadsheet name. 31 | GDOCS_SPREADSHEET_NAME = 'Sensors' 32 | 33 | # How long to wait (in seconds) between measurements. 34 | FREQUENCY_SECONDS = 30 35 | 36 | 37 | def login_open_sheet(oauth_key_file, spreadsheet): 38 | """Connect to Google Docs spreadsheet and return the first worksheet.""" 39 | try: 40 | json_key = json.load(open(oauth_key_file)) 41 | credentials = SignedJwtAssertionCredentials(json_key['client_email'], 42 | json_key['private_key'], 43 | ['https://spreadsheets.google.com/feeds']) 44 | gc = gspread.authorize(credentials) 45 | worksheet = gc.open(spreadsheet).sheet1 46 | return worksheet 47 | except Exception as ex: 48 | print 'Unable to login and get spreadsheet. Check OAuth credentials, spreadsheet name, and make sure spreadsheet is shared to the client_email address in the OAuth .json file!' 49 | print 'Google sheet login failed with error:', ex 50 | sys.exit(1) 51 | 52 | 53 | print 'Logging sensor measurements to {0} every {1} seconds.'.format(GDOCS_SPREADSHEET_NAME, FREQUENCY_SECONDS) 54 | print 'Press Ctrl-C to quit.' 55 | worksheet = None 56 | while True: 57 | # Login if necessary. 58 | if worksheet is None: 59 | worksheet = login_open_sheet(GDOCS_OAUTH_JSON, GDOCS_SPREADSHEET_NAME) 60 | 61 | # Attempt to get sensor reading. 62 | 63 | humidity, temperature1 = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302 , am2302Pin) 64 | sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES) 65 | pressure = sensor.read_pressure() 66 | altitude = sensor.read_altitude() 67 | slpressure = sensor.read_sealevel_pressure() 68 | temperature2 = sensor.read_temperature() 69 | temperature3 = ds18b20_read_temp() 70 | lux = luxrdr.readLux() 71 | avgTemp = ((temperature1 + temperature2 + temperature3) / 3) 72 | 73 | print 'Temp Sensor 1 = {0:0.1f} *C'.format(temperature1) 74 | print 'Humidity={0:0.1f}%'.format(humidity) 75 | print 'BMP180:' 76 | print 'Temp Sensor 2 = {0:0.2f} *C'.format(temperature2) 77 | print 'Pressure = {0:0.2f} Pa'.format(pressure) 78 | print 'Altitude = {0:0.2f} m'.format(altitude) 79 | print 'Sealevel Pressure = {0:0.2f} Pa'.format(slpressure) 80 | print 'Temp Sensor 3 = {0:0.3f} *C'.format(temperature3) 81 | print 'Lux: ' + str(lux) 82 | print "Average: " + str(avgTemp) 83 | 84 | # Append the data in the spreadsheet, including a timestamp 85 | try: 86 | worksheet.append_row((datetime.datetime.now(), altitude,humidity,lux,pressure,slpressure,temperature1,temperature2,temperature3,avgTemp)) 87 | except: 88 | # Error appending data, most likely because credentials are stale. 89 | # Null out the worksheet so a login is performed at the top of the loop. 90 | print 'Append error, logging in again' 91 | worksheet = None 92 | time.sleep(FREQUENCY_SECONDS) 93 | continue 94 | 95 | # Wait 30 seconds before continuing 96 | print 'Wrote a row to {0}'.format(GDOCS_SPREADSHEET_NAME) 97 | time.sleep(FREQUENCY_SECONDS) 98 | -------------------------------------------------------------------------------- /luxreader.py: -------------------------------------------------------------------------------- 1 | from Adafruit_I2C import Adafruit_I2C 2 | import time 3 | 4 | class TSL2561: 5 | 6 | i2c = None 7 | 8 | def __init__(self, address=0x39, debug=0, pause=0.8): 9 | self.i2c = Adafruit_I2C(address) 10 | self.address = address 11 | self.pause = pause 12 | self.debug = debug 13 | self.gain = 0 # no gain preselected 14 | self.i2c.write8(0x80, 0x03) # enable the device 15 | 16 | 17 | def setGain(self,gain=1): 18 | """ Set the gain """ 19 | if (gain != self.gain): 20 | if (gain==1): 21 | self.i2c.write8(0x81, 0x02) # set gain = 1X and timing = 402 mSec 22 | if (self.debug): 23 | print "Setting low gain" 24 | else: 25 | self.i2c.write8(0x81, 0x12) # set gain = 16X and timing = 402 mSec 26 | if (self.debug): 27 | print "Setting high gain" 28 | self.gain=gain; # safe gain for calculation 29 | time.sleep(self.pause) # pause for integration (self.pause must be bigger than integration time) 30 | 31 | 32 | def readWord(self, reg): 33 | """Reads a word from the I2C device""" 34 | try: 35 | wordval = self.i2c.readU16(reg) 36 | newval = self.i2c.reverseByteOrder(wordval) 37 | if (self.debug): 38 | print("I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, wordval & 0xFFFF, reg)) 39 | return newval 40 | except IOError: 41 | print("Error accessing 0x%02X: Check your I2C address" % self.address) 42 | return -1 43 | 44 | 45 | def readFull(self, reg=0x8C): 46 | """Reads visible+IR diode from the I2C device""" 47 | return self.readWord(reg); 48 | 49 | def readIR(self, reg=0x8E): 50 | """Reads IR only diode from the I2C device""" 51 | return self.readWord(reg); 52 | 53 | def readLux(self, gain = 0): 54 | """Grabs a lux reading either with autoranging (gain=0) or with a specified gain (1, 16)""" 55 | if (gain == 1 or gain == 16): 56 | self.setGain(gain) # low/highGain 57 | ambient = self.readFull() 58 | IR = self.readIR() 59 | elif (gain==0): # auto gain 60 | self.setGain(16) # first try highGain 61 | ambient = self.readFull() 62 | if (ambient < 65535): 63 | IR = self.readIR() 64 | if (ambient >= 65535 or IR >= 65535): # value(s) exeed(s) datarange 65 | self.setGain(1) # set lowGain 66 | ambient = self.readFull() 67 | IR = self.readIR() 68 | 69 | if (self.gain==1): 70 | ambient *= 16 # scale 1x to 16x 71 | IR *= 16 # scale 1x to 16x 72 | 73 | ratio = (IR / float(ambient)) # changed to make it run under python 2 74 | 75 | if (self.debug): 76 | print "IR Result", IR 77 | print "Ambient Result", ambient 78 | 79 | if ((ratio >= 0) & (ratio <= 0.52)): 80 | lux = (0.0315 * ambient) - (0.0593 * ambient * (ratio**1.4)) 81 | elif (ratio <= 0.65): 82 | lux = (0.0229 * ambient) - (0.0291 * IR) 83 | elif (ratio <= 0.80): 84 | lux = (0.0157 * ambient) - (0.018 * IR) 85 | elif (ratio <= 1.3): 86 | lux = (0.00338 * ambient) - (0.0026 * IR) 87 | elif (ratio > 1.3): 88 | lux = 0 89 | 90 | return lux 91 | -------------------------------------------------------------------------------- /mini.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeremyMorgan/Raspberry_Pi_Weather_Station/c62914ef26f19fda478467b989abeba9386179c3/mini.jpg -------------------------------------------------------------------------------- /readings.py: -------------------------------------------------------------------------------- 1 | __author__ = 'jeremymorgan' 2 | 3 | # libraries 4 | import sys 5 | import urllib2 6 | import json 7 | import Adafruit_DHT 8 | import Adafruit_BMP.BMP085 as BMP085 9 | 10 | # custom functions 11 | from ds18b20 import ds18b20_read_temp 12 | import luxreader 13 | 14 | # Instance of TSL2561 Class 15 | luxrdr = luxreader.TSL2561() 16 | 17 | # Config 18 | am2302Pin = 22 19 | 20 | # Check if this is a dry run 21 | if len(sys.argv) > 1: 22 | if(sys.argv[1] == 'dryrun'): 23 | dryrun = True 24 | else: 25 | dryrun = False 26 | 27 | # Start Output 28 | if dryrun: 29 | print 'Sensor Reading Dry Run' 30 | print '************************' 31 | 32 | # Select Sensors to Use 33 | useAM2302 = True 34 | useBMP180 = True 35 | useDS18B20 = True 36 | useTSL2561 = True 37 | 38 | ## AM2302 Humidity / Temp Sensor 39 | if useAM2302: 40 | humidity, temperature1 = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302 , am2302Pin) 41 | if (dryrun): 42 | print 'AM2302:' 43 | print 'Temp Sensor 1 = {0:0.1f} *C'.format(temperature1) 44 | print 'Humidity={0:0.1f}%'.format(humidity) + '\n' 45 | else: 46 | humidity,temperature1 = 0,0 47 | 48 | # BMP180 Barometric Pressure Sensor 49 | if useBMP180: 50 | #sensor = BMP085.BMP085() 51 | #sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRALOWPOWER) 52 | #sensor = BMP085.BMP085(mode=BMP085.BMP085_STANDARD) 53 | #sensor = BMP085.BMP085(mode=BMP085.BMP085_STANDARD) 54 | #sensor = BMP085.BMP085(mode=BMP085.BMP085_HIGHRES) 55 | sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES) 56 | 57 | pressure = sensor.read_pressure() 58 | altitude = sensor.read_altitude() 59 | slpressure = sensor.read_sealevel_pressure() 60 | temperature2 = sensor.read_temperature() 61 | 62 | if dryrun: 63 | print 'BMP180:' 64 | print 'Temp Sensor 2 = {0:0.2f} *C'.format(temperature2) 65 | print 'Pressure = {0:0.2f} Pa'.format(pressure) 66 | print 'Altitude = {0:0.2f} m'.format(altitude) 67 | print 'Sealevel Pressure = {0:0.2f} Pa'.format(slpressure) + '\n' 68 | else: 69 | sensor,pressure,altitude,slpressure,temperature2 = 0,0,0,0,0 70 | 71 | ## DS18B20 Waterproof Temperature Probe 72 | if useDS18B20: 73 | temperature3 = ds18b20_read_temp() 74 | if dryrun: 75 | print 'DS18B20:' 76 | print 'Temp Sensor 3 = {0:0.3f} *C'.format(temperature3) + '\n' 77 | 78 | else: 79 | temperature3 = 0 80 | 81 | ## TSL2561 Lux Sensor 82 | if useTSL2561: 83 | lux = luxrdr.readLux() # Auto 84 | #lux = luxrdr.readLux(1) # Low Gain 85 | #lux = luxrdr.readLux(16) # High Gain 86 | 87 | lux = luxrdr.readLux() 88 | 89 | if dryrun: 90 | print 'TSL2561:' 91 | print 'Lux: ' + str(lux) + '\n' 92 | else: 93 | lux = 0 94 | 95 | 96 | ## Get Average Temperature 97 | 98 | avgTemp = ((temperature1 + temperature2 + temperature3) / 3) 99 | tempList = [temperature1,temperature2,temperature3] 100 | highestTemp = max(tempList) 101 | lowestTemp = min(tempList) 102 | 103 | if dryrun: 104 | print "Highest: " + str(highestTemp) 105 | print "Lowest: " + str(lowestTemp) 106 | print "Average: " + str(avgTemp) 107 | print "Variance: " + str(highestTemp - lowestTemp) + '\n' 108 | print '************************\n' 109 | else: 110 | url = '[YOUR URL]' 111 | 112 | postdata = { 113 | 'Altitude': altitude, 114 | 'Humidity': humidity, 115 | 'Lux': lux, 116 | 'Pressure': pressure, 117 | 'SeaLevelPressure': slpressure, 118 | 'TempSensor1': temperature1, 119 | 'TempSensor2': temperature2, 120 | 'TempSensor3': temperature3, 121 | 'TempSensorAvg': avgTemp 122 | } 123 | 124 | req = urllib2.Request(url) 125 | req.add_header('Content-Type','application/json') 126 | data = json.dumps(postdata) 127 | 128 | response = urllib2.urlopen(req,data) 129 | -------------------------------------------------------------------------------- /sensortests/AM2302/AdafruitDHT.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Copyright (c) 2014 Adafruit Industries 3 | # Author: Tony DiCola 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 all 13 | # 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 THE 21 | # SOFTWARE. 22 | import sys 23 | 24 | import Adafruit_DHT 25 | 26 | 27 | # Parse command line parameters. 28 | sensor_args = { '11': Adafruit_DHT.DHT11, 29 | '22': Adafruit_DHT.DHT22, 30 | '2302': Adafruit_DHT.AM2302 } 31 | if len(sys.argv) == 3 and sys.argv[1] in sensor_args: 32 | sensor = sensor_args[sys.argv[1]] 33 | pin = sys.argv[2] 34 | else: 35 | print 'usage: sudo ./Adafruit_DHT.py [11|22|2302] GPIOpin#' 36 | print 'example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO #4' 37 | sys.exit(1) 38 | 39 | # Try to grab a sensor reading. Use the read_retry method which will retry up 40 | # to 15 times to get a sensor reading (waiting 2 seconds between each retry). 41 | humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) 42 | 43 | # Un-comment the line below to convert the temperature to Fahrenheit. 44 | # temperature = temperature * 9/5.0 + 32 45 | 46 | # Note that sometimes you won't get a reading and 47 | # the results will be null (because Linux can't 48 | # guarantee the timing of calls to read the sensor). 49 | # If this happens try again! 50 | if humidity is not None and temperature is not None: 51 | print 'Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity) 52 | else: 53 | print 'Failed to get reading. Try again!' 54 | sys.exit(1) 55 | -------------------------------------------------------------------------------- /sensortests/AM2302/google_spreadsheet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | # Google Spreadsheet DHT Sensor Data-logging Example 4 | 5 | # Depends on the 'gspread' and 'oauth2client' package being installed. If you 6 | # have pip installed execute: 7 | # sudo pip install gspread oauth2client 8 | 9 | # Also it's _very important_ on the Raspberry Pi to install the python-openssl 10 | # package because the version of Python is a bit old and can fail with Google's 11 | # new OAuth2 based authentication. Run the following command to install the 12 | # the package: 13 | # sudo apt-get update 14 | # sudo apt-get install python-openssl 15 | 16 | # Copyright (c) 2014 Adafruit Industries 17 | # Author: Tony DiCola 18 | 19 | # Permission is hereby granted, free of charge, to any person obtaining a copy 20 | # of this software and associated documentation files (the "Software"), to deal 21 | # in the Software without restriction, including without limitation the rights 22 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 23 | # copies of the Software, and to permit persons to whom the Software is 24 | # furnished to do so, subject to the following conditions: 25 | 26 | # The above copyright notice and this permission notice shall be included in all 27 | # copies or substantial portions of the Software. 28 | 29 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 30 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 31 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 32 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 33 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 34 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 35 | # SOFTWARE. 36 | import json 37 | import sys 38 | import time 39 | import datetime 40 | 41 | import Adafruit_DHT 42 | import gspread 43 | from oauth2client.client import SignedJwtAssertionCredentials 44 | 45 | # Type of sensor, can be Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302. 46 | DHT_TYPE = Adafruit_DHT.DHT22 47 | 48 | # Example of sensor connected to Raspberry Pi pin 23 49 | DHT_PIN = 23 50 | # Example of sensor connected to Beaglebone Black pin P8_11 51 | #DHT_PIN = 'P8_11' 52 | 53 | # Google Docs OAuth credential JSON file. Note that the process for authenticating 54 | # with Google docs has changed as of ~April 2015. You _must_ use OAuth2 to log 55 | # in and authenticate with the gspread library. Unfortunately this process is much 56 | # more complicated than the old process. You _must_ carefully follow the steps on 57 | # this page to create a new OAuth service in your Google developer console: 58 | # http://gspread.readthedocs.org/en/latest/oauth2.html 59 | # 60 | # Once you've followed the steps above you should have downloaded a .json file with 61 | # your OAuth2 credentials. This file has a name like SpreadsheetData-.json. 62 | # Place that file in the same directory as this python script. 63 | # 64 | # Now one last _very important_ step before updating the spreadsheet will work. 65 | # Go to your spreadsheet in Google Spreadsheet and share it to the email address 66 | # inside the 'client_email' setting in the SpreadsheetData-*.json file. For example 67 | # if the client_email setting inside the .json file has an email address like: 68 | # 149345334675-md0qff5f0kib41meu20f7d1habos3qcu@developer.gserviceaccount.com 69 | # Then use the File -> Share... command in the spreadsheet to share it with read 70 | # and write acess to the email address above. If you don't do this step then the 71 | # updates to the sheet will fail! 72 | GDOCS_OAUTH_JSON = 'your SpreadsheetData-*.json file name' 73 | 74 | # Google Docs spreadsheet name. 75 | GDOCS_SPREADSHEET_NAME = 'your google docs spreadsheet name' 76 | 77 | # How long to wait (in seconds) between measurements. 78 | FREQUENCY_SECONDS = 30 79 | 80 | 81 | def login_open_sheet(oauth_key_file, spreadsheet): 82 | """Connect to Google Docs spreadsheet and return the first worksheet.""" 83 | try: 84 | json_key = json.load(open(oauth_key_file)) 85 | credentials = SignedJwtAssertionCredentials(json_key['client_email'], 86 | json_key['private_key'], 87 | ['https://spreadsheets.google.com/feeds']) 88 | gc = gspread.authorize(credentials) 89 | worksheet = gc.open(spreadsheet).sheet1 90 | return worksheet 91 | except Exception as ex: 92 | print 'Unable to login and get spreadsheet. Check OAuth credentials, spreadsheet name, and make sure spreadsheet is shared to the client_email address in the OAuth .json file!' 93 | print 'Google sheet login failed with error:', ex 94 | sys.exit(1) 95 | 96 | 97 | print 'Logging sensor measurements to {0} every {1} seconds.'.format(GDOCS_SPREADSHEET_NAME, FREQUENCY_SECONDS) 98 | print 'Press Ctrl-C to quit.' 99 | worksheet = None 100 | while True: 101 | # Login if necessary. 102 | if worksheet is None: 103 | worksheet = login_open_sheet(GDOCS_OAUTH_JSON, GDOCS_SPREADSHEET_NAME) 104 | 105 | # Attempt to get sensor reading. 106 | humidity, temp = Adafruit_DHT.read(DHT_TYPE, DHT_PIN) 107 | 108 | # Skip to the next reading if a valid measurement couldn't be taken. 109 | # This might happen if the CPU is under a lot of load and the sensor 110 | # can't be reliably read (timing is critical to read the sensor). 111 | if humidity is None or temp is None: 112 | time.sleep(2) 113 | continue 114 | 115 | print 'Temperature: {0:0.1f} C'.format(temp) 116 | print 'Humidity: {0:0.1f} %'.format(humidity) 117 | 118 | # Append the data in the spreadsheet, including a timestamp 119 | try: 120 | worksheet.append_row((datetime.datetime.now(), temp, humidity)) 121 | except: 122 | # Error appending data, most likely because credentials are stale. 123 | # Null out the worksheet so a login is performed at the top of the loop. 124 | print 'Append error, logging in again' 125 | worksheet = None 126 | time.sleep(FREQUENCY_SECONDS) 127 | continue 128 | 129 | # Wait 30 seconds before continuing 130 | print 'Wrote a row to {0}'.format(GDOCS_SPREADSHEET_NAME) 131 | time.sleep(FREQUENCY_SECONDS) 132 | -------------------------------------------------------------------------------- /sensortests/AM2302/simpletest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | # Copyright (c) 2014 Adafruit Industries 4 | # Author: Tony DiCola 5 | 6 | # Permission is hereby granted, free of charge, to any person obtaining a copy 7 | # of this software and associated documentation files (the "Software"), to deal 8 | # in the Software without restriction, including without limitation the rights 9 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | # copies of the Software, and to permit persons to whom the Software is 11 | # furnished to do so, subject to the following conditions: 12 | 13 | # The above copyright notice and this permission notice shall be included in all 14 | # copies or substantial portions of the Software. 15 | 16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | # SOFTWARE. 23 | import Adafruit_DHT 24 | 25 | # Sensor should be set to Adafruit_DHT.DHT11, 26 | # Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302. 27 | sensor = Adafruit_DHT.DHT22 28 | 29 | # Example using a Beaglebone Black with DHT sensor 30 | # connected to pin P8_11. 31 | pin = 'P8_11' 32 | 33 | # Example using a Raspberry Pi with DHT sensor 34 | # connected to GPIO23. 35 | #pin = 23 36 | 37 | # Try to grab a sensor reading. Use the read_retry method which will retry up 38 | # to 15 times to get a sensor reading (waiting 2 seconds between each retry). 39 | humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) 40 | 41 | # Note that sometimes you won't get a reading and 42 | # the results will be null (because Linux can't 43 | # guarantee the timing of calls to read the sensor). 44 | # If this happens try again! 45 | if humidity is not None and temperature is not None: 46 | print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity) 47 | else: 48 | print 'Failed to get reading. Try again!' 49 | -------------------------------------------------------------------------------- /sensortests/AM2302/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | sudo python AdafruitDHT.py 2302 22 3 | -------------------------------------------------------------------------------- /sensortests/BMP180/simpletest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Copyright (c) 2014 Adafruit Industries 3 | # Author: Tony DiCola 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 | # Can enable debug output by uncommenting: 24 | #import logging 25 | #logging.basicConfig(level=logging.DEBUG) 26 | 27 | import Adafruit_BMP.BMP085 as BMP085 28 | 29 | # Default constructor will pick a default I2C bus. 30 | # 31 | # For the Raspberry Pi this means you should hook up to the only exposed I2C bus 32 | # from the main GPIO header and the library will figure out the bus number based 33 | # on the Pi's revision. 34 | # 35 | # For the Beaglebone Black the library will assume bus 1 by default, which is 36 | # exposed with SCL = P9_19 and SDA = P9_20. 37 | sensor = BMP085.BMP085() 38 | 39 | # Optionally you can override the bus number: 40 | #sensor = BMP085.BMP085(busnum=2) 41 | 42 | # You can also optionally change the BMP085 mode to one of BMP085_ULTRALOWPOWER, 43 | # BMP085_STANDARD, BMP085_HIGHRES, or BMP085_ULTRAHIGHRES. See the BMP085 44 | # datasheet for more details on the meanings of each mode (accuracy and power 45 | # consumption are primarily the differences). The default mode is STANDARD. 46 | #sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES) 47 | 48 | print 'Temp = {0:0.2f} *C'.format(sensor.read_temperature()) 49 | print 'Pressure = {0:0.2f} Pa'.format(sensor.read_pressure()) 50 | print 'Altitude = {0:0.2f} m'.format(sensor.read_altitude()) 51 | print 'Sealevel Pressure = {0:0.2f} Pa'.format(sensor.read_sealevel_pressure()) 52 | -------------------------------------------------------------------------------- /sensortests/DS18B20/check.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | cd /sys/bus/w1/devices 4 | ls 5 | echo "cat w1_slave" 6 | 7 | -------------------------------------------------------------------------------- /sensortests/DS18B20/test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import glob 3 | import time 4 | 5 | os.system('modprobe w1-gpio') 6 | os.system('modprobe w1-therm') 7 | 8 | base_dir = '/sys/bus/w1/devices/' 9 | device_folder = glob.glob(base_dir + '28*')[0] 10 | device_file = device_folder + '/w1_slave' 11 | 12 | def read_temp_raw(): 13 | f = open(device_file, 'r') 14 | lines = f.readlines() 15 | f.close() 16 | return lines 17 | 18 | def read_temp(): 19 | lines = read_temp_raw() 20 | while lines[0].strip()[-3:] != 'YES': 21 | time.sleep(0.2) 22 | lines = read_temp_raw() 23 | equals_pos = lines[1].find('t=') 24 | if equals_pos != -1: 25 | temp_string = lines[1][equals_pos+2:] 26 | temp_c = float(temp_string) / 1000.0 27 | temp_f = temp_c * 9.0 / 5.0 + 32.0 28 | return temp_c, temp_f 29 | 30 | while True: 31 | print(read_temp()) 32 | time.sleep(1) 33 | 34 | -------------------------------------------------------------------------------- /sensortests/TSL2561/Adafruit_I2C.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import re 3 | import smbus 4 | 5 | # =========================================================================== 6 | # Adafruit_I2C Class 7 | # =========================================================================== 8 | 9 | class Adafruit_I2C(object): 10 | 11 | @staticmethod 12 | def getPiRevision(): 13 | "Gets the version number of the Raspberry Pi board" 14 | # Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History 15 | try: 16 | with open('/proc/cpuinfo', 'r') as infile: 17 | for line in infile: 18 | # Match a line of the form "Revision : 0002" while ignoring extra 19 | # info in front of the revsion (like 1000 when the Pi was over-volted). 20 | match = re.match('Revision\s+:\s+.*(\w{4})$', line) 21 | if match and match.group(1) in ['0000', '0002', '0003']: 22 | # Return revision 1 if revision ends with 0000, 0002 or 0003. 23 | return 1 24 | elif match: 25 | # Assume revision 2 if revision ends with any other 4 chars. 26 | return 2 27 | # Couldn't find the revision, assume revision 0 like older code for compatibility. 28 | return 0 29 | except: 30 | return 0 31 | 32 | @staticmethod 33 | def getPiI2CBusNumber(): 34 | # Gets the I2C bus number /dev/i2c# 35 | return 1 if Adafruit_I2C.getPiRevision() > 1 else 0 36 | 37 | def __init__(self, address, busnum=-1, debug=False): 38 | self.address = address 39 | # By default, the correct I2C bus is auto-detected using /proc/cpuinfo 40 | # Alternatively, you can hard-code the bus version below: 41 | # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's) 42 | # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's) 43 | self.bus = smbus.SMBus(busnum if busnum >= 0 else Adafruit_I2C.getPiI2CBusNumber()) 44 | self.debug = debug 45 | 46 | def reverseByteOrder(self, data): 47 | "Reverses the byte order of an int (16-bit) or long (32-bit) value" 48 | # Courtesy Vishal Sapre 49 | byteCount = len(hex(data)[2:].replace('L','')[::2]) 50 | val = 0 51 | for i in range(byteCount): 52 | val = (val << 8) | (data & 0xff) 53 | data >>= 8 54 | return val 55 | 56 | def errMsg(self): 57 | print "Error accessing 0x%02X: Check your I2C address" % self.address 58 | return -1 59 | 60 | def write8(self, reg, value): 61 | "Writes an 8-bit value to the specified register/address" 62 | try: 63 | self.bus.write_byte_data(self.address, reg, value) 64 | if self.debug: 65 | print "I2C: Wrote 0x%02X to register 0x%02X" % (value, reg) 66 | except IOError, err: 67 | return self.errMsg() 68 | 69 | def write16(self, reg, value): 70 | "Writes a 16-bit value to the specified register/address pair" 71 | try: 72 | self.bus.write_word_data(self.address, reg, value) 73 | if self.debug: 74 | print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" % 75 | (value, reg, reg+1)) 76 | except IOError, err: 77 | return self.errMsg() 78 | 79 | def writeRaw8(self, value): 80 | "Writes an 8-bit value on the bus" 81 | try: 82 | self.bus.write_byte(self.address, value) 83 | if self.debug: 84 | print "I2C: Wrote 0x%02X" % value 85 | except IOError, err: 86 | return self.errMsg() 87 | 88 | def writeList(self, reg, list): 89 | "Writes an array of bytes using I2C format" 90 | try: 91 | if self.debug: 92 | print "I2C: Writing list to register 0x%02X:" % reg 93 | print list 94 | self.bus.write_i2c_block_data(self.address, reg, list) 95 | except IOError, err: 96 | return self.errMsg() 97 | 98 | def readList(self, reg, length): 99 | "Read a list of bytes from the I2C device" 100 | try: 101 | results = self.bus.read_i2c_block_data(self.address, reg, length) 102 | if self.debug: 103 | print ("I2C: Device 0x%02X returned the following from reg 0x%02X" % 104 | (self.address, reg)) 105 | print results 106 | return results 107 | except IOError, err: 108 | return self.errMsg() 109 | 110 | def readU8(self, reg): 111 | "Read an unsigned byte from the I2C device" 112 | try: 113 | result = self.bus.read_byte_data(self.address, reg) 114 | if self.debug: 115 | print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % 116 | (self.address, result & 0xFF, reg)) 117 | return result 118 | except IOError, err: 119 | return self.errMsg() 120 | 121 | def readS8(self, reg): 122 | "Reads a signed byte from the I2C device" 123 | try: 124 | result = self.bus.read_byte_data(self.address, reg) 125 | if result > 127: result -= 256 126 | if self.debug: 127 | print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % 128 | (self.address, result & 0xFF, reg)) 129 | return result 130 | except IOError, err: 131 | return self.errMsg() 132 | 133 | def readU16(self, reg, little_endian=True): 134 | "Reads an unsigned 16-bit value from the I2C device" 135 | try: 136 | result = self.bus.read_word_data(self.address,reg) 137 | # Swap bytes if using big endian because read_word_data assumes little 138 | # endian on ARM (little endian) systems. 139 | if not little_endian: 140 | result = ((result << 8) & 0xFF00) + (result >> 8) 141 | if (self.debug): 142 | print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) 143 | return result 144 | except IOError, err: 145 | return self.errMsg() 146 | 147 | def readS16(self, reg, little_endian=True): 148 | "Reads a signed 16-bit value from the I2C device" 149 | try: 150 | result = self.readU16(reg,little_endian) 151 | if result > 32767: result -= 65536 152 | return result 153 | except IOError, err: 154 | return self.errMsg() 155 | 156 | if __name__ == '__main__': 157 | try: 158 | bus = Adafruit_I2C(address=0) 159 | print "Default I2C bus is accessible" 160 | except: 161 | print "Error accessing default I2C bus" 162 | -------------------------------------------------------------------------------- /sensortests/TSL2561/Adafruit_I2C.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JeremyMorgan/Raspberry_Pi_Weather_Station/c62914ef26f19fda478467b989abeba9386179c3/sensortests/TSL2561/Adafruit_I2C.pyc -------------------------------------------------------------------------------- /sensortests/TSL2561/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Code sourced from AdaFruit discussion board: https://www.adafruit.com/forums/viewtopic.php?f=8&t=34922 3 | 4 | 5 | import sys 6 | # Not needed here. Thanks to https://github.com/mackstann for highlighting this. 7 | #import smbus 8 | import time 9 | #Adafruit_I2C from https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/blob/master/Adafruit_I2C/Adafruit_I2C.py 10 | from Adafruit_I2C import Adafruit_I2C 11 | 12 | 13 | ### Written for Python 2 <-!!! 14 | ### Big thanks to bryand, who wrote the code that I borrowed heavily from/was inspired by 15 | ### More thanks pandring who kind of kickstarted my work on the TSL2561 sensor 16 | ### A great big huge thanks to driverblock and the Adafruit team (Congrats on your many succeses 17 | ### Ladyada). Without you folks I would just be a guy sitting somewhere thinking about cool stuff 18 | ### Now I'm a guy building cool stuff. 19 | ### If any of this code proves useful, drop me a line at medicforlife.blogspot.com 20 | 21 | # TODO: Strip out values into constants. 22 | 23 | class TSL2561: 24 | i2c = None 25 | 26 | def __init__(self, address=0x39, debug=0, pause=0.8): 27 | self.i2c = Adafruit_I2C(address) 28 | self.address = address 29 | self.pause = pause 30 | self.debug = debug 31 | self.gain = 0 # no gain preselected 32 | self.i2c.write8(0x80, 0x03) # enable the device 33 | 34 | 35 | def setGain(self,gain=1): 36 | """ Set the gain """ 37 | if (gain != self.gain): 38 | if (gain==1): 39 | self.i2c.write8(0x81, 0x02) # set gain = 1X and timing = 402 mSec 40 | if (self.debug): 41 | print "Setting low gain" 42 | else: 43 | self.i2c.write8(0x81, 0x12) # set gain = 16X and timing = 402 mSec 44 | if (self.debug): 45 | print "Setting high gain" 46 | self.gain=gain; # safe gain for calculation 47 | time.sleep(self.pause) # pause for integration (self.pause must be bigger than integration time) 48 | 49 | 50 | def readWord(self, reg): 51 | """Reads a word from the I2C device""" 52 | try: 53 | wordval = self.i2c.readU16(reg) 54 | newval = self.i2c.reverseByteOrder(wordval) 55 | if (self.debug): 56 | print("I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, wordval & 0xFFFF, reg)) 57 | return newval 58 | except IOError: 59 | print("Error accessing 0x%02X: Check your I2C address" % self.address) 60 | return -1 61 | 62 | 63 | def readFull(self, reg=0x8C): 64 | """Reads visible+IR diode from the I2C device""" 65 | return self.readWord(reg); 66 | 67 | def readIR(self, reg=0x8E): 68 | """Reads IR only diode from the I2C device""" 69 | return self.readWord(reg); 70 | 71 | def readLux(self, gain = 0): 72 | """Grabs a lux reading either with autoranging (gain=0) or with a specified gain (1, 16)""" 73 | if (gain == 1 or gain == 16): 74 | self.setGain(gain) # low/highGain 75 | ambient = self.readFull() 76 | IR = self.readIR() 77 | elif (gain==0): # auto gain 78 | self.setGain(16) # first try highGain 79 | ambient = self.readFull() 80 | if (ambient < 65535): 81 | IR = self.readIR() 82 | if (ambient >= 65535 or IR >= 65535): # value(s) exeed(s) datarange 83 | self.setGain(1) # set lowGain 84 | ambient = self.readFull() 85 | IR = self.readIR() 86 | 87 | if (self.gain==1): 88 | ambient *= 16 # scale 1x to 16x 89 | IR *= 16 # scale 1x to 16x 90 | 91 | ratio = (IR / float(ambient)) # changed to make it run under python 2 92 | 93 | if (self.debug): 94 | print "IR Result", IR 95 | print "Ambient Result", ambient 96 | 97 | if ((ratio >= 0) & (ratio <= 0.52)): 98 | lux = (0.0315 * ambient) - (0.0593 * ambient * (ratio**1.4)) 99 | elif (ratio <= 0.65): 100 | lux = (0.0229 * ambient) - (0.0291 * IR) 101 | elif (ratio <= 0.80): 102 | lux = (0.0157 * ambient) - (0.018 * IR) 103 | elif (ratio <= 1.3): 104 | lux = (0.00338 * ambient) - (0.0026 * IR) 105 | elif (ratio > 1.3): 106 | lux = 0 107 | 108 | return lux 109 | 110 | if __name__ == "__main__": 111 | tsl=TSL2561() 112 | print tsl.readLux() 113 | #print "LUX HIGH GAIN ", tsl.readLux(16) 114 | #print "LUX LOW GAIN ", tsl.readLux(1) 115 | #print "LUX AUTO GAIN ", tsl.readLux() 116 | -------------------------------------------------------------------------------- /texty/ds18b20.py: -------------------------------------------------------------------------------- 1 | import time 2 | import glob 3 | 4 | base_dir = '/sys/bus/w1/devices/' 5 | device_folder = glob.glob(base_dir + '28*')[0] 6 | device_file = device_folder + '/w1_slave' 7 | 8 | def ds18b20_read_temp_raw(): 9 | f = open(device_file, 'r') 10 | lines = f.readlines() 11 | f.close() 12 | return lines 13 | 14 | def ds18b20_read_temp(): 15 | lines = ds18b20_read_temp_raw() 16 | while lines[0].strip()[-3:] != 'YES': 17 | time.sleep(0.2) 18 | lines = ds18b20_read_temp_raw() 19 | equals_pos = lines[1].find('t=') 20 | if equals_pos != -1: 21 | temp_string = lines[1][equals_pos+2:] 22 | temp_c = float(temp_string) / 1000.0 23 | temp_f = temp_c * 9.0 / 5.0 + 32.0 24 | return temp_c -------------------------------------------------------------------------------- /texty/texty.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | from ds18b20 import ds18b20_read_temp 4 | from twilio.rest import TwilioRestClient 5 | 6 | ACCOUNT_SID = "YOUR SID" 7 | AUTH_TOKEN = "YOUR KEY" 8 | 9 | threshold = 79 10 | 11 | sent = False 12 | 13 | while True: 14 | temp = 9.0/5.0 * ds18b20_read_temp() + 32 15 | 16 | print(temp) 17 | if ((temp > threshold) & (sent == False)): 18 | client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) 19 | client.messages.create( 20 | to="YOUR PHONE", 21 | from_="YOUR TWILIO PHONE", 22 | body="Temperature is above the threshold at " + str(temp), 23 | ) 24 | sent = True 25 | 26 | time.sleep(1) 27 | 28 | GPIO.cleanup() 29 | 30 | --------------------------------------------------------------------------------