Skip to content

Encoder: fix sysfs import, make code Python 3 compatible #210

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
393 changes: 220 additions & 173 deletions Adafruit_BBIO/Encoder.py

Large diffs are not rendered by default.

79 changes: 52 additions & 27 deletions Adafruit_BBIO/README.md
Original file line number Diff line number Diff line change
@@ -1,52 +1,72 @@
# Adafruit_BBIO.Encoder module
# Adafruit_BBIO.Encoder

This module enables access to the Beaglebone Black enhanced Quadrature Encoder Pulse (eQEP) modules: eQEP0, eQEP1 and eQEP2.
This module enables access to the Beaglebone Black enhanced Quadrature Encoder Pulse (eQEP) modules: eQEP0, eQEP1 and eQEP2/eQEP2b.

Initially based on the [PyBBIO](https://github.com/graycatlabs/PyBBIO/bbio/libraries/RotaryEncoder/rotary_encoder.py) rotary encoder code.
## Usage

## Prerequisites
On a recent Beaglebone Debian image, access to the eQEP0 and eQEP2 channels should work out of the box:

These instructions are based on a 4.4.x Linux kernel.
```python
import Adafruit_BBIO.Encoder as Encoder

In order to use all eQEP pins the BeagleBone must boot with the [cape-universal](https://github.com/beagleboard/bb.org-overlays/tree/master/tools/beaglebone-universal-io) enabled, and load the cape-universal overlay
'''
Each channel can be accessed and initialized using its corresponding
channel name constants:

```
enable_uboot_cape_universal=1
Encoder.eQEP0
Encoder.eQEP1 # Pins only available when video is disabled
Encoder.eQEP2
Encoder.eQEP2b # Pins only available when video is disabled
'''

# Instantiate the class to access channel eQEP2, and only initialize
# that channel
myEncoder = Encoder.RotaryEncoder(Encoder.eQEP2)
```

Notes:
- It seems that the `cape-universal` cape _does only enable access to eQEP0 and eQEP2_. TBD: check how to load [`cape-universala`](https://github.com/cdsteinkuehler/beaglebone-universal-io/pull/30)
- An alternative option to the `cape-universal` overlay would be to load one of the [dedicated eQEP overlays](https://github.com/Teknoman117/beaglebot/tree/master/encoders/dts).
If you need to use further channels, read on the prerequisites in the following section.

### Install/upgrade the latest Device Tree overlays
## Prerequisites

These instructions are based on:

- Linux kernel: 4.4.x or later
- `bb-cape-overlays` package: version 4.4.20171120.0-0rcnee1~stretch+20171120 or later
- `bb-customizations` package: version 1.20171123-0rcnee0~stretch+20171123 or later

It's recommended to run the following commands to ensure you have the latest required packages:

```
sudo apt-get upgrade bb-cape-overlays
sudo apt update
sudo apt upgrade bb-cape-overlays bb-customizations
```

### Load the universal cape
In order to use all eQEP pins the BeagleBone must boot with the [cape-universal](https://github.com/beagleboard/bb.org-overlays/tree/master/tools/beaglebone-universal-io) enabled, and load the `cape-universal` overlay.

If it doesn't already contain it, modify the `/boot/uEnv.txt` file to contain this line:
This is the default, thus **no further steps are initially required to use eQEP0 and eQEP2**. Simply double-check that the following line is present and not commented out on your `/boot/uEnv.txt` file:

```
enable_uboot_cape_universal=1
```

Notes:
Note: Some older documentation recommends using the `cmdline` and `cape_enable` options instead. They are meant to load deprecated kernel-based overlays and it's not recommended to use them. Use the new way of [loading overlays via uboot](https://elinux.org/Beagleboard:BeagleBoneBlack_Debian#U-Boot_Overlays) instead, as instructed above.

- Some older documentation recommends using these two lines instead. They are meant to load deprecated kernel-based overlays and it's not recommended to use them. Use the new way of [loading overlays via uboot](https://elinux.org/Beagleboard:BeagleBoneBlack_Debian#U-Boot_Overlays) instead, as instructed above.
### Enabling additional eQEP modules

```
cmdline=cape_universal=enable # Plus some other options
```
```
cape_enable=bone_capemgr.enable_partno=cape-universala
```
- TBD: check the overlays that are currently loaded
The `cape-universal` overlay will enable access to the eQEP0 and eQEP2 modules. As it does not expose pins that are shared with the HDMI interface, eQEP1 and eQEP2b will **not** be available.

To disable the HDMI interface and gain access to the pins and peripherals that share its pins, comment out the following line on the `/boot/uEnv.txt` file and reboot:

```
disable_uboot_overlay_video=1
```

## eQEP configuraton

Note: if either eQEP1 or eQEP2b are used on the Beaglebone Black, video must be disabled, as their pins are shared with the LCD_DATAx lines of the HDMI interface.
Notes:

- If either eQEP1 or eQEP2b are used on the Beaglebone Black, video must be disabled, as their pins are shared with the LCD_DATAx lines of the HDMI interface.
- eQEP2 and eQEP2b are the same module, but with the alternative of accessing it via two sets of pins. These are mutually exclusive.

### eQEP0

Expand Down Expand Up @@ -91,7 +111,12 @@ $ config-pin P8.41 qep
$ config-pin P8.42 qep
$ cat /sys/devices/platform/ocp/48304000.epwmss/48304180.eqep/position
```

## Credits

Initially based on the [PyBBIO](https://github.com/graycatlabs/PyBBIO/bbio/libraries/RotaryEncoder/rotary_encoder.py) rotary encoder code.

## Further reading

- [Beaglebone encoder inputs](https://github.com/Teknoman117/beaglebot/tree/master/encoders)
- [Beaglebone eQEP overlays](https://github.com/Teknoman117/beaglebot/tree/master/encoders/dts)
1. [Beaglebone encoder inputs](https://github.com/Teknoman117/beaglebot/tree/master/encoders)
1. [Beaglebone eQEP overlays](https://github.com/Teknoman117/beaglebot/tree/master/encoders/dts)
118 changes: 118 additions & 0 deletions Adafruit_BBIO/sysfs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (c) 2014 MIT OpenCourseWare
# Copyright (c) 2017 Adafruit Industries
#
# 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.
#
# Code originally published at http://stackoverflow.com/questions/4648792/ and
# subsequently forked at https://github.com/ponycloud/python-sysfs
#
# Original author: Benedikt Reinartz <filmor@gmail.com>
# Contributors:
# - Jan Dvořák <mordae@anilinux.org>
# - Jonathon Reinhart https://github.com/JonathonReinhart
# - Ondřej Koch <o.koch@zerusnet.com>
# - David Planella <david.planella@ubuntu.com>

"""
Simplistic Python SysFS interface. It enables access to the sys filesystem device
nodes and to get and set their exposed attributes.

Usage examples::
from sysfs import sys

# Print all block devices in /sys, with their sizes
for block_dev in sys.block:
print block_dev, str(int(block_dev.size) / 1048576) + ' M'

>>> import sysfs
>>> # Read/write Beaglebone Black's eQEP module attributes
>>> eqep0 = sysfs.Node("/sys/devices/platform/ocp/48300000.epwmss/48300180.eqep")
>>> # Read eqep attributes
>>> eqep0.enabled
'1'
>>> eqep0.mode
'0'
>>> eqep0.period
'1000000000'
>>> eqep0.position
'0'
>>> # Write eqep attributes. They should be strings.
>>> eqep0.position = str(2)
>>> eqep0.position
'2'
"""

from os import listdir
from os.path import isdir, isfile, join, realpath, basename

__all__ = ['sys', 'Node']


class Node(object):
__slots__ = ['_path_', '__dict__']

def __init__(self, path='/sys'):
self._path_ = realpath(path)
if not self._path_.startswith('/sys/') and not '/sys' == self._path_:
raise RuntimeError('Using this on non-sysfs files is dangerous!')

self.__dict__.update(dict.fromkeys(listdir(self._path_)))

def __repr__(self):
return '<sysfs.Node "%s">' % self._path_

def __str__(self):
return basename(self._path_)

def __setattr__(self, name, val):
if name.startswith('_'):
return object.__setattr__(self, name, val)

path = realpath(join(self._path_, name))
if isfile(path):
with open(path, 'w') as fp:
fp.write(val)
else:
raise RuntimeError('Cannot write to non-files.')

def __getattribute__(self, name):
if name.startswith('_'):
return object.__getattribute__(self, name)

path = realpath(join(self._path_, name))
if isfile(path):
with open(path, 'r') as fp:
return fp.read().strip()
elif isdir(path):
return Node(path)

def __setitem__(self, name, val):
return setattr(self, name, val)

def __getitem__(self, name):
return getattr(self, name)

def __iter__(self):
return iter(getattr(self, name) for name in listdir(self._path_))


sys = Node()
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,22 @@ sudo pip install --upgrade Adafruit_BBIO

Using the library is very similar to the excellent RPi.GPIO library used on the Raspberry Pi. Below are some examples.

### Pin Numbers

Please note that there is no '0' prefix for the pin numbers. For example, pin 7 on header P8 is `P8_7`.

**Correct:**
```
GPIO.setup("P8_7", OUT )
```

**INCORRECT:**
```
GPIO.setup("P8_07", OUT )
```

Refer to `pins_t table[]` in [common.c](https://github.com/adafruit/adafruit-beaglebone-io-python/blob/master/source/common.c#L73) all the pin labels.

### config-pin

[config-pin](https://github.com/beagleboard/bb.org-overlays/tree/master/tools/beaglebone-universal-io) is now used on the official BeagleBoard.org Debian Jessie and Stretch images to control pin mode (e.g. pin mux).
Expand Down
9 changes: 9 additions & 0 deletions install_all_python_versions.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash
# useful for testing changes against all versions of python
make clean
echo "Install Python 2.7"
python2.7 ./setup.py install
echo "Install Python 3.5"
python3.5 ./setup.py install
echo "Install Python 3.6"
python3.6 ./setup.py install
11 changes: 11 additions & 0 deletions pytest_all_versions.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/bin/bash
# useful for testing changes against all versions of python

cd test
echo "Testing Python 2.7"
python2.7 -mpytest
echo "Testing Python 3.5"
python3.5 -mpytest
echo "Testing Python 3.6"
python3.6 -mpytest
cd ..
4 changes: 2 additions & 2 deletions source/py_pwm.c
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,8 @@ static const char moduledocstring[] = "PWM functionality of a BeagleBone using P
PyMethodDef pwm_methods[] = {
{"start", (PyCFunction)py_start_channel, METH_VARARGS | METH_KEYWORDS, "Set up and start the PWM channel. channel can be in the form of 'P8_10', or 'EHRPWM2A'"},
{"stop", (PyCFunction)py_stop_channel, METH_VARARGS | METH_KEYWORDS, "Stop the PWM channel. channel can be in the form of 'P8_10', or 'EHRPWM2A'"},
{ "set_duty_cycle", (PyCFunction)py_set_duty_cycle, METH_VARARGS, "Change the duty cycle\ndutycycle - between 0.0 and 100.0" },
{ "set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" },
{ "set_duty_cycle", (PyCFunction)py_set_duty_cycle, METH_VARARGS | METH_KEYWORDS, "Change the duty cycle\ndutycycle - between 0.0 and 100.0" },
{ "set_frequency", (PyCFunction)py_set_frequency, METH_VARARGS | METH_KEYWORDS, "Change the frequency\nfrequency - frequency in Hz (freq > 0.0)" },
{"cleanup", py_cleanup, METH_VARARGS, "Clean up by resetting all GPIO channels that have been used by this program to INPUT with no pullup/pulldown and no event detection"},
//{"setwarnings", py_setwarnings, METH_VARARGS, "Enable or disable warning messages"},
{NULL, NULL, 0, NULL}
Expand Down
74 changes: 0 additions & 74 deletions test/test_rotary.py

This file was deleted.

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy