Commit 8373ed70 authored by Umut Karcı's avatar Umut Karcı
Browse files

Initial Commit

parent 01dea716
MIT License
Copyright (c) 2017 Umut Karcı
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# PCF8591 for Micropython
## Installation
It's actually very simple. Just import upip and install the package.
import upip
upip.install('micropython-pcf8591')
## Usage
The PCF8591 class has 4 main public methods available: set_out, set_program, read, write.
###PCF8591:
####\_\_init\_\_(i2c, addr=..., enable_out=..., in_program=...):
_Initializes the instance_
- **i2c** is a Micropython I2C instance
- **addr** is the address of the device, defaults to 72 (0x48).
- **enable_out** is for setting "ANALOG OUTPUT ENABLE FLAG". Also enables the internal oscillator which is a must for auto-increment. Valid options are: (`True`, `False`). Defaults to `True`.
- **in_program** is for settings "ANALOG INPUT PROGRAMMING". Valid options are: (`AINPRG0`, `AINPRG1`, `AINPRG2`, `AINPRG3`). Defaults to `AINPRG0`.
####set_out(enable_out):
_Sets the output flag_
- **enable_out** is for setting "ANALOG OUTPUT ENABLE FLAG". Also enables the internal oscillator which is a must for auto-increment. Valid options are: (`True`, `False`).
####set_program(in_program):
_Sets the input program_
- **in_program** is for settings "ANALOG INPUT PROGRAMMING". Valid options are: (`AINPRG0`, `AINPRG1`, `AINPRG2`, `AINPRG3`).
####read(channel=...):
_Reads analog data from the device. When auto incrementing is enabled, this function will return all four inputs as a list, otherwise returns a single integer._
- **channel** is for setting the "A/D CHANNEL NUMBER". When is None, auto incrementing will be enabled. Valid options are(`ACHNNL0`, `ACHNNL1`, `ACHNNL2`, `ACHNNL3`, `None`). Defaults to `None`.
####write(value):
_Writes analog data to the device. It'll automatically enable analog out._
- **value** is for setting the analog output value of the device. Valid options are: (`0-255`)
###Constants
- **AINPRG0**: ANALOG INPUT PROGRAM 0
- **AINPRG1**: ANALOG INPUT PROGRAM 1
- **AINPRG2**: ANALOG INPUT PROGRAM 2
- **AINPRG3**: ANALOG INPUT PROGRAM 3
- **ACHNNL0**: ANALOG CHANNEL 0
- **ACHNNL1**: ANALOG CHANNEL 1
- **ACHNNL2**: ANALOG CHANNEL 2
- **ACHNNL3**: ANALOG CHANNEL 3
## Development
As you can guess, there are no tests whatsoever, no coverage, nothing!
You can create a distribution package by running this command inside pcf8591 directory.
python setup.py sdist optimize_upip
\ No newline at end of file
###
# Copied from official micropython-lib git repository.
# Licensed with MIT.
# Copyright (c) 2013, 2014 micropython-lib contributors
###
#
# This script optimizes a Python source distribution tarball as produced by
# "python3 setup.py sdist" command for MicroPython's native package manager,
# upip. Optimization includes:
# * Removing metadata files not used by upip (this includes setup.py)
# * Recompressing gzip archive with 4K dictionary size so it can be
# installed even on low-heap targets.
#
import sys
import os
import zlib
from subprocess import Popen, PIPE
import glob
import tarfile
import re
import io
def gzip_4k(inf, fname):
comp = zlib.compressobj(level=9, wbits=16 + 12)
with open(fname + ".out", "wb") as outf:
while 1:
data = inf.read(1024)
if not data:
break
outf.write(comp.compress(data))
outf.write(comp.flush())
os.rename(fname, fname + ".orig")
os.rename(fname + ".out", fname)
def recompress(fname):
with Popen(["gzip", "-d", "-c", fname], stdout=PIPE).stdout as inf:
gzip_4k(inf, fname)
def find_latest(dir):
res = []
for fname in glob.glob(dir + "/*.gz"):
st = os.stat(fname)
res.append((st.st_mtime, fname))
res.sort()
latest = res[-1][1]
return latest
def recompress_latest(dir):
latest = find_latest(dir)
print(latest)
recompress(latest)
FILTERS = [
# include, exclude, repeat
(r".+\.egg-info/(PKG-INFO|requires\.txt)", r"setup.py$"),
(r".+\.py$", r"[^/]+$"),
(None, r".+\.egg-info/.+"),
]
outbuf = io.BytesIO()
def filter_tar(name):
fin = tarfile.open(name, "r:gz")
fout = tarfile.open(fileobj=outbuf, mode="w")
for info in fin:
# print(info)
if not "/" in info.name:
continue
fname = info.name.split("/", 1)[1]
include = None
for inc_re, exc_re in FILTERS:
if include is None and inc_re:
if re.match(inc_re, fname):
include = True
if include is None and exc_re:
if re.match(exc_re, fname):
include = False
if include is None:
include = True
if include:
print("Including:", fname)
else:
print("Excluding:", fname)
continue
farch = fin.extractfile(info)
fout.addfile(info, farch)
fout.close()
fin.close()
from setuptools import Command
class OptimizeUpip(Command):
user_options = []
def run(self):
latest = find_latest("dist")
filter_tar(latest)
outbuf.seek(0)
gzip_4k(outbuf, latest)
def initialize_options(self):
pass
def finalize_options(self):
pass
# For testing only
if __name__ == "__main__":
# recompress_latest(sys.argv[1])
filter_tar(sys.argv[1])
outbuf.seek(0)
gzip_4k(outbuf, sys.argv[1])
AOUTFLG = 0b01000000
AINPRG0 = 0b00000000
AINPRG1 = 0b00010000
AINPRG2 = 0b00100000
AINPRG3 = 0b00110000
AUTOINC = 0b00000100
ACHNNL0 = 0b00000000
ACHNNL1 = 0b00000001
ACHNNL2 = 0b00000010
ACHNNL3 = 0b00000011
class PCF8591:
def __init__(self, i2c, addr=0x48, enable_out=True, in_program=AINPRG0):
self.i2c = i2c
self.addr = addr
self._aout = self.set_out(enable_out)
self._ainprg = self.set_program(in_program)
self._last_ctl = self._make_control()
def _make_control(self, auto_increment=False, channel=ACHNNL0):
return 0 | self._aout | self._ainprg | (AUTOINC if auto_increment else 0) | channel
def _write_control(self, control):
if control != self._last_ctl:
self.i2c.writeto(self.addr, bytes([control]))
self.i2c.readfrom(self.addr, 1)
self._last_ctl = control
def _read_raw(self):
return self.i2c.readfrom(self.addr, 4)
def set_out(self, enable_out):
self._aout = AOUTFLG if enable_out else 0
return self._aout
def set_program(self, in_program):
self._ainprg = in_program
return self._ainprg
def read(self, channel=-1):
if channel == -1:
self.set_out(True)
self._write_control(self._make_control(auto_increment=True))
return self._read_raw()
else:
self._write_control(self._make_control(channel=channel))
return int(self._read_raw()[0])
def write(self, value):
self.set_out(True)
control = self._make_control()
self._last_ctl = control
self.i2c.writeto(self.addr, bytes([control, value]))
from setuptools import setup
import optimize_upip
setup(
name='micropython-pcf8591',
version='0.1',
description='A pcf8591 driver for micropython',
long_description='PCF8591 is a digital-analog and analog-digital converter that supports 4 analog inputs'
' and 1 analog output and a I2C interface. This driver is for MicroPython and microchips'
' that have a I2C interface.',
author='Umut Karcı',
author_email='cediddi@gmail.com',
license='MIT',
cmdclass={'optimize_upip': optimize_upip.OptimizeUpip},
py_modules=['pcf8591'],
url='https://gitlab.com/cediddi/micropython-pcf8591/'
)
  • hi sir plz mention some examples using esp8266 with micropython to acess pcf8591.py if no examples entry level programmers cant acess or understand without a examples

    thank you vijayakumar ks. viji2ks@gmail.com

Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment