code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
"""I2C Class for FTDI MPSSE"""
from adafruit_blinka.microcontroller.ftdi_mpsse.mpsse.pin import Pin
from adafruit_blinka.microcontroller.ftdi_mpsse.mpsse.url import (
get_ft232h_url,
get_ft2232h_url,
)
class I2C:
"""Custom I2C Class for FTDI MPSSE"""
MASTER = 0
SLAVE = 1
_mode = None
# pylint: disable=unused-argument
def __init__(self, i2c_id=None, mode=MASTER, baudrate=None, frequency=400000):
if mode != self.MASTER:
raise NotImplementedError("Only I2C Master supported!")
_mode = self.MASTER
# change GPIO controller to I2C
# pylint: disable=import-outside-toplevel
from pyftdi.i2c import I2cController
# pylint: enable=import-outside-toplevel
self._i2c = I2cController()
if i2c_id is None:
self._i2c.configure(get_ft232h_url(), frequency=frequency)
else:
self._i2c.configure(get_ft2232h_url(i2c_id), frequency=frequency)
Pin.mpsse_gpio = self._i2c.get_gpio()
def scan(self):
"""Perform an I2C Device Scan"""
return [addr for addr in range(0x79) if self._i2c.poll(addr)]
def writeto(self, address, buffer, *, start=0, end=None, stop=True):
"""Write data from the buffer to an address"""
end = end if end else len(buffer)
port = self._i2c.get_port(address)
port.write(buffer[start:end], relax=stop)
def readfrom_into(self, address, buffer, *, start=0, end=None, stop=True):
"""Read data from an address and into the buffer"""
end = end if end else len(buffer)
port = self._i2c.get_port(address)
result = port.read(len(buffer[start:end]), relax=stop)
for i, b in enumerate(result):
buffer[start + i] = b
# pylint: disable=unused-argument
def writeto_then_readfrom(
self,
address,
buffer_out,
buffer_in,
*,
out_start=0,
out_end=None,
in_start=0,
in_end=None,
stop=False,
):
"""Write data from buffer_out to an address and then
read data from an address and into buffer_in
"""
out_end = out_end if out_end else len(buffer_out)
in_end = in_end if in_end else len(buffer_in)
port = self._i2c.get_port(address)
result = port.exchange(
buffer_out[out_start:out_end], in_end - in_start, relax=True
)
for i, b in enumerate(result):
buffer_in[in_start + i] = b
# pylint: enable=unused-argument | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/ftdi_mpsse/mpsse/i2c.py | i2c.py |
"""SPI Class for FTDI MPSSE"""
from adafruit_blinka.microcontroller.ftdi_mpsse.mpsse.pin import Pin
from adafruit_blinka.microcontroller.ftdi_mpsse.mpsse.url import (
get_ft232h_url,
get_ft2232h_url,
)
# pylint: disable=protected-access
class SPI:
"""Custom SPI Class for FTDI MPSSE"""
MSB = 0
def __init__(self, spi_id=None):
# pylint: disable=import-outside-toplevel
from pyftdi.spi import SpiController
# pylint: enable=import-outside-toplevel
self._spi = SpiController(cs_count=1)
if spi_id is None:
self._spi.configure(get_ft232h_url())
else:
self._spi.configure(get_ft2232h_url(spi_id + 1))
self._port = self._spi.get_port(0)
self._port.set_frequency(100000)
self._port._cpol = 0
self._port._cpha = 0
# Change GPIO controller to SPI
Pin.mpsse_gpio = self._spi.get_gpio()
# pylint: disable=too-many-arguments,unused-argument
def init(
self,
baudrate=100000,
polarity=0,
phase=0,
bits=8,
firstbit=MSB,
sck=None,
mosi=None,
miso=None,
):
"""Initialize the Port"""
self._port.set_frequency(baudrate)
# FTDI device can only support mode 0 and mode 2
# due to the limitation of MPSSE engine.
# This means CPHA must = 0
self._port._cpol = polarity
if phase != 0:
raise ValueError("Only SPI phase 0 is supported by FT232H.")
self._port._cpha = phase
# pylint: enable=too-many-arguments
@property
def frequency(self):
"""Return the current frequency"""
return self._port.frequency
def write(self, buf, start=0, end=None):
"""Write data from the buffer to SPI"""
end = end if end else len(buf)
chunks, rest = divmod(end - start, self._spi.PAYLOAD_MAX_LENGTH)
for i in range(chunks):
chunk_start = start + i * self._spi.PAYLOAD_MAX_LENGTH
chunk_end = chunk_start + self._spi.PAYLOAD_MAX_LENGTH
self._port.write(buf[chunk_start:chunk_end])
if rest:
rest_start = start + chunks * self._spi.PAYLOAD_MAX_LENGTH
self._port.write(buf[rest_start:end])
# pylint: disable=unused-argument
def readinto(self, buf, start=0, end=None, write_value=0):
"""Read data from SPI and into the buffer"""
end = end if end else len(buf)
buffer_out = [write_value] * (end - start)
result = self._port.exchange(buffer_out, end - start, duplex=True)
for i, b in enumerate(result):
buf[start + i] = b
# pylint: enable=unused-argument
# pylint: disable=too-many-arguments
def write_readinto(
self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
):
"""Perform a half-duplex write from buffer_out and then
read data into buffer_in
"""
out_end = out_end if out_end else len(buffer_out)
in_end = in_end if in_end else len(buffer_in)
result = self._port.exchange(
buffer_out[out_start:out_end], in_end - in_start, duplex=True
)
for i, b in enumerate(result):
buffer_in[in_start + i] = b
# pylint: enable=too-many-arguments | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/ftdi_mpsse/mpsse/spi.py | spi.py |
import os
from time import sleep
from errno import EACCES
try:
from microcontroller.pin import pwmOuts
except ImportError:
raise RuntimeError("No PWM outputs defined for this board.") from ImportError
# pylint: disable=unnecessary-pass, too-many-instance-attributes
class PWMError(IOError):
"""Base class for PWM errors."""
pass
# pylint: enable=unnecessary-pass
class PWMOut:
"""Pulse Width Modulation Output Class"""
# Number of retries to check for successful PWM export on open
PWM_STAT_RETRIES = 10
# Delay between check for successful PWM export on open (100ms)
PWM_STAT_DELAY = 0.1
# Sysfs paths
_chip_path = "pwmchip{}"
_channel_path = "pwm{}"
def __init__(self, pwm, *, frequency=500, duty_cycle=0, variable_frequency=False):
"""Instantiate a PWM object and open the sysfs PWM corresponding to the
specified chip and channel.
Args:
pwm (str): PWM pin.
frequency (int, float): target frequency in Hertz (32-bit).
duty_cycle (int, float): The fraction of each pulse which is high (16-bit).
variable_frequency (bool): True if the frequency will change over time.
Returns:
PWM: PWM object.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if `chip` or `channel` types are invalid.
LookupError: if PWM chip does not exist.
TimeoutError: if waiting for PWM export times out.
"""
self._chip = None
self._channel = None
self._period_ns = 0
self._open(pwm, frequency, duty_cycle, variable_frequency)
def __del__(self):
self.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def _open(self, pwm, frequency, duty_cycle, variable_frequency):
for pwmout in pwmOuts:
if pwmout[1] == pwm:
self._chip = pwmout[0][0]
self._channel = pwmout[0][1]
self._chip_path = os.path.join(
"/sys/class/pwm", self._chip_path.format(self._chip)
)
self._channel_path = os.path.join(
self._chip_path, self._channel_path.format(self._channel)
)
if variable_frequency:
print("Variable Frequency is not supported, continuing without it...")
if not os.path.isdir(self._chip_path):
raise LookupError("Opening PWM: PWM chip {} not found.".format(self._chip))
if not os.path.isdir(self._channel_path):
# Exporting the PWM.
try:
with open(
os.path.join(self._chip_path, "export"), "w", encoding="utf-8"
) as f_export:
f_export.write("{:d}\n".format(self._channel))
except IOError as e:
raise PWMError(
e.errno, "Exporting PWM channel: " + e.strerror
) from IOError
# Loop until PWM is exported
exported = False
for i in range(PWMOut.PWM_STAT_RETRIES):
if os.path.isdir(self._channel_path):
exported = True
break
sleep(PWMOut.PWM_STAT_DELAY)
if not exported:
raise TimeoutError(
'Exporting PWM: waiting for "{:s}" timed out.'.format(
self._channel_path
)
)
# Loop until 'period' is writable, This could take some time after
# export as application of the udev rules after export is asynchronous.
# Without this loop, the following properties may not be writable yet.
for i in range(PWMOut.PWM_STAT_RETRIES):
try:
with open(
os.path.join(self._channel_path, "period"),
"w",
encoding="utf-8",
):
break
except IOError as e:
if e.errno != EACCES or (
e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
):
raise PWMError(
e.errno, "Opening PWM period: " + e.strerror
) from IOError
sleep(PWMOut.PWM_STAT_DELAY)
self.frequency = frequency
self.duty_cycle = duty_cycle
# Cache the period for fast duty cycle updates
self._period_ns = self._get_period_ns()
def close(self):
"""Close the PWM."""
if self._channel is not None:
# Unexporting the PWM channel
try:
unexport_fd = os.open(
os.path.join(self._chip_path, "unexport"), os.O_WRONLY
)
os.write(unexport_fd, "{:d}\n".format(self._channel).encode())
os.close(unexport_fd)
except OSError as e:
raise PWMError(e.errno, "Unexporting PWM: " + e.strerror) from OSError
self._chip = None
self._channel = None
def _write_channel_attr(self, attr, value):
with open(
os.path.join(self._channel_path, attr), "w", encoding="utf-8"
) as f_attr:
f_attr.write(value + "\n")
def _read_channel_attr(self, attr):
with open(
os.path.join(self._channel_path, attr), "r", encoding="utf-8"
) as f_attr:
return f_attr.read().strip()
# Methods
def enable(self):
"""Enable the PWM output."""
self.enabled = True
def disable(self):
"""Disable the PWM output."""
self.enabled = False
# Mutable properties
def _get_period(self):
return float(self.period_ms) / 1000
def _set_period(self, period):
if not isinstance(period, (int, float)):
raise TypeError("Invalid period type, should be int.")
self.period_ms = int(period * 1000)
period = property(_get_period, _set_period)
"""Get or set the PWM's output period in seconds.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int.
:type: int, float
"""
def _get_period_ms(self):
return self.period_us / 1000
def _set_period_ms(self, period_ms):
if not isinstance(period_ms, (int, float)):
raise TypeError("Invalid period type, should be int or float.")
self.period_us = int(period_ms * 1000)
period_ms = property(_get_period_ms, _set_period_ms)
"""Get or set the PWM's output period in milliseconds.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int.
:type: int, float
"""
def _get_period_us(self):
return self.period_ns / 1000
def _set_period_us(self, period_us):
if not isinstance(period_us, int):
raise TypeError("Invalid period type, should be int.")
self.period_ns = int(period_us * 1000)
period_us = property(_get_period_us, _set_period_us)
"""Get or set the PWM's output period in microseconds.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int.
:type: int
"""
def _get_period_ns(self):
period_ns = self._read_channel_attr("period")
try:
period_ns = int(period_ns)
except ValueError:
raise PWMError(
None, 'Unknown period value: "%s".' % period_ns
) from ValueError
self._period_ns = period_ns
return period_ns
def _set_period_ns(self, period_ns):
if not isinstance(period_ns, int):
raise TypeError("Invalid period type, should be int.")
self._write_channel_attr("period", str(period_ns))
# Update our cached period
self._period_ns = period_ns
period_ns = property(_get_period_ns, _set_period_ns)
"""Get or set the PWM's output period in nanoseconds.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int.
:type: int
"""
def _get_duty_cycle_ns(self):
duty_cycle_ns_str = self._read_channel_attr("duty_cycle")
try:
duty_cycle_ns = int(duty_cycle_ns_str)
except ValueError:
raise PWMError(
None, 'Unknown duty cycle value: "{:s}"'.format(duty_cycle_ns_str)
) from ValueError
return duty_cycle_ns
def _set_duty_cycle_ns(self, duty_cycle_ns):
if not isinstance(duty_cycle_ns, int):
raise TypeError("Invalid duty cycle type, should be int.")
self._write_channel_attr("duty_cycle", str(duty_cycle_ns))
duty_cycle_ns = property(_get_duty_cycle_ns, _set_duty_cycle_ns)
"""Get or set the PWM's output duty cycle in nanoseconds.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int.
:type: int
"""
def _get_duty_cycle(self):
return float(self.duty_cycle_ns) / self._period_ns
def _set_duty_cycle(self, duty_cycle):
if not isinstance(duty_cycle, (int, float)):
raise TypeError("Invalid duty cycle type, should be int or float.")
if not 0.0 <= duty_cycle <= 1.0:
raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
# Convert duty cycle from ratio to nanoseconds
self.duty_cycle_ns = int(duty_cycle * self._period_ns)
duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
"""Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
ValueError: if value is out of bounds of 0.0 to 1.0.
:type: int, float
"""
def _get_frequency(self):
return 1.0 / self.period
def _set_frequency(self, frequency):
if not isinstance(frequency, (int, float)):
raise TypeError("Invalid frequency type, should be int or float.")
self.period = 1.0 / frequency
frequency = property(_get_frequency, _set_frequency)
"""Get or set the PWM's output frequency in Hertz.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
:type: int, float
"""
def _get_polarity(self):
return self._read_channel_attr("polarity")
def _set_polarity(self, polarity):
if not isinstance(polarity, str):
raise TypeError("Invalid polarity type, should be str.")
if polarity.lower() not in ["normal", "inversed"]:
raise ValueError('Invalid polarity, can be: "normal" or "inversed".')
self._write_channel_attr("polarity", polarity.lower())
polarity = property(_get_polarity, _set_polarity)
"""Get or set the PWM's output polarity. Can be "normal" or "inversed".
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not str.
ValueError: if value is invalid.
:type: str
"""
def _get_enabled(self):
enabled = self._read_channel_attr("enable")
if enabled == "1":
return True
if enabled == "0":
return False
raise PWMError(None, 'Unknown enabled value: "{:s}"'.format(enabled))
def _set_enabled(self, value):
if not isinstance(value, bool):
raise TypeError("Invalid enabled type, should be bool.")
self._write_channel_attr("enable", "1" if value else "0")
enabled = property(_get_enabled, _set_enabled)
"""Get or set the PWM's output enabled state.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not bool.
:type: bool
"""
# String representation
def __str__(self):
return (
"PWM {:d}, chip {:d} (period={:f} sec, duty_cycle={:f}%,"
" polarity={:s}, enabled={:s})".format(
self._channel,
self._chip,
self.period,
self.duty_cycle * 100,
self.polarity,
str(self.enabled),
)
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rockchip/PWMOut.py | PWMOut.py |
"""A Pin class for use with Rockchip RK3308."""
from adafruit_blinka.microcontroller.generic_linux.sysfs_pin import Pin
GPIO0_A0 = Pin(0)
GPIO0_A1 = Pin(1)
GPIO0_A2 = Pin(2)
GPIO0_A3 = Pin(3)
GPIO0_A4 = Pin(4)
GPIO0_A5 = Pin(5)
GPIO0_A6 = Pin(6)
GPIO0_A7 = Pin(7)
GPIO0_B0 = Pin(8)
GPIO0_B1 = Pin(9)
GPIO0_B2 = Pin(10)
GPIO0_B3 = Pin(11)
GPIO0_B4 = Pin(12)
GPIO0_B5 = Pin(13)
GPIO0_B6 = Pin(14)
GPIO0_B7 = Pin(15)
GPIO0_C0 = Pin(16)
GPIO0_C1 = Pin(17)
GPIO0_C2 = Pin(18)
GPIO0_C3 = Pin(19)
GPIO0_C4 = Pin(20)
GPIO0_C5 = Pin(21)
GPIO0_C6 = Pin(22)
GPIO0_C7 = Pin(23)
GPIO0_D0 = Pin(24)
GPIO0_D1 = Pin(25)
GPIO0_D2 = Pin(26)
GPIO0_D3 = Pin(27)
GPIO0_D4 = Pin(28)
GPIO0_D5 = Pin(29)
GPIO0_D6 = Pin(30)
GPIO0_D7 = Pin(31)
GPIO1_A0 = Pin(32)
GPIO1_A1 = Pin(33)
GPIO1_A2 = Pin(34)
GPIO1_A3 = Pin(35)
GPIO1_A4 = Pin(36)
GPIO1_A5 = Pin(37)
GPIO1_A6 = Pin(38)
GPIO1_A7 = Pin(39)
GPIO1_B0 = Pin(40)
GPIO1_B1 = Pin(41)
GPIO1_B2 = Pin(42)
GPIO1_B3 = Pin(43)
GPIO1_B4 = Pin(44)
GPIO1_B5 = Pin(45)
GPIO1_B6 = Pin(46)
GPIO1_B7 = Pin(47)
GPIO1_C0 = Pin(48)
GPIO1_C1 = Pin(49)
GPIO1_C2 = Pin(50)
GPIO1_C3 = Pin(51)
GPIO1_C4 = Pin(52)
GPIO1_C5 = Pin(53)
GPIO1_C6 = Pin(54)
GPIO1_C7 = Pin(55)
GPIO1_D0 = Pin(56)
GPIO1_D1 = Pin(57)
GPIO1_D2 = Pin(58)
GPIO1_D3 = Pin(59)
GPIO1_D4 = Pin(60)
GPIO1_D5 = Pin(61)
GPIO1_D6 = Pin(62)
GPIO1_D7 = Pin(63)
GPIO2_A0 = Pin(64)
GPIO2_A1 = Pin(65)
GPIO2_A2 = Pin(66)
GPIO2_A3 = Pin(67)
GPIO2_A4 = Pin(68)
GPIO2_A5 = Pin(69)
GPIO2_A6 = Pin(70)
GPIO2_A7 = Pin(71)
GPIO2_B0 = Pin(72)
GPIO2_B1 = Pin(73)
GPIO2_B2 = Pin(74)
GPIO2_B3 = Pin(75)
GPIO2_B4 = Pin(76)
GPIO2_B5 = Pin(77)
GPIO2_B6 = Pin(78)
GPIO2_B7 = Pin(79)
GPIO2_C0 = Pin(80)
GPIO2_C1 = Pin(81)
GPIO2_C2 = Pin(82)
GPIO2_C3 = Pin(83)
GPIO2_C4 = Pin(84)
GPIO2_C5 = Pin(85)
GPIO2_C6 = Pin(86)
GPIO2_C7 = Pin(87)
GPIO2_D0 = Pin(88)
GPIO2_D1 = Pin(89)
GPIO2_D2 = Pin(90)
GPIO2_D3 = Pin(91)
GPIO2_D4 = Pin(92)
GPIO2_D5 = Pin(93)
GPIO2_D6 = Pin(94)
GPIO2_D7 = Pin(95)
GPIO3_A0 = Pin(96)
GPIO3_A1 = Pin(97)
GPIO3_A2 = Pin(98)
GPIO3_A3 = Pin(99)
GPIO3_A4 = Pin(100)
GPIO3_A5 = Pin(101)
GPIO3_A6 = Pin(102)
GPIO3_A7 = Pin(103)
GPIO3_B0 = Pin(104)
GPIO3_B1 = Pin(105)
GPIO3_B2 = Pin(106)
GPIO3_B3 = Pin(107)
GPIO3_B4 = Pin(108)
GPIO3_B5 = Pin(109)
GPIO3_B6 = Pin(110)
GPIO3_B7 = Pin(111)
GPIO3_C0 = Pin(112)
GPIO3_C1 = Pin(113)
GPIO3_C2 = Pin(114)
GPIO3_C3 = Pin(115)
GPIO3_C4 = Pin(116)
GPIO3_C5 = Pin(117)
GPIO3_C6 = Pin(118)
GPIO3_C7 = Pin(119)
GPIO3_D0 = Pin(120)
GPIO3_D1 = Pin(121)
GPIO3_D2 = Pin(122)
GPIO3_D3 = Pin(123)
GPIO3_D4 = Pin(124)
GPIO3_D5 = Pin(125)
GPIO3_D6 = Pin(126)
GPIO3_D7 = Pin(127)
ADC_IN0 = 1
# I2C
I2C0_SDA = GPIO1_D0
I2C0_SCL = GPIO1_D1
I2C1_SDA = GPIO0_B3
I2C1_SCL = GPIO0_B4
I2C2_SDA = GPIO2_A2
I2C2_SCL = GPIO2_A3
I2C3_SDA = GPIO0_B7
I2C3_SCL = GPIO0_C0
# SPI
SPI2_CS = GPIO1_D1
SPI2_SCLK = GPIO1_D0
SPI2_MISO = GPIO1_C6
SPI2_MOSI = GPIO1_C7
# UART
UART0_TX = GPIO2_A1
UART0_RX = GPIO2_A0
UART1_TX = GPIO1_D1
UART1_RX = GPIO1_D0
UART2_TX = GPIO1_C7
UART2_RX = GPIO1_C6
# PWM
PWM2 = GPIO0_B7
PWM3 = GPIO0_C0
# ordered as i2cId, SCL, SDA
i2cPorts = (
(0, I2C0_SCL, I2C0_SDA),
(1, I2C1_SCL, I2C1_SDA),
(2, I2C2_SCL, I2C2_SDA),
(3, I2C3_SCL, I2C3_SDA),
)
# ordered as spiId, sckId, mosiId, misoId
spiPorts = ((2, SPI2_SCLK, SPI2_MOSI, SPI2_MISO),)
# SysFS pwm outputs, pwm channel and pin in first tuple
pwmOuts = (
((1, 0), PWM2),
((2, 0), PWM3),
)
# SysFS analog inputs, Ordered as analog analogInId, device, and channel
analogIns = ((ADC_IN0, 0, 0),) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rockchip/rk3308/pin.py | pin.py |
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
GPIO0_A2 = Pin((0, 2))
GPIO0_A4 = Pin((0, 4))
GPIO0_A5 = Pin((0, 5))
GPIO0_B1 = Pin((0, 9))
GPIO0_B2 = Pin((0, 10))
GPIO0_B5 = Pin((0, 13))
GPIO0_B6 = Pin((0, 14))
GPIO0_B7 = Pin((0, 15))
GPIO0_C2 = Pin((0, 18))
GPIO0_C3 = Pin((0, 19))
GPIO0_C5 = Pin((0, 21))
GPIO0_C6 = Pin((0, 22))
GPIO0_C7 = Pin((0, 23))
GPIO0_D0 = Pin((0, 24))
GPIO0_D1 = Pin((0, 25))
GPIO1_A0 = Pin((1, 0))
GPIO1_A1 = Pin((1, 1))
GPIO1_A2 = Pin((1, 2))
GPIO1_A3 = Pin((1, 3))
GPIO1_A4 = Pin((1, 4))
GPIO1_A5 = Pin((1, 5))
GPIO1_A7 = Pin((1, 7))
GPIO1_B0 = Pin((1, 8))
GPIO1_B1 = Pin((1, 9))
GPIO1_B2 = Pin((1, 10))
GPIO1_B3 = Pin((1, 11))
GPIO1_D5 = Pin((1, 29))
GPIO1_D6 = Pin((1, 30))
GPIO1_D7 = Pin((1, 31))
GPIO2_A0 = Pin((2, 0))
GPIO2_A1 = Pin((2, 1))
GPIO2_A2 = Pin((2, 2))
GPIO2_C3 = Pin((2, 19))
GPIO2_C4 = Pin((2, 20))
GPIO2_C5 = Pin((2, 21))
GPIO2_C6 = Pin((2, 22))
GPIO3_A5 = Pin((3, 5))
GPIO3_A6 = Pin((3, 6))
GPIO3_A7 = Pin((3, 7))
GPIO3_B1 = Pin((3, 9))
GPIO3_B2 = Pin((3, 10))
GPIO3_B3 = Pin((3, 11))
GPIO3_B4 = Pin((3, 12))
GPIO3_B5 = Pin((3, 13))
GPIO3_B6 = Pin((3, 14))
GPIO3_B7 = Pin((3, 15))
GPIO3_C0 = Pin((3, 16))
GPIO3_C1 = Pin((3, 17))
GPIO3_C2 = Pin((3, 18))
GPIO3_C3 = Pin((3, 19))
GPIO3_C4 = Pin((3, 20))
GPIO3_C5 = Pin((3, 21))
GPIO3_C6 = Pin((3, 22))
GPIO3_C7 = Pin((3, 23))
GPIO3_D0 = Pin((3, 24))
GPIO3_D1 = Pin((3, 25))
GPIO3_D2 = Pin((3, 26))
GPIO3_D3 = Pin((3, 27))
GPIO3_D4 = Pin((3, 28))
GPIO3_D5 = Pin((3, 29))
GPIO4_A4 = Pin((4, 4))
GPIO4_A5 = Pin((4, 5))
GPIO4_A6 = Pin((4, 6))
GPIO4_A7 = Pin((4, 7))
GPIO4_B0 = Pin((4, 8))
GPIO4_B1 = Pin((4, 9))
GPIO4_B2 = Pin((4, 10))
GPIO4_B3 = Pin((4, 11))
GPIO4_B4 = Pin((4, 12))
GPIO4_B5 = Pin((4, 13))
GPIO4_B6 = Pin((4, 14))
GPIO4_B7 = Pin((4, 15))
GPIO4_C0 = Pin((4, 16))
GPIO4_C1 = Pin((4, 17))
GPIO4_C2 = Pin((4, 18))
GPIO4_C3 = Pin((4, 19))
GPIO4_C4 = Pin((4, 20))
GPIO4_C5 = Pin((4, 21))
GPIO4_C6 = Pin((4, 22))
ADC_AIN3 = 37
# I2C
I2C0_SCL = GPIO0_B1
I2C0_SDA = GPIO0_B2
I2C2_SCL_M0 = GPIO0_B5
I2C2_SDA_M0 = GPIO0_B6
I2C2_SCL_M1 = GPIO4_B5
I2C2_SDA_M1 = GPIO4_B4
I2C3_SCL_M0 = GPIO1_A1
I2C3_SDA_M0 = GPIO1_A0
I2C4_SCL_M0 = GPIO4_B3
I2C4_SDA_M0 = GPIO4_B2
I2C5_SCL_M0 = GPIO3_B3
I2C5_SDA_M0 = GPIO3_B4
# SPI
SPI0_CS0_M0 = GPIO0_C6
SPI0_CLK_M0 = GPIO0_B5
SPI0_MISO_M0 = GPIO0_C5
SPI0_MOSI_M0 = GPIO0_B6
SPI3_CS0_M0 = GPIO4_A6
SPI3_CLK_M0 = GPIO4_B3
SPI3_MISO_M0 = GPIO4_B0
SPI3_MOSI_M0 = GPIO4_B2
SPI3_CS0_M1 = GPIO4_C6
SPI3_CLK_M1 = GPIO4_C2
SPI3_MISO_M1 = GPIO4_C5
SPI3_MOSI_M1 = GPIO4_C3
# UART
UART2_TX = GPIO0_D1
UART2_RX = GPIO0_D0
UART3_TX_M1 = GPIO3_B7
UART3_RX_M1 = GPIO3_C0
UART8_TX_M0 = GPIO2_C5
UART8_RX_M0 = GPIO2_C6
# PWM
PWM0 = GPIO0_B7
PWM1 = GPIO0_C7
# ordered as i2cId, SCL, SDA
i2cPorts = (
(2, I2C2_SCL_M0, I2C2_SDA_M0),
(3, I2C3_SCL_M0, I2C3_SDA_M0),
(5, I2C5_SCL_M0, I2C5_SDA_M0),
)
# ordered as spiId, sckId, mosiId, misoId
spiPorts = (
(3, SPI3_CLK_M0, SPI3_MOSI_M0, SPI3_MISO_M0),
(3, SPI3_CLK_M1, SPI3_MOSI_M1, SPI3_MISO_M1),
)
# SysFS pwm outputs, pwm channel and pin in first tuple
pwmOuts = (
((0, 0), PWM0),
((0, 0), PWM1),
)
# SysFS analog inputs, Ordered as analog analogInId, device, and channel
analogIns = ((ADC_AIN3, 0, 3),) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rockchip/rk3566/pin.py | pin.py |
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
# GPIOx_yz = x * 32 + y * 8 + z
# y: A -> 0, B -> 1, C -> 2, D -> 3
# GPIO0
GPIO0_A0 = Pin((0, 0))
GPIO0_A1 = Pin((0, 1))
GPIO0_A2 = Pin((0, 2))
GPIO0_A3 = Pin((0, 3))
GPIO0_A4 = Pin((0, 4))
GPIO0_A5 = Pin((0, 5))
GPIO0_A6 = Pin((0, 6))
GPIO0_A7 = Pin((0, 7))
GPIO0_B0 = Pin((0, 8))
GPIO0_B1 = Pin((0, 9))
GPIO0_B2 = Pin((0, 10))
GPIO0_B3 = Pin((0, 11))
GPIO0_B4 = Pin((0, 12))
GPIO0_B5 = Pin((0, 13))
GPIO0_B6 = Pin((0, 14))
GPIO0_B7 = Pin((0, 15))
GPIO0_C0 = Pin((0, 16))
GPIO0_C1 = Pin((0, 17))
GPIO0_C2 = Pin((0, 18))
GPIO0_C3 = Pin((0, 19))
GPIO0_C4 = Pin((0, 20))
GPIO0_C5 = Pin((0, 21))
GPIO0_C6 = Pin((0, 22))
GPIO0_C7 = Pin((0, 23))
GPIO0_D0 = Pin((0, 24))
GPIO0_D1 = Pin((0, 25))
GPIO0_D2 = Pin((0, 26))
GPIO0_D3 = Pin((0, 27))
GPIO0_D4 = Pin((0, 28))
GPIO0_D5 = Pin((0, 29))
GPIO0_D6 = Pin((0, 30))
GPIO0_D7 = Pin((0, 31))
# GPIO1
GPIO1_A0 = Pin((1, 0))
GPIO1_A1 = Pin((1, 1))
GPIO1_A2 = Pin((1, 2))
GPIO1_A3 = Pin((1, 3))
GPIO1_A4 = Pin((1, 4))
GPIO1_A5 = Pin((1, 5))
GPIO1_A6 = Pin((1, 6))
GPIO1_A7 = Pin((1, 7))
GPIO1_B0 = Pin((1, 8))
GPIO1_B1 = Pin((1, 9))
GPIO1_B2 = Pin((1, 10))
GPIO1_B3 = Pin((1, 11))
GPIO1_B4 = Pin((1, 12))
GPIO1_B5 = Pin((1, 13))
GPIO1_B6 = Pin((1, 14))
GPIO1_B7 = Pin((1, 15))
GPIO1_C0 = Pin((1, 16))
GPIO1_C1 = Pin((1, 17))
GPIO1_C2 = Pin((1, 18))
GPIO1_C3 = Pin((1, 19))
GPIO1_C4 = Pin((1, 20))
GPIO1_C5 = Pin((1, 21))
GPIO1_C6 = Pin((1, 22))
GPIO1_C7 = Pin((1, 23))
GPIO1_D0 = Pin((1, 24))
GPIO1_D1 = Pin((1, 25))
GPIO1_D2 = Pin((1, 26))
GPIO1_D3 = Pin((1, 27))
GPIO1_D4 = Pin((1, 28))
GPIO1_D5 = Pin((1, 29))
GPIO1_D6 = Pin((1, 30))
GPIO1_D7 = Pin((1, 31))
# GPIO2
GPIO2_A0 = Pin((2, 0))
GPIO2_A1 = Pin((2, 1))
GPIO2_A2 = Pin((2, 2))
GPIO2_A3 = Pin((2, 3))
GPIO2_A4 = Pin((2, 4))
GPIO2_A5 = Pin((2, 5))
GPIO2_A6 = Pin((2, 6))
GPIO2_A7 = Pin((2, 7))
GPIO2_B0 = Pin((2, 8))
GPIO2_B1 = Pin((2, 9))
GPIO2_B2 = Pin((2, 10))
GPIO2_B3 = Pin((2, 11))
GPIO2_B4 = Pin((2, 12))
GPIO2_B5 = Pin((2, 13))
GPIO2_B6 = Pin((2, 14))
GPIO2_B7 = Pin((2, 15))
GPIO2_C0 = Pin((2, 16))
GPIO2_C1 = Pin((2, 17))
GPIO2_C2 = Pin((2, 18))
GPIO2_C3 = Pin((2, 19))
GPIO2_C4 = Pin((2, 20))
GPIO2_C5 = Pin((2, 21))
GPIO2_C6 = Pin((2, 22))
GPIO2_C7 = Pin((2, 23))
GPIO2_D0 = Pin((2, 24))
GPIO2_D1 = Pin((2, 25))
GPIO2_D2 = Pin((2, 26))
GPIO2_D3 = Pin((2, 27))
GPIO2_D4 = Pin((2, 28))
GPIO2_D5 = Pin((2, 29))
GPIO2_D6 = Pin((2, 30))
GPIO2_D7 = Pin((2, 31))
# GPIO3
GPIO3_A0 = Pin((3, 0))
GPIO3_A1 = Pin((3, 1))
GPIO3_A2 = Pin((3, 2))
GPIO3_A3 = Pin((3, 3))
GPIO3_A4 = Pin((3, 4))
GPIO3_A5 = Pin((3, 5))
GPIO3_A6 = Pin((3, 6))
GPIO3_A7 = Pin((3, 7))
GPIO3_B0 = Pin((3, 8))
GPIO3_B1 = Pin((3, 9))
GPIO3_B2 = Pin((3, 10))
GPIO3_B3 = Pin((3, 11))
GPIO3_B4 = Pin((3, 12))
GPIO3_B5 = Pin((3, 13))
GPIO3_B6 = Pin((3, 14))
GPIO3_B7 = Pin((3, 15))
GPIO3_C0 = Pin((3, 16))
GPIO3_C1 = Pin((3, 17))
GPIO3_C2 = Pin((3, 18))
GPIO3_C3 = Pin((3, 19))
GPIO3_C4 = Pin((3, 20))
GPIO3_C5 = Pin((3, 21))
GPIO3_C6 = Pin((3, 22))
GPIO3_C7 = Pin((3, 23))
GPIO3_D0 = Pin((3, 24))
GPIO3_D1 = Pin((3, 25))
GPIO3_D2 = Pin((3, 26))
GPIO3_D3 = Pin((3, 27))
GPIO3_D4 = Pin((3, 28))
GPIO3_D5 = Pin((3, 29))
GPIO3_D6 = Pin((3, 30))
GPIO3_D7 = Pin((3, 31))
# GPIO4
GPIO4_A0 = Pin((4, 0))
GPIO4_A1 = Pin((4, 1))
GPIO4_A2 = Pin((4, 2))
GPIO4_A3 = Pin((4, 3))
GPIO4_A4 = Pin((4, 4))
GPIO4_A5 = Pin((4, 5))
GPIO4_A6 = Pin((4, 6))
GPIO4_A7 = Pin((4, 7))
GPIO4_B0 = Pin((4, 8))
GPIO4_B1 = Pin((4, 9))
GPIO4_B2 = Pin((4, 10))
GPIO4_B3 = Pin((4, 11))
GPIO4_B4 = Pin((4, 12))
GPIO4_B5 = Pin((4, 13))
GPIO4_B6 = Pin((4, 14))
GPIO4_B7 = Pin((4, 15))
GPIO4_C0 = Pin((4, 16))
GPIO4_C1 = Pin((4, 17))
GPIO4_C2 = Pin((4, 18))
GPIO4_C3 = Pin((4, 19))
GPIO4_C4 = Pin((4, 20))
GPIO4_C5 = Pin((4, 21))
GPIO4_C6 = Pin((4, 22))
GPIO4_C7 = Pin((4, 23))
GPIO4_D0 = Pin((4, 24))
GPIO4_D1 = Pin((4, 25))
GPIO4_D2 = Pin((4, 26))
GPIO4_D3 = Pin((4, 27))
GPIO4_D4 = Pin((4, 28))
GPIO4_D5 = Pin((4, 29))
GPIO4_D6 = Pin((4, 30))
GPIO4_D7 = Pin((4, 31))
# I2C
I2C3_SCL_M0 = GPIO1_A1
I2C3_SDA_M0 = GPIO1_A0
I2C5_SCL_M0 = GPIO3_B3
I2C5_SDA_M0 = GPIO3_B4
I2C2_SCL_M0 = GPIO0_B5
I2C2_SDA_M0 = GPIO0_B6
I2C1_SCL = GPIO0_B3
I2C1_SDA = GPIO0_B4
# SPI
SPI3_CS0_M1 = GPIO4_C6
SPI3_CS1_M1 = GPIO4_D1
SPI3_CLK_M1 = GPIO4_C2
SPI3_MISO_M1 = GPIO4_C5
SPI3_MOSI_M1 = GPIO4_C3
# UART
UART0_RX = GPIO0_C0
UART0_TX = GPIO0_C1
UART2_TX_M0 = GPIO0_D1
UART2_RX_M0 = GPIO0_D0
UART3_TX_M0 = GPIO1_A1
UART3_RX_M0 = GPIO1_A0
UART3_TX_M1 = GPIO3_B7
UART3_RX_M1 = GPIO3_C0
UART7_TX_M1 = GPIO3_C4
UART7_RX_M1 = GPIO3_C5
# PWM
PWM1_M0 = GPIO0_C0
PWM1_M1 = GPIO0_B5
PWM2_M0 = GPIO0_C1
PWM2_M1 = GPIO0_B6
PWM8_M0 = GPIO3_B1
PWM9_M0 = GPIO3_B2
PWM12_M1 = GPIO4_C5
PWM13_M1 = GPIO4_C6
PWM10_M0 = GPIO3_B5
PWM14_M0 = GPIO3_C4
PWM14_M1 = GPIO4_C2
PWM15_IR_M1 = GPIO3_C5
# ordered as i2cId, SCL, SDA
i2cPorts = (
(3, I2C3_SCL_M0, I2C3_SDA_M0),
(5, I2C5_SCL_M0, I2C5_SDA_M0),
(2, I2C2_SCL_M0, I2C2_SDA_M0),
(1, I2C1_SCL, I2C1_SDA),
)
# ordered as spiId, sckId, mosiId, misoId
spiPorts = ((3, SPI3_CLK_M1, SPI3_MOSI_M1, SPI3_MISO_M1),)
# SysFS pwm outputs, pwm channel and pin in first tuple
pwmOuts = (
((1, 0), PWM1_M0),
((1, 0), PWM2_M0),
((1, 0), PWM8_M0),
((1, 0), PWM9_M0),
((1, 0), PWM10_M0),
((1, 0), PWM12_M1),
((1, 0), PWM13_M1),
((1, 0), PWM14_M0),
)
# SysFS analog inputs, Ordered as analog analogInId, device, and channel | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rockchip/rk3568/pin.py | pin.py |
"""A Pin class for use with Rockchip RK3328."""
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
GPIO0_A0 = Pin((0, 0))
GPIO0_A1 = Pin((0, 1))
GPIO0_A2 = Pin((0, 2))
GPIO0_A3 = Pin((0, 3))
GPIO0_A4 = Pin((0, 4))
GPIO0_A5 = Pin((0, 5))
GPIO0_A6 = Pin((0, 6))
GPIO0_A7 = Pin((0, 7))
GPIO0_B0 = Pin((0, 8))
GPIO0_B1 = Pin((0, 9))
GPIO0_B2 = Pin((0, 10))
GPIO0_B3 = Pin((0, 11))
GPIO0_B4 = Pin((0, 12))
GPIO0_B5 = Pin((0, 13))
GPIO0_B6 = Pin((0, 14))
GPIO0_B7 = Pin((0, 15))
GPIO0_C0 = Pin((0, 16))
GPIO0_C1 = Pin((0, 17))
GPIO0_C2 = Pin((0, 18))
GPIO0_C3 = Pin((0, 19))
GPIO0_C4 = Pin((0, 20))
GPIO0_C5 = Pin((0, 21))
GPIO0_C6 = Pin((0, 22))
GPIO0_C7 = Pin((0, 23))
GPIO0_D0 = Pin((0, 24))
GPIO0_D1 = Pin((0, 25))
GPIO0_D2 = Pin((0, 26))
GPIO0_D3 = Pin((0, 27))
GPIO0_D4 = Pin((0, 28))
GPIO0_D5 = Pin((0, 29))
GPIO0_D6 = Pin((0, 30))
GPIO0_D7 = Pin((0, 31))
GPIO1_A0 = Pin((1, 0))
GPIO1_A1 = Pin((1, 1))
GPIO1_A2 = Pin((1, 2))
GPIO1_A3 = Pin((1, 3))
GPIO1_A4 = Pin((1, 4))
GPIO1_A5 = Pin((1, 5))
GPIO1_A6 = Pin((1, 6))
GPIO1_A7 = Pin((1, 7))
GPIO1_B0 = Pin((1, 8))
GPIO1_B1 = Pin((1, 9))
GPIO1_B2 = Pin((1, 10))
GPIO1_B3 = Pin((1, 11))
GPIO1_B4 = Pin((1, 12))
GPIO1_B5 = Pin((1, 13))
GPIO1_B6 = Pin((1, 14))
GPIO1_B7 = Pin((1, 15))
GPIO1_C0 = Pin((1, 16))
GPIO1_C1 = Pin((1, 17))
GPIO1_C2 = Pin((1, 18))
GPIO1_C3 = Pin((1, 19))
GPIO1_C4 = Pin((1, 20))
GPIO1_C5 = Pin((1, 21))
GPIO1_C6 = Pin((1, 22))
GPIO1_C7 = Pin((1, 23))
GPIO1_D0 = Pin((1, 24))
GPIO1_D1 = Pin((1, 25))
GPIO1_D2 = Pin((1, 26))
GPIO1_D3 = Pin((1, 27))
GPIO1_D4 = Pin((1, 28))
GPIO1_D5 = Pin((1, 29))
GPIO1_D6 = Pin((1, 30))
GPIO1_D7 = Pin((1, 31))
GPIO2_A0 = Pin((2, 0))
GPIO2_A1 = Pin((2, 1))
GPIO2_A2 = Pin((2, 2))
GPIO2_A3 = Pin((2, 3))
GPIO2_A4 = Pin((2, 4))
GPIO2_A5 = Pin((2, 5))
GPIO2_A6 = Pin((2, 6))
GPIO2_A7 = Pin((2, 7))
GPIO2_B0 = Pin((2, 8))
GPIO2_B1 = Pin((2, 9))
GPIO2_B2 = Pin((2, 10))
GPIO2_B3 = Pin((2, 11))
GPIO2_B4 = Pin((2, 12))
GPIO2_B5 = Pin((2, 13))
GPIO2_B6 = Pin((2, 14))
GPIO2_B7 = Pin((2, 15))
GPIO2_C0 = Pin((2, 16))
GPIO2_C1 = Pin((2, 17))
GPIO2_C2 = Pin((2, 18))
GPIO2_C3 = Pin((2, 19))
GPIO2_C4 = Pin((2, 20))
GPIO2_C5 = Pin((2, 21))
GPIO2_C6 = Pin((2, 22))
GPIO2_C7 = Pin((2, 23))
GPIO2_D0 = Pin((2, 24))
GPIO2_D1 = Pin((2, 25))
GPIO2_D2 = Pin((2, 26))
GPIO2_D3 = Pin((2, 27))
GPIO2_D4 = Pin((2, 28))
GPIO2_D5 = Pin((2, 29))
GPIO2_D6 = Pin((2, 30))
GPIO2_D7 = Pin((2, 31))
GPIO3_A0 = Pin((3, 0))
GPIO3_A1 = Pin((3, 1))
GPIO3_A2 = Pin((3, 2))
GPIO3_A3 = Pin((3, 3))
GPIO3_A4 = Pin((3, 4))
GPIO3_A5 = Pin((3, 5))
GPIO3_A6 = Pin((3, 6))
GPIO3_A7 = Pin((3, 7))
GPIO3_B0 = Pin((3, 8))
GPIO3_B1 = Pin((3, 9))
GPIO3_B2 = Pin((3, 10))
GPIO3_B3 = Pin((3, 11))
GPIO3_B4 = Pin((3, 12))
GPIO3_B5 = Pin((3, 13))
GPIO3_B6 = Pin((3, 14))
GPIO3_B7 = Pin((3, 15))
GPIO3_C0 = Pin((3, 16))
GPIO3_C1 = Pin((3, 17))
GPIO3_C2 = Pin((3, 18))
GPIO3_C3 = Pin((3, 19))
GPIO3_C4 = Pin((3, 20))
GPIO3_C5 = Pin((3, 21))
GPIO3_C6 = Pin((3, 22))
GPIO3_C7 = Pin((3, 23))
GPIO3_D0 = Pin((3, 24))
GPIO3_D1 = Pin((3, 25))
GPIO3_D2 = Pin((3, 26))
GPIO3_D3 = Pin((3, 27))
GPIO3_D4 = Pin((3, 28))
GPIO3_D5 = Pin((3, 29))
GPIO3_D6 = Pin((3, 30))
GPIO3_D7 = Pin((3, 31))
# I2C
I2C1_SDA = GPIO2_A4
I2C1_SCL = GPIO2_A5
# SPI
SPI0_CS = GPIO3_B0
SPI0_SCLK = GPIO3_A0
SPI0_MISO = GPIO3_A2
SPI0_MOSI = GPIO3_A1
# UART
UART1_TX = GPIO3_A4
UART1_RX = GPIO3_A6
UART2_TX = GPIO2_A0
UART2_RX = GPIO2_A1
# PWM
PWM2 = GPIO2_A6
# ordered as i2cId, SCL, SDA
i2cPorts = ((0, I2C1_SCL, I2C1_SDA),)
# ordered as spiId, sckId, mosiId, misoId
spiPorts = ((0, SPI0_SCLK, SPI0_MOSI, SPI0_MISO),)
# SysFS pwm outputs, pwm channel and pin in first tuple
pwmOuts = (((2, 0), PWM2),) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rockchip/rk3328/pin.py | pin.py |
"""A Pin class for use with Rockchip RK3588."""
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
# GPIOx_yz = x * 32 + y * 8 + z
# y: A -> 0, B -> 1, C -> 2, D -> 3
GPIO0_A0 = Pin((0, 0))
GPIO0_A1 = Pin((0, 1))
GPIO0_A2 = Pin((0, 2))
GPIO0_A3 = Pin((0, 3))
GPIO0_A4 = Pin((0, 4))
GPIO0_A5 = Pin((0, 5))
GPIO0_A6 = Pin((0, 6))
GPIO0_A7 = Pin((0, 7))
GPIO0_B0 = Pin((0, 8))
GPIO0_B1 = Pin((0, 9))
GPIO0_B2 = Pin((0, 10))
GPIO0_B3 = Pin((0, 11))
GPIO0_B4 = Pin((0, 12))
GPIO0_B5 = Pin((0, 13))
GPIO0_B6 = Pin((0, 14))
GPIO0_B7 = Pin((0, 15))
GPIO0_C0 = Pin((0, 16))
GPIO0_C1 = Pin((0, 17))
GPIO0_C2 = Pin((0, 18))
GPIO0_C3 = Pin((0, 19))
GPIO0_C4 = Pin((0, 20))
GPIO0_C5 = Pin((0, 21))
GPIO0_C6 = Pin((0, 22))
GPIO0_C7 = Pin((0, 23))
GPIO0_D0 = Pin((0, 24))
GPIO0_D1 = Pin((0, 25))
GPIO0_D2 = Pin((0, 26))
GPIO0_D3 = Pin((0, 27))
GPIO0_D4 = Pin((0, 28))
GPIO0_D5 = Pin((0, 29))
GPIO0_D6 = Pin((0, 30))
GPIO0_D7 = Pin((0, 31))
GPIO1_A0 = Pin((1, 0))
GPIO1_A1 = Pin((1, 1))
GPIO1_A2 = Pin((1, 2))
GPIO1_A3 = Pin((1, 3))
GPIO1_A4 = Pin((1, 4))
GPIO1_A5 = Pin((1, 5))
GPIO1_A6 = Pin((1, 6))
GPIO1_A7 = Pin((1, 7))
GPIO1_B0 = Pin((1, 8))
GPIO1_B1 = Pin((1, 9))
GPIO1_B2 = Pin((1, 10))
GPIO1_B3 = Pin((1, 11))
GPIO1_B4 = Pin((1, 12))
GPIO1_B5 = Pin((1, 13))
GPIO1_B6 = Pin((1, 14))
GPIO1_B7 = Pin((1, 15))
GPIO1_C0 = Pin((1, 16))
GPIO1_C1 = Pin((1, 17))
GPIO1_C2 = Pin((1, 18))
GPIO1_C3 = Pin((1, 19))
GPIO1_C4 = Pin((1, 20))
GPIO1_C5 = Pin((1, 21))
GPIO1_C6 = Pin((1, 22))
GPIO1_C7 = Pin((1, 23))
GPIO1_D0 = Pin((1, 24))
GPIO1_D1 = Pin((1, 25))
GPIO1_D2 = Pin((1, 26))
GPIO1_D3 = Pin((1, 27))
GPIO1_D4 = Pin((1, 28))
GPIO1_D5 = Pin((1, 29))
GPIO1_D6 = Pin((1, 30))
GPIO1_D7 = Pin((1, 31))
GPIO2_A0 = Pin((2, 0))
GPIO2_A1 = Pin((2, 1))
GPIO2_A2 = Pin((2, 2))
GPIO2_A3 = Pin((2, 3))
GPIO2_A4 = Pin((2, 4))
GPIO2_A5 = Pin((2, 5))
GPIO2_A6 = Pin((2, 6))
GPIO2_A7 = Pin((2, 7))
GPIO2_B0 = Pin((2, 8))
GPIO2_B1 = Pin((2, 9))
GPIO2_B2 = Pin((2, 10))
GPIO2_B3 = Pin((2, 11))
GPIO2_B4 = Pin((2, 12))
GPIO2_B5 = Pin((2, 13))
GPIO2_B6 = Pin((2, 14))
GPIO2_B7 = Pin((2, 15))
GPIO2_C0 = Pin((2, 16))
GPIO2_C1 = Pin((2, 17))
GPIO2_C2 = Pin((2, 18))
GPIO2_C3 = Pin((2, 19))
GPIO2_C4 = Pin((2, 20))
GPIO2_C5 = Pin((2, 21))
GPIO2_C6 = Pin((2, 22))
GPIO2_C7 = Pin((2, 23))
GPIO2_D0 = Pin((2, 24))
GPIO2_D1 = Pin((2, 25))
GPIO2_D2 = Pin((2, 26))
GPIO2_D3 = Pin((2, 27))
GPIO2_D4 = Pin((2, 28))
GPIO2_D5 = Pin((2, 29))
GPIO2_D6 = Pin((2, 30))
GPIO2_D7 = Pin((2, 31))
GPIO3_A0 = Pin((3, 0))
GPIO3_A1 = Pin((3, 1))
GPIO3_A2 = Pin((3, 2))
GPIO3_A3 = Pin((3, 3))
GPIO3_A4 = Pin((3, 4))
GPIO3_A5 = Pin((3, 5))
GPIO3_A6 = Pin((3, 6))
GPIO3_A7 = Pin((3, 7))
GPIO3_B0 = Pin((3, 8))
GPIO3_B1 = Pin((3, 9))
GPIO3_B2 = Pin((3, 10))
GPIO3_B3 = Pin((3, 11))
GPIO3_B4 = Pin((3, 12))
GPIO3_B5 = Pin((3, 13))
GPIO3_B6 = Pin((3, 14))
GPIO3_B7 = Pin((3, 15))
GPIO3_C0 = Pin((3, 16))
GPIO3_C1 = Pin((3, 17))
GPIO3_C2 = Pin((3, 18))
GPIO3_C3 = Pin((3, 19))
GPIO3_C4 = Pin((3, 20))
GPIO3_C5 = Pin((3, 21))
GPIO3_C6 = Pin((3, 22))
GPIO3_C7 = Pin((3, 23))
GPIO3_D0 = Pin((3, 24))
GPIO3_D1 = Pin((3, 25))
GPIO3_D2 = Pin((3, 26))
GPIO3_D3 = Pin((3, 27))
GPIO3_D4 = Pin((3, 28))
GPIO3_D5 = Pin((3, 29))
GPIO3_D6 = Pin((3, 30))
GPIO3_D7 = Pin((3, 31))
GPIO4_A0 = Pin((4, 0))
GPIO4_A1 = Pin((4, 1))
GPIO4_A2 = Pin((4, 2))
GPIO4_A3 = Pin((4, 3))
GPIO4_A4 = Pin((4, 4))
GPIO4_A5 = Pin((4, 5))
GPIO4_A6 = Pin((4, 6))
GPIO4_A7 = Pin((4, 7))
GPIO4_B0 = Pin((4, 8))
GPIO4_B1 = Pin((4, 9))
GPIO4_B2 = Pin((4, 10))
GPIO4_B3 = Pin((4, 11))
GPIO4_B4 = Pin((4, 12))
GPIO4_B5 = Pin((4, 13))
GPIO4_B6 = Pin((4, 14))
GPIO4_B7 = Pin((4, 15))
GPIO4_C0 = Pin((4, 16))
GPIO4_C1 = Pin((4, 17))
GPIO4_C2 = Pin((4, 18))
GPIO4_C3 = Pin((4, 19))
GPIO4_C4 = Pin((4, 20))
GPIO4_C5 = Pin((4, 21))
GPIO4_C6 = Pin((4, 22))
GPIO4_C7 = Pin((4, 23))
GPIO4_D0 = Pin((4, 24))
GPIO4_D1 = Pin((4, 25))
GPIO4_D2 = Pin((4, 26))
GPIO4_D3 = Pin((4, 27))
GPIO4_D4 = Pin((4, 28))
GPIO4_D5 = Pin((4, 29))
GPIO4_D6 = Pin((4, 30))
GPIO4_D7 = Pin((4, 31))
# UART
UART2_TX_M0 = GPIO0_B5
UART2_RX_M0 = GPIO0_B6
UART2_TX_M2 = GPIO3_B1
UART2_RX_M2 = GPIO3_B2
UART3_TX_M1 = GPIO3_B5
UART3_RX_M1 = GPIO3_B6
UART4_TX_M2 = GPIO1_B3
UART4_RX_M2 = GPIO1_B2
UART7_TX_M1 = GPIO3_C0
UART7_RX_M1 = GPIO3_C1
UART7_TX_M2 = GPIO1_B5
UART7_RX_M2 = GPIO1_B4
# ordered as uartId, txId, rxId
uartPorts = (
(2, UART2_TX_M0, UART2_RX_M0),
(2, UART2_TX_M2, UART2_RX_M2),
(3, UART3_TX_M1, UART3_RX_M1),
(4, UART4_TX_M2, UART4_RX_M2),
(7, UART7_TX_M1, UART7_RX_M1),
(7, UART7_TX_M2, UART7_RX_M2),
)
# I2C
I2C0_SCL_M1 = GPIO4_C5
I2C0_SDA_M1 = GPIO4_C6
I2C1_SCL_M0 = GPIO0_B5
I2C1_SDA_M0 = GPIO0_B6
I2C1_SCL_M4 = GPIO1_B1
I2C1_SDA_M4 = GPIO1_B2
I2C3_SCL_M1 = GPIO3_B7
I2C3_SDA_M1 = GPIO3_C0
I2C7_SCL_M3 = GPIO4_B2
I2C7_SDA_M3 = GPIO4_B3
I2C8_SCL_M4 = GPIO3_C2
I2C8_SDA_M4 = GPIO3_C3
I2C5_SDA_M3 = GPIO1_B7
I2C5_SCL_M3 = GPIO1_B6
# ordered as i2cId, sclId, sdaId
i2cPorts = (
(0, I2C0_SCL_M1, I2C0_SDA_M1),
(1, I2C1_SCL_M0, I2C1_SDA_M0),
(1, I2C1_SCL_M4, I2C1_SDA_M4),
(3, I2C3_SCL_M1, I2C3_SDA_M1),
(5, I2C5_SCL_M3, I2C5_SDA_M3),
(7, I2C7_SCL_M3, I2C7_SDA_M3),
(8, I2C8_SCL_M4, I2C8_SDA_M4),
)
# SPI
SPI0_MOSI_M2 = GPIO1_B2
SPI0_MISO_M2 = GPIO1_B1
SPI0_CLK_M2 = GPIO1_B3
SPI0_SCLK_M2 = SPI0_CLK_M2
SPI0_CS0_M2 = GPIO1_B4
SPI0_CS1_M2 = GPIO1_B5
SPI1_MOSI_M1 = GPIO3_B7
SPI1_MISO_M1 = GPIO3_C0
SPI1_CLK_M1 = GPIO3_C1
SPI1_SCLK_M1 = SPI1_CLK_M1
SPI1_CS0_M1 = GPIO3_C2
SPI1_CS1_M1 = GPIO3_C3
SPI3_MISO_M0 = GPIO4_C4
SPI3_MOSI_M0 = GPIO4_C5
SPI3_SCK_M0 = GPIO4_C6
SPI3_SCLK_M0 = SPI3_SCK_M0
SPI4_MISO_M0 = GPIO1_C0
SPI4_MOSI_M0 = GPIO1_C1
SPI4_SCK_M0 = GPIO1_C2
SPI4_SCLK_M0 = SPI4_SCK_M0
# ordered as spiId, sckId, mosiId, misoId
spiPorts = (
(0, SPI0_SCLK_M2, SPI0_MOSI_M2, SPI0_MISO_M2),
(1, SPI1_SCLK_M1, SPI1_MOSI_M1, SPI1_MISO_M1),
(3, SPI3_SCLK_M0, SPI3_MOSI_M0, SPI3_MISO_M0),
(4, SPI4_SCLK_M0, SPI4_MOSI_M0, SPI4_MISO_M0),
)
# PWM
PWM2_M1 = GPIO3_B1
PWM3_IR_M1 = GPIO3_B2
PWM5_M2 = GPIO4_C4
PWM6_M2 = GPIO4_C5
PWM7_IR_M3 = GPIO4_C6
PWM8_M0 = GPIO3_A7
PWM12_M0 = GPIO3_B5
PWM13_M0 = GPIO3_B6
PWM13_M2 = GPIO1_B7
PWM14_M0 = GPIO3_C2
PWM14_M1 = GPIO4_B2
PWM15_IR_M0 = GPIO3_C3
PWM15_IR_M1 = GPIO4_B3
PWM15_IR_M3 = GPIO1_D7
# SysFS pwm outputs, pwm channel and pin in first tuple
pwmOuts = (
((0, 2), PWM2_M1),
((0, 3), PWM3_IR_M1),
((0, 5), PWM5_M2),
((0, 6), PWM6_M2),
((0, 7), PWM7_IR_M3),
((0, 8), PWM8_M0),
((0, 12), PWM12_M0),
((0, 13), PWM13_M0),
((0, 13), PWM13_M2),
((0, 14), PWM14_M0),
((0, 14), PWM14_M1),
((0, 15), PWM15_IR_M0),
((0, 15), PWM15_IR_M1),
((0, 15), PWM15_IR_M3),
)
# SysFS analog inputs, Ordered as analog analogInId, device, and channel
ADC_IN0 = 0
analogIns = ((ADC_IN0, 0, 4),) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rockchip/rk3588/pin.py | pin.py |
"""A Pin class for use with Rockchip RK3399 and RK3399_T."""
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
# GPIOx_yz = x * 32 + y * 8 + z
# y: A -> 0, B -> 1, C -> 2, D -> 3
GPIO0_A0 = Pin((0, 0))
GPIO0_A1 = Pin((0, 1))
GPIO0_A2 = Pin((0, 2))
GPIO0_A3 = Pin((0, 3))
GPIO0_A4 = Pin((0, 4))
GPIO0_A5 = Pin((0, 5))
GPIO0_A6 = Pin((0, 6))
GPIO0_A7 = Pin((0, 7))
GPIO0_B0 = Pin((0, 8))
GPIO0_B1 = Pin((0, 9))
GPIO0_B2 = Pin((0, 10))
GPIO0_B3 = Pin((0, 11))
GPIO0_B4 = Pin((0, 12))
GPIO0_B5 = Pin((0, 13))
GPIO0_B6 = Pin((0, 14))
GPIO0_B7 = Pin((0, 15))
GPIO0_C0 = Pin((0, 16))
GPIO0_C1 = Pin((0, 17))
GPIO0_C2 = Pin((0, 18))
GPIO0_C3 = Pin((0, 19))
GPIO0_C4 = Pin((0, 20))
GPIO0_C5 = Pin((0, 21))
GPIO0_C6 = Pin((0, 22))
GPIO0_C7 = Pin((0, 23))
GPIO0_D0 = Pin((0, 24))
GPIO0_D1 = Pin((0, 25))
GPIO0_D2 = Pin((0, 26))
GPIO0_D3 = Pin((0, 27))
GPIO0_D4 = Pin((0, 28))
GPIO0_D5 = Pin((0, 29))
GPIO0_D6 = Pin((0, 30))
GPIO0_D7 = Pin((0, 31))
GPIO1_A0 = Pin((1, 0))
GPIO1_A1 = Pin((1, 1))
GPIO1_A2 = Pin((1, 2))
GPIO1_A3 = Pin((1, 3))
GPIO1_A4 = Pin((1, 4))
GPIO1_A5 = Pin((1, 5))
GPIO1_A6 = Pin((1, 6))
GPIO1_A7 = Pin((1, 7))
GPIO1_B0 = Pin((1, 8))
GPIO1_B1 = Pin((1, 9))
GPIO1_B2 = Pin((1, 10))
GPIO1_B3 = Pin((1, 11))
GPIO1_B4 = Pin((1, 12))
GPIO1_B5 = Pin((1, 13))
GPIO1_B6 = Pin((1, 14))
GPIO1_B7 = Pin((1, 15))
GPIO1_C0 = Pin((1, 16))
GPIO1_C1 = Pin((1, 17))
GPIO1_C2 = Pin((1, 18))
GPIO1_C3 = Pin((1, 19))
GPIO1_C4 = Pin((1, 20))
GPIO1_C5 = Pin((1, 21))
GPIO1_C6 = Pin((1, 22))
GPIO1_C7 = Pin((1, 23))
GPIO1_D0 = Pin((1, 24))
GPIO1_D1 = Pin((1, 25))
GPIO1_D2 = Pin((1, 26))
GPIO1_D3 = Pin((1, 27))
GPIO1_D4 = Pin((1, 28))
GPIO1_D5 = Pin((1, 29))
GPIO1_D6 = Pin((1, 30))
GPIO1_D7 = Pin((1, 31))
GPIO2_A0 = Pin((2, 0))
GPIO2_A1 = Pin((2, 1))
GPIO2_A2 = Pin((2, 2))
GPIO2_A3 = Pin((2, 3))
GPIO2_A4 = Pin((2, 4))
GPIO2_A5 = Pin((2, 5))
GPIO2_A6 = Pin((2, 6))
GPIO2_A7 = Pin((2, 7))
GPIO2_B0 = Pin((2, 8))
GPIO2_B1 = Pin((2, 9))
GPIO2_B2 = Pin((2, 10))
GPIO2_B3 = Pin((2, 11))
GPIO2_B4 = Pin((2, 12))
GPIO2_B5 = Pin((2, 13))
GPIO2_B6 = Pin((2, 14))
GPIO2_B7 = Pin((2, 15))
GPIO2_C0 = Pin((2, 16))
GPIO2_C1 = Pin((2, 17))
GPIO2_C2 = Pin((2, 18))
GPIO2_C3 = Pin((2, 19))
GPIO2_C4 = Pin((2, 20))
GPIO2_C5 = Pin((2, 21))
GPIO2_C6 = Pin((2, 22))
GPIO2_C7 = Pin((2, 23))
GPIO2_D0 = Pin((2, 24))
GPIO2_D1 = Pin((2, 25))
GPIO2_D2 = Pin((2, 26))
GPIO2_D3 = Pin((2, 27))
GPIO2_D4 = Pin((2, 28))
GPIO2_D5 = Pin((2, 29))
GPIO2_D6 = Pin((2, 30))
GPIO2_D7 = Pin((2, 31))
GPIO3_A0 = Pin((3, 0))
GPIO3_A1 = Pin((3, 1))
GPIO3_A2 = Pin((3, 2))
GPIO3_A3 = Pin((3, 3))
GPIO3_A4 = Pin((3, 4))
GPIO3_A5 = Pin((3, 5))
GPIO3_A6 = Pin((3, 6))
GPIO3_A7 = Pin((3, 7))
GPIO3_B0 = Pin((3, 8))
GPIO3_B1 = Pin((3, 9))
GPIO3_B2 = Pin((3, 10))
GPIO3_B3 = Pin((3, 11))
GPIO3_B4 = Pin((3, 12))
GPIO3_B5 = Pin((3, 13))
GPIO3_B6 = Pin((3, 14))
GPIO3_B7 = Pin((3, 15))
GPIO3_C0 = Pin((3, 16))
GPIO3_C1 = Pin((3, 17))
GPIO3_C2 = Pin((3, 18))
GPIO3_C3 = Pin((3, 19))
GPIO3_C4 = Pin((3, 20))
GPIO3_C5 = Pin((3, 21))
GPIO3_C6 = Pin((3, 22))
GPIO3_C7 = Pin((3, 23))
GPIO3_D0 = Pin((3, 24))
GPIO3_D1 = Pin((3, 25))
GPIO3_D2 = Pin((3, 26))
GPIO3_D3 = Pin((3, 27))
GPIO3_D4 = Pin((3, 28))
GPIO3_D5 = Pin((3, 29))
GPIO3_D6 = Pin((3, 30))
GPIO3_D7 = Pin((3, 31))
GPIO4_A0 = Pin((4, 0))
GPIO4_A1 = Pin((4, 1))
GPIO4_A2 = Pin((4, 2))
GPIO4_A3 = Pin((4, 3))
GPIO4_A4 = Pin((4, 4))
GPIO4_A5 = Pin((4, 5))
GPIO4_A6 = Pin((4, 6))
GPIO4_A7 = Pin((4, 7))
GPIO4_B0 = Pin((4, 8))
GPIO4_B1 = Pin((4, 9))
GPIO4_B2 = Pin((4, 10))
GPIO4_B3 = Pin((4, 11))
GPIO4_B4 = Pin((4, 12))
GPIO4_B5 = Pin((4, 13))
GPIO4_B6 = Pin((4, 14))
GPIO4_B7 = Pin((4, 15))
GPIO4_C0 = Pin((4, 16))
GPIO4_C1 = Pin((4, 17))
GPIO4_C2 = Pin((4, 18))
GPIO4_C3 = Pin((4, 19))
GPIO4_C4 = Pin((4, 20))
GPIO4_C5 = Pin((4, 21))
GPIO4_C6 = Pin((4, 22))
GPIO4_C7 = Pin((4, 23))
GPIO4_D0 = Pin((4, 24))
GPIO4_D1 = Pin((4, 25))
GPIO4_D2 = Pin((4, 26))
GPIO4_D3 = Pin((4, 27))
GPIO4_D4 = Pin((4, 28))
GPIO4_D5 = Pin((4, 29))
GPIO4_D6 = Pin((4, 30))
GPIO4_D7 = Pin((4, 31))
ADC_IN0 = 1
# I2C
I2C2_SDA = GPIO2_A0
I2C2_SCL = GPIO2_A1
I2C3_SDA = GPIO4_C0
I2C3_SCL = GPIO4_C1
I2C6_SDA = GPIO2_B1
I2C6_SCL = GPIO2_B2
I2C7_SDA = GPIO2_A7
I2C7_SCL = GPIO2_B0
I2C8_SDA = GPIO1_C4
I2C8_SCL = GPIO1_C5
# SPI
SPI1_CS = GPIO1_B2
SPI1_SCLK = GPIO1_B1
SPI1_MISO = GPIO1_A7
SPI1_MOSI = GPIO1_B0
SPI2_CS = GPIO2_B4
SPI2_SCLK = GPIO2_B3
SPI2_MISO = GPIO2_B1
SPI2_MOSI = GPIO2_B2
# UART
UART2_TX = GPIO4_C4
UART2_RX = GPIO4_C3
UART4_TX = GPIO1_B0
UART4_RX = GPIO1_A7
# PWM
PWM0 = GPIO4_C2
PWM1 = GPIO4_C6
# ordered as i2cId, SCL, SDA
i2cPorts = (
(2, I2C2_SCL, I2C2_SDA),
(6, I2C6_SCL, I2C6_SDA),
(7, I2C7_SCL, I2C7_SDA),
)
# ordered as spiId, sckId, mosiId, misoId
spiPorts = (
(1, SPI1_SCLK, SPI1_MOSI, SPI1_MISO),
(2, SPI2_SCLK, SPI2_MOSI, SPI2_MISO),
)
# SysFS pwm outputs, pwm channel and pin in first tuple
pwmOuts = (
((0, 0), PWM0),
((0, 0), PWM1),
)
# SysFS analog inputs, Ordered as analog analogInId, device, and channel
analogIns = ((ADC_IN0, 0, 0),) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rockchip/rk3399/pin.py | pin.py |
"""Helper class for use with RP2040 running u2if firmware"""
# https://github.com/execuc/u2if
import os
import time
import hid
# Use to set delay between reset and device reopen. if negative, don't reset at all
RP2040_U2IF_RESET_DELAY = float(os.environ.get("RP2040_U2IF_RESET_DELAY", 1))
# pylint: disable=import-outside-toplevel,too-many-branches,too-many-statements
# pylint: disable=too-many-arguments,too-many-function-args, too-many-public-methods
class RP2040_u2if:
"""Helper class for use with RP2040 running u2if firmware"""
# MISC
RESP_OK = 0x01
SYS_RESET = 0x10
# GPIO
GPIO_INIT_PIN = 0x20
GPIO_SET_VALUE = 0x21
GPIO_GET_VALUE = 0x22
# ADC
ADC_INIT_PIN = 0x40
ADC_GET_VALUE = 0x41
# I2C
I2C0_INIT = 0x80
I2C0_DEINIT = 0x81
I2C0_WRITE = 0x82
I2C0_READ = 0x83
I2C0_WRITE_FROM_UART = 0x84
I2C1_INIT = I2C0_INIT + 0x10
I2C1_DEINIT = I2C0_DEINIT + 0x10
I2C1_WRITE = I2C0_WRITE + 0x10
I2C1_READ = I2C0_READ + 0x10
I2C1_WRITE_FROM_UART = I2C0_WRITE_FROM_UART + 0x10
# SPI
SPI0_INIT = 0x60
SPI0_DEINIT = 0x61
SPI0_WRITE = 0x62
SPI0_READ = 0x63
SPI0_WRITE_FROM_UART = 0x64
SPI1_INIT = SPI0_INIT + 0x10
SPI1_DEINIT = SPI0_DEINIT + 0x10
SPI1_WRITE = SPI0_WRITE + 0x10
SPI1_READ = SPI0_READ + 0x10
SPI1_WRITE_FROM_UART = SPI0_WRITE_FROM_UART + 0x10
# WS2812B (LED)
WS2812B_INIT = 0xA0
WS2812B_DEINIT = 0xA1
WS2812B_WRITE = 0xA2
# PWM
PWM_INIT_PIN = 0x30
PWM_DEINIT_PIN = 0x31
PWM_SET_FREQ = 0x32
PWM_GET_FREQ = 0x33
PWM_SET_DUTY_U16 = 0x34
PWM_GET_DUTY_U16 = 0x35
PWM_SET_DUTY_NS = 0x36
PWM_GET_DUTY_NS = 0x37
def __init__(self):
self._vid = None
self._pid = None
self._hid = None
self._opened = False
self._i2c_index = None
self._spi_index = None
self._serial = None
self._neopixel_initialized = False
self._uart_rx_buffer = None
def _hid_xfer(self, report, response=True):
"""Perform HID Transfer"""
# first byte is report ID, which =0
# remaing bytes = 64 byte report data
# https://github.com/libusb/hidapi/blob/083223e77952e1ef57e6b77796536a3359c1b2a3/hidapi/hidapi.h#L185
self._hid.write(b"\0" + report + b"\0" * (64 - len(report)))
if response:
# return is 64 byte response report
return self._hid.read(64)
return None
def _reset(self):
self._hid_xfer(bytes([self.SYS_RESET]), False)
self._hid.close()
time.sleep(RP2040_U2IF_RESET_DELAY)
start = time.monotonic()
while time.monotonic() - start < 5:
try:
self._hid.open(self._vid, self._pid)
except OSError:
time.sleep(0.1)
continue
return
raise OSError("RP2040 u2if open error.")
# ----------------------------------------------------------------
# MISC
# ----------------------------------------------------------------
def open(self, vid, pid):
"""Open HID interface for given USB VID and PID."""
if self._opened:
return
self._vid = vid
self._pid = pid
self._hid = hid.device()
self._hid.open(self._vid, self._pid)
if RP2040_U2IF_RESET_DELAY >= 0:
self._reset()
self._opened = True
# ----------------------------------------------------------------
# GPIO
# ----------------------------------------------------------------
def gpio_init_pin(self, pin_id, direction, pull):
"""Configure GPIO Pin."""
self._hid_xfer(
bytes(
[
self.GPIO_INIT_PIN,
pin_id,
direction,
pull,
]
)
)
def gpio_set_pin(self, pin_id, value):
"""Set Current GPIO Pin Value"""
self._hid_xfer(
bytes(
[
self.GPIO_SET_VALUE,
pin_id,
int(value),
]
)
)
def gpio_get_pin(self, pin_id):
"""Get Current GPIO Pin Value"""
resp = self._hid_xfer(
bytes(
[
self.GPIO_GET_VALUE,
pin_id,
]
),
True,
)
return resp[3] != 0x00
# ----------------------------------------------------------------
# ADC
# ----------------------------------------------------------------
def adc_init_pin(self, pin_id):
"""Configure ADC Pin."""
self._hid_xfer(
bytes(
[
self.ADC_INIT_PIN,
pin_id,
]
)
)
def adc_get_value(self, pin_id):
"""Get ADC value for pin."""
resp = self._hid_xfer(
bytes(
[
self.ADC_GET_VALUE,
pin_id,
]
),
True,
)
return int.from_bytes(resp[3 : 3 + 2], byteorder="little")
# ----------------------------------------------------------------
# I2C
# ----------------------------------------------------------------
def i2c_configure(self, baudrate, pullup=False):
"""Configure I2C."""
if self._i2c_index is None:
raise RuntimeError("I2C bus not initialized.")
resp = self._hid_xfer(
bytes(
[
self.I2C0_INIT if self._i2c_index == 0 else self.I2C1_INIT,
0x00 if not pullup else 0x01,
]
)
+ baudrate.to_bytes(4, byteorder="little"),
True,
)
if resp[1] != self.RESP_OK:
raise RuntimeError("I2C init error.")
def i2c_set_port(self, index):
"""Set I2C port."""
if index not in (0, 1):
raise ValueError("I2C index must be 0 or 1.")
self._i2c_index = index
def _i2c_write(self, address, buffer, start=0, end=None, stop=True):
"""Write data from the buffer to an address"""
if self._i2c_index is None:
raise RuntimeError("I2C bus not initialized.")
end = end if end else len(buffer)
write_cmd = self.I2C0_WRITE if self._i2c_index == 0 else self.I2C1_WRITE
stop_flag = 0x01 if stop else 0x00
while (end - start) > 0:
remain_bytes = end - start
chunk = min(remain_bytes, 64 - 7)
resp = self._hid_xfer(
bytes([write_cmd, address, stop_flag])
+ remain_bytes.to_bytes(4, byteorder="little")
+ buffer[start : (start + chunk)],
True,
)
if resp[1] != self.RESP_OK:
raise RuntimeError("I2C write error")
start += chunk
def _i2c_read(self, address, buffer, start=0, end=None):
"""Read data from an address and into the buffer"""
# TODO: support chunkified reads
if self._i2c_index is None:
raise RuntimeError("I2C bus not initialized.")
end = end if end else len(buffer)
read_cmd = self.I2C0_READ if self._i2c_index == 0 else self.I2C1_READ
stop_flag = 0x01 # always stop
read_size = end - start
resp = self._hid_xfer(bytes([read_cmd, address, stop_flag, read_size]), True)
if resp[1] != self.RESP_OK:
raise RuntimeError("I2C write error")
# move into buffer
for i in range(read_size):
buffer[start + i] = resp[i + 2]
def i2c_writeto(self, address, buffer, *, start=0, end=None):
"""Write data from the buffer to an address"""
self._i2c_write(address, buffer, start, end)
def i2c_readfrom_into(self, address, buffer, *, start=0, end=None):
"""Read data from an address and into the buffer"""
self._i2c_read(address, buffer, start, end)
def i2c_writeto_then_readfrom(
self,
address,
out_buffer,
in_buffer,
*,
out_start=0,
out_end=None,
in_start=0,
in_end=None,
):
"""Write data from buffer_out to an address and then
read data from an address and into buffer_in
"""
self._i2c_write(address, out_buffer, out_start, out_end, False)
self._i2c_read(address, in_buffer, in_start, in_end)
def i2c_scan(self, *, start=0, end=0x79):
"""Perform an I2C Device Scan"""
if self._i2c_index is None:
raise RuntimeError("I2C bus not initialized.")
found = []
for addr in range(start, end + 1):
# try a write
try:
self.i2c_writeto(addr, b"\x00\x00\x00")
except RuntimeError: # no reply!
continue
# store if success
found.append(addr)
return found
# ----------------------------------------------------------------
# SPI
# ----------------------------------------------------------------
def spi_configure(self, baudrate):
"""Configure SPI."""
if self._spi_index is None:
raise RuntimeError("SPI bus not initialized.")
resp = self._hid_xfer(
bytes(
[
self.SPI0_INIT if self._spi_index == 0 else self.SPI1_INIT,
0x00, # mode, not yet implemented
]
)
+ baudrate.to_bytes(4, byteorder="little"),
True,
)
if resp[1] != self.RESP_OK:
raise RuntimeError("SPI init error.")
def spi_set_port(self, index):
"""Set SPI port."""
if index not in (0, 1):
raise ValueError("SPI index must be 0 or 1.")
self._spi_index = index
def spi_write(self, buffer, *, start=0, end=None):
"""SPI write."""
if self._spi_index is None:
raise RuntimeError("SPI bus not initialized.")
end = end if end else len(buffer)
write_cmd = self.SPI0_WRITE if self._spi_index == 0 else self.SPI1_WRITE
while (end - start) > 0:
remain_bytes = end - start
chunk = min(remain_bytes, 64 - 3)
resp = self._hid_xfer(
bytes([write_cmd, chunk]) + buffer[start : (start + chunk)], True
)
if resp[1] != self.RESP_OK:
raise RuntimeError("SPI write error")
start += chunk
def spi_readinto(self, buffer, *, start=0, end=None, write_value=0):
"""SPI readinto."""
if self._spi_index is None:
raise RuntimeError("SPI bus not initialized.")
end = end if end else len(buffer)
read_cmd = self.SPI0_READ if self._spi_index == 0 else self.SPI1_READ
read_size = end - start
resp = self._hid_xfer(bytes([read_cmd, write_value, read_size]), True)
if resp[1] != self.RESP_OK:
raise RuntimeError("SPI write error")
# move into buffer
for i in range(read_size):
buffer[start + i] = resp[i + 2]
def spi_write_readinto(
self,
buffer_out,
buffer_in,
*,
out_start=0,
out_end=None,
in_start=0,
in_end=None,
):
"""SPI write and readinto."""
raise NotImplementedError("SPI write_readinto Not implemented")
# ----------------------------------------------------------------
# NEOPIXEL
# ----------------------------------------------------------------
def neopixel_write(self, gpio, buf):
"""NeoPixel write."""
# open serial (data is sent over this)
if self._serial is None:
import serial
import serial.tools.list_ports
ports = serial.tools.list_ports.comports()
for port in ports:
if port.vid == self._vid and port.pid == self._pid:
self._serial = serial.Serial(port.device)
break
if self._serial is None:
raise RuntimeError("Could not find Pico com port.")
# init
if not self._neopixel_initialized:
# deinit any current setup
# pylint: disable=protected-access
self._hid_xfer(bytes([self.WS2812B_DEINIT]))
resp = self._hid_xfer(
bytes(
[
self.WS2812B_INIT,
gpio._pin.id,
]
),
True,
)
if resp[1] != self.RESP_OK:
raise RuntimeError("Neopixel init error")
self._neopixel_initialized = True
self._serial.reset_output_buffer()
# write
# command is done over HID
remain_bytes = len(buf)
resp = self._hid_xfer(
bytes([self.WS2812B_WRITE]) + remain_bytes.to_bytes(4, byteorder="little"),
True,
)
if resp[1] != self.RESP_OK:
# pylint: disable=no-else-raise
if resp[2] == 0x01:
raise RuntimeError(
"Neopixel write error : too many pixel for the firmware."
)
elif resp[2] == 0x02:
raise RuntimeError(
"Neopixel write error : transfer already in progress."
)
else:
raise RuntimeError("Neopixel write error.")
# buffer is sent over serial
self._serial.write(buf)
# hack (see u2if)
if len(buf) % 64 == 0:
self._serial.write([0])
self._serial.flush()
# polling loop to wait for write complete?
time.sleep(0.1)
resp = self._hid.read(64)
while resp[0] != self.WS2812B_WRITE:
resp = self._hid.read(64)
if resp[1] != self.RESP_OK:
raise RuntimeError("Neopixel write (flush) error.")
# ----------------------------------------------------------------
# PWM
# ----------------------------------------------------------------
# pylint: disable=unused-argument
def pwm_configure(self, pin, frequency=500, duty_cycle=0, variable_frequency=False):
"""Configure PWM."""
self.pwm_deinit(pin)
resp = self._hid_xfer(bytes([self.PWM_INIT_PIN, pin.id]), True)
if resp[1] != self.RESP_OK:
raise RuntimeError("PWM init error.")
self.pwm_set_frequency(pin, frequency)
self.pwm_set_duty_cycle(pin, duty_cycle)
def pwm_deinit(self, pin):
"""Deinit PWM."""
self._hid_xfer(bytes([self.PWM_DEINIT_PIN, pin.id]))
def pwm_get_frequency(self, pin):
"""PWM get freq."""
resp = self._hid_xfer(bytes([self.PWM_GET_FREQ, pin.id]), True)
if resp[1] != self.RESP_OK:
raise RuntimeError("PWM get frequency error.")
return int.from_bytes(resp[3 : 3 + 4], byteorder="little")
def pwm_set_frequency(self, pin, frequency):
"""PWM set freq."""
resp = self._hid_xfer(
bytes([self.PWM_SET_FREQ, pin.id])
+ frequency.to_bytes(4, byteorder="little"),
True,
)
if resp[1] != self.RESP_OK:
# pylint: disable=no-else-raise
if resp[3] == 0x01:
raise RuntimeError("PWM different frequency on same slice.")
elif resp[3] == 0x02:
raise RuntimeError("PWM frequency too low.")
elif resp[3] == 0x03:
raise RuntimeError("PWM frequency too high.")
else:
raise RuntimeError("PWM frequency error.")
def pwm_get_duty_cycle(self, pin):
"""PWM get duty cycle."""
resp = self._hid_xfer(bytes([self.PWM_GET_DUTY_U16, pin.id]), True)
if resp[1] != self.RESP_OK:
raise RuntimeError("PWM get duty cycle error.")
return int.from_bytes(resp[3 : 3 + 4], byteorder="little")
def pwm_set_duty_cycle(self, pin, duty_cycle):
"""PWM set duty cycle."""
resp = self._hid_xfer(
bytes([self.PWM_SET_DUTY_U16, pin.id])
+ duty_cycle.to_bytes(2, byteorder="little"),
True,
)
if resp[1] != self.RESP_OK:
raise RuntimeError("PWM set duty cycle error.")
rp2040_u2if = RP2040_u2if() | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rp2040_u2if/rp2040_u2if.py | rp2040_u2if.py |
"""Generic RP2040 pin names"""
from .rp2040_u2if import rp2040_u2if
class Pin:
"""A basic Pin class for use with RP2040 with u2if firmware."""
# pin modes
IN = 0
OUT = 1
# pin values
LOW = 0
HIGH = 1
# pin pulls
PULL_NONE = 0
PULL_UP = 1
PULL_DOWN = 2
def __init__(self, pin_id=None):
self.id = pin_id
self._mode = None
self._pull = None
# pylint:disable = no-self-use
def _u2if_open_hid(self, vid, pid):
rp2040_u2if.open(vid, pid)
def init(self, mode=IN, pull=PULL_NONE):
"""Initialize the Pin"""
pull = Pin.PULL_NONE if pull is None else pull
if self.id is None:
raise RuntimeError("Can not init a None type pin.")
if mode not in (Pin.IN, Pin.OUT):
raise ValueError("Incorrect mode value.")
if pull not in (Pin.PULL_NONE, Pin.PULL_UP, Pin.PULL_DOWN):
raise ValueError("Incorrect pull value.")
rp2040_u2if.gpio_init_pin(self.id, mode, pull)
self._mode = mode
self._pull = pull
def value(self, val=None):
"""Set or return the Pin Value"""
# Digital In / Out
if self._mode in (Pin.IN, Pin.OUT):
# digital read
if val is None:
return rp2040_u2if.gpio_get_pin(self.id)
# digital write
if val in (Pin.LOW, Pin.HIGH):
rp2040_u2if.gpio_set_pin(self.id, val)
return None
# nope
raise ValueError("Invalid value for pin.")
raise RuntimeError(
"No action for mode {} with value {}".format(self._mode, val)
)
# create pin instances for each pin
GP0 = Pin(0)
GP1 = Pin(1)
GP2 = Pin(2)
GP3 = Pin(3)
GP4 = Pin(4)
GP5 = Pin(5)
GP6 = Pin(6)
GP7 = Pin(7)
GP8 = Pin(8)
GP9 = Pin(9)
GP10 = Pin(10)
GP11 = Pin(11)
GP12 = Pin(12)
GP13 = Pin(13)
GP14 = Pin(14)
GP15 = Pin(15)
GP16 = Pin(16)
GP17 = Pin(17)
GP18 = Pin(18)
GP19 = Pin(19)
GP20 = Pin(20)
GP21 = Pin(21)
GP22 = Pin(22)
GP23 = Pin(23)
GP24 = Pin(24)
GP25 = Pin(25)
GP26 = Pin(26)
GP27 = Pin(27)
GP28 = Pin(28)
GP29 = Pin(29) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rp2040_u2if/pin.py | pin.py |
"""I2C Classes for RP2040s with u2if firmware"""
from .rp2040_u2if import rp2040_u2if
class I2C:
"""I2C Base Class for RP2040 u2if"""
def __init__(self, index, *, frequency=100000):
self._index = index
rp2040_u2if.i2c_set_port(self._index)
rp2040_u2if.i2c_configure(frequency)
def scan(self):
"""Perform an I2C Device Scan"""
rp2040_u2if.i2c_set_port(self._index)
return rp2040_u2if.i2c_scan()
# pylint: disable=unused-argument
def writeto(self, address, buffer, *, start=0, end=None, stop=True):
"""Write data from the buffer to an address"""
rp2040_u2if.i2c_set_port(self._index)
rp2040_u2if.i2c_writeto(address, buffer, start=start, end=end)
def readfrom_into(self, address, buffer, *, start=0, end=None, stop=True):
"""Read data from an address and into the buffer"""
rp2040_u2if.i2c_set_port(self._index)
rp2040_u2if.i2c_readfrom_into(address, buffer, start=start, end=end)
def writeto_then_readfrom(
self,
address,
buffer_out,
buffer_in,
*,
out_start=0,
out_end=None,
in_start=0,
in_end=None,
stop=False,
):
"""Write data from buffer_out to an address and then
read data from an address and into buffer_in
"""
rp2040_u2if.i2c_set_port(self._index)
rp2040_u2if.i2c_writeto_then_readfrom(
address,
buffer_out,
buffer_in,
out_start=out_start,
out_end=out_end,
in_start=in_start,
in_end=in_end,
)
# pylint: enable=unused-argument
class I2C_Pico(I2C):
"""I2C Class for Pico u2if"""
def __init__(self, scl, sda, *, frequency=100000):
index = None
if scl.id == 5 and sda.id == 4:
index = 0
if scl.id == 15 and sda.id == 14:
index = 1
if index is None:
raise ValueError("I2C not found on specified pins.")
self._index = index
super().__init__(index, frequency=frequency)
class I2C_Feather(I2C):
"""I2C Class for Feather u2if"""
def __init__(self, scl, sda, *, frequency=100000):
index = None
if scl.id == 3 and sda.id == 2:
index = 1
if index is None:
raise ValueError("I2C not found on specified pins.")
self._index = index
super().__init__(index, frequency=frequency)
class I2C_Feather_CAN(I2C):
"""I2C Class for Feather EPD u2if"""
def __init__(self, scl, sda, *, frequency=100000):
index = None
if scl.id == 3 and sda.id == 2:
index = 1
if index is None:
raise ValueError("I2C not found on specified pins.")
self._index = index
super().__init__(index, frequency=frequency)
class I2C_Feather_EPD(I2C):
"""I2C Class for Feather EPD u2if"""
def __init__(self, scl, sda, *, frequency=100000):
index = None
if scl.id == 3 and sda.id == 2:
index = 1
if index is None:
raise ValueError("I2C not found on specified pins.")
self._index = index
super().__init__(index, frequency=frequency)
class I2C_Feather_RFM(I2C):
"""I2C Class for Feather EPD u2if"""
def __init__(self, scl, sda, *, frequency=100000):
index = None
if scl.id == 3 and sda.id == 2:
index = 1
if index is None:
raise ValueError("I2C not found on specified pins.")
self._index = index
super().__init__(index, frequency=frequency)
class I2C_QTPY(I2C):
"""I2C Class for QT Py 2if"""
def __init__(self, scl, sda, *, frequency=100000):
index = None
if scl.id == 25 and sda.id == 24:
index = 0
if scl.id == 23 and sda.id == 22:
index = 1
if index is None:
raise ValueError("I2C not found on specified pins.")
self._index = index
super().__init__(index, frequency=frequency)
class I2C_ItsyBitsy(I2C):
"""I2C Class for ItsyBitsy u2if"""
def __init__(self, scl, sda, *, frequency=100000):
index = None
if scl.id == 3 and sda.id == 2:
index = 1
if index is None:
raise ValueError("I2C not found on specified pins.")
self._index = index
super().__init__(index, frequency=frequency)
class I2C_MacroPad(I2C):
"""I2C Class for MacroPad u2if"""
def __init__(self, scl, sda, *, frequency=100000):
index = None
if scl.id == 21 and sda.id == 20:
index = 0
if index is None:
raise ValueError("I2C not found on specified pins.")
self._index = index
super().__init__(index, frequency=frequency)
class I2C_QT2040_Trinkey(I2C):
"""I2C Class for QT2040 Trinkey u2if"""
def __init__(self, scl, sda, *, frequency=100000):
index = None
if scl.id == 17 and sda.id == 16:
index = 0
if index is None:
raise ValueError("I2C not found on specified pins.")
self._index = index
super().__init__(index, frequency=frequency)
class I2C_KB2040(I2C):
"""I2C Class for KB2040 u2if"""
def __init__(self, scl, sda, *, frequency=100000):
index = None
if scl.id == 13 and sda.id == 12:
index = 0
if index is None:
raise ValueError("I2C not found on specified pins.")
self._index = index
super().__init__(index, frequency=frequency) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rp2040_u2if/i2c.py | i2c.py |
"""SPI Classes for RP2040s with u2if firmware"""
from .rp2040_u2if import rp2040_u2if
# pylint: disable=protected-access, no-self-use
class SPI:
"""SPI Base Class for RP2040 u2if"""
MSB = 0
def __init__(self, index, *, baudrate=100000):
self._index = index
self._frequency = baudrate
rp2040_u2if.spi_set_port(self._index)
rp2040_u2if.spi_configure(self._frequency)
# pylint: disable=too-many-arguments,unused-argument
def init(
self,
baudrate=1000000,
polarity=0,
phase=0,
bits=8,
firstbit=MSB,
sck=None,
mosi=None,
miso=None,
):
"""Initialize the Port"""
self._frequency = baudrate
rp2040_u2if.spi_set_port(self._index)
rp2040_u2if.spi_configure(self._frequency)
# pylint: enable=too-many-arguments
@property
def frequency(self):
"""Return the current frequency"""
return self._frequency
def write(self, buf, start=0, end=None):
"""Write data from the buffer to SPI"""
rp2040_u2if.spi_write(buf, start=start, end=end)
def readinto(self, buf, start=0, end=None, write_value=0):
"""Read data from SPI and into the buffer"""
rp2040_u2if.spi_readinto(buf, start=start, end=end, write_value=write_value)
# pylint: disable=too-many-arguments
def write_readinto(
self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
):
"""Perform a half-duplex write from buffer_out and then
read data into buffer_in
"""
rp2040_u2if.spi_write_readinto(
buffer_out,
buffer_in,
out_start=out_start,
out_end=out_end,
in_start=in_start,
in_end=in_end,
)
# pylint: enable=too-many-arguments
class SPI_Pico(SPI):
"""SPI Class for Pico u2if"""
def __init__(self, clock, *, baudrate=100000):
index = None
if clock.id == 18:
index = 0
if clock.id == 10:
index = 1
if index is None:
raise ValueError("No SPI port on specified pin.")
super().__init__(index, baudrate=baudrate)
class SPI_Feather(SPI):
"""SPI Class for Feather u2if"""
def __init__(self, clock, *, baudrate=100000):
index = None
if clock.id == 18:
index = 0
if index is None:
raise ValueError("No SPI port on specified pin.")
super().__init__(index, baudrate=baudrate)
class SPI_Feather_CAN(SPI):
"""SPI Class for Feather EPD u2if"""
def __init__(self, clock, *, baudrate=100000):
index = None
if clock.id == 14:
index = 1
if index is None:
raise ValueError("No SPI port on specified pin.")
super().__init__(index, baudrate=baudrate)
class SPI_Feather_EPD(SPI):
"""SPI Class for Feather EPD u2if"""
def __init__(self, clock, *, baudrate=100000):
index = None
if clock.id == 22:
index = 0
if clock.id == 14:
index = 1
if index is None:
raise ValueError("No SPI port on specified pin.")
super().__init__(index, baudrate=baudrate)
class SPI_Feather_RFM(SPI):
"""SPI Class for Feather EPD u2if"""
def __init__(self, clock, *, baudrate=100000):
index = None
if clock.id == 14:
index = 1
if index is None:
raise ValueError("No SPI port on specified pin.")
super().__init__(index, baudrate=baudrate)
class SPI_QTPY(SPI):
"""SPI Class for QT Py u2if"""
def __init__(self, clock, *, baudrate=100000):
index = None
if clock.id == 6:
index = 0
if index is None:
raise ValueError("No SPI port on specified pin.")
super().__init__(index, baudrate=baudrate)
class SPI_ItsyBitsy(SPI):
"""SPI Class for ItsyBitsy u2if"""
def __init__(self, clock, *, baudrate=100000):
index = None
if clock.id == 18:
index = 0
if index is None:
raise ValueError("No SPI port on specified pin.")
super().__init__(index, baudrate=baudrate)
class SPI_MacroPad(SPI):
"""SPI Class for MacroPad u2if"""
def __init__(self, clock, *, baudrate=100000):
index = None
if clock.id == 26:
index = 1
if index is None:
raise ValueError("No SPI port on specified pin.")
super().__init__(index, baudrate=baudrate)
class SPI_KB2040(SPI):
"""SPI Class for KB2040 u2if"""
def __init__(self, clock, *, baudrate=100000):
index = None
if clock.id == 18:
index = 0
if index is None:
raise ValueError("No SPI port on specified pin.")
super().__init__(index, baudrate=baudrate) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rp2040_u2if/spi.py | spi.py |
"""PWMOut Class for NXP LPC4330"""
from greatfet import GreatFET
try:
from microcontroller.pin import pwmOuts
except ImportError:
raise RuntimeError("No PWM outputs defined for this board") from ImportError
# pylint: disable=unnecessary-pass
class PWMError(IOError):
"""Base class for PWM errors."""
pass
# pylint: enable=unnecessary-pass
class PWMOut:
"""Pulse Width Modulation Output Class"""
MAX_CYCLE_LEVEL = 1024
def __init__(self, pin, *, frequency=750, duty_cycle=0, variable_frequency=False):
"""This class makes use of the GreatFET One's Pattern Generator to create a
Simulated Pulse width modulation. The way that the Pattern Generator works is that
takes a pattern in the form of bytes and will repeat the output. The trick to simulate
PWM is to generate the correct byte pattern for the correct channel.
Args:
pin (Pin): CircuitPython Pin object to output to
duty_cycle (int) : The fraction of each pulse which is high. 16-bit
frequency (int) : target frequency in Hertz (32-bit)
Returns:
PWMOut: PWMOut object.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if `channel` or `pin` types are invalid.
ValueError: if PWM channel does not exist.
"""
self._gf = GreatFET()
if variable_frequency:
raise NotImplementedError("Variable Frequency is not currently supported.")
self._pattern = None
self._channel = None
self._enable = False
self._frequency = 500
self._duty_cycle = 0
self._open(pin, duty_cycle, frequency)
def __enter__(self):
return self
def __exit__(self, t, value, traceback):
self.deinit()
def _open(self, pin, duty=0, freq=500):
self._channel = None
for pwmpair in pwmOuts:
if pwmpair[1] == pin:
self._channel = pwmpair[0]
self._pin = pin
if self._channel is None:
raise RuntimeError("No PWM channel found for this Pin")
# set duty
self.duty_cycle = duty
# set frequency
self.frequency = freq
self._set_enabled(True)
def deinit(self):
"""Deinit the GreatFET One PWM."""
# pylint: disable=broad-except
try:
if self._channel is not None:
# self.duty_cycle = 0
self._set_enabled(False)
except Exception as e:
# due to a race condition for which I have not yet been
# able to find the root cause, deinit() often fails
# but it does not effect future usage of the pwm pin
print(
"warning: failed to deinitialize pwm pin {0} due to: {1}\n".format(
self._channel, type(e).__name__
)
)
finally:
self._pattern = None
self._channel = None
# pylint: enable=broad-except
def _is_deinited(self):
if self._pattern is None:
raise ValueError(
"Object has been deinitialize and can no longer "
"be used. Create a new object."
)
# Mutable properties
def _get_period(self):
return 1.0 / self._get_frequency()
def _set_period(self, period):
"""Get or set the PWM's output period in seconds.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
:type: int, float
"""
if not isinstance(period, (int, float)):
raise TypeError("Invalid period type, should be int or float.")
self._set_frequency(1.0 / period)
period = property(_get_period, _set_period)
def _get_duty_cycle(self):
"""Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
ValueError: if value is out of bounds of 0.0 to 1.0.
:type: int, float
"""
return self._duty_cycle
def _set_duty_cycle(self, duty_cycle):
if not isinstance(duty_cycle, (int, float)):
raise TypeError("Invalid duty cycle type, should be int or float.")
# convert from 16-bit
if isinstance(duty_cycle, int):
duty_cycle /= 65535.0
if not 0.0 <= duty_cycle <= 1.0:
raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
# Generate a pattern for 1024 samples of the duty cycle
pattern = [(1 << self._channel)] * round(PWMOut.MAX_CYCLE_LEVEL * duty_cycle)
pattern += [(0 << self._channel)] * round(
PWMOut.MAX_CYCLE_LEVEL * (1.0 - duty_cycle)
)
self._pattern = pattern
self._duty_cycle = duty_cycle
if self._enable:
self._set_enabled(True)
duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
def _get_frequency(self):
return self._frequency
def _set_frequency(self, frequency):
"""Get or set the PWM's output frequency in Hertz.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
:type: int, float
"""
if not isinstance(frequency, (int, float)):
raise TypeError("Invalid frequency type, should be int or float.")
# We are sending 1024 samples per second already
self._gf.pattern_generator.set_sample_rate(frequency * len(self._pattern))
self._frequency = frequency
frequency = property(_get_frequency, _set_frequency)
def _get_enabled(self):
enabled = self._enable
if enabled == "1":
return True
if enabled == "0":
return False
raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
def _set_enabled(self, value):
"""Get or set the PWM's output enabled state.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not bool.
:type: bool
"""
if not isinstance(value, bool):
raise TypeError("Invalid enabled type, should be string.")
self._enable = value
if self._gf:
if self._enable:
if self._pattern:
self._gf.pattern_generator.scan_out_pattern(self._pattern)
else:
self._gf.pattern_generator.stop() | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/nxp_lpc4330/pwmout.py | pwmout.py |
"""NXP LPC4330 pin names"""
try:
from greatfet import GreatFET
from greatfet.interfaces.adc import ADC
gf = GreatFET()
except ModuleNotFoundError:
raise RuntimeError(
"Unable to create GreatFET object. Make sure library is "
"installed and the device is connected."
) from ModuleNotFoundError
class Pin:
"""A basic Pin class for the NXP LPC4330 that
acts as a wrapper for the GreatFET api.
"""
# pin modes
OUT = gf.gpio.DIRECTION_OUT
IN = gf.gpio.DIRECTION_IN
ADC = 2
DAC = 3
# pin values
LOW = 0
HIGH = 1
def __init__(self, pin_id=None):
self.id = pin_id
self._mode = None
self._pin = None
def init(self, mode=IN, pull=None):
"""Initialize the Pin"""
if self.id is None:
raise RuntimeError("Can not init a None type pin.")
if pull is not None:
raise NotImplementedError("Internal pullups and pulldowns not supported")
if mode in (Pin.IN, Pin.OUT):
if self.id not in gf.GPIO_MAPPINGS:
raise ValueError("Pin does not have GPIO capabilities")
self._pin = gf.gpio.get_pin(self.id)
self._pin.set_direction(mode)
elif mode == Pin.ADC:
# ADC only available on these pins
if self.id not in gf.ADC_MAPPINGS:
raise ValueError("Pin does not have ADC capabilities")
self._pin = ADC(gf, self.id)
elif mode == Pin.DAC:
# DAC only available on these pins
if self.id != "J2_P5":
raise ValueError("Pin does not have DAC capabilities")
self._pin = gf.apis.dac
self._pin.initialize()
else:
raise ValueError("Incorrect pin mode: {}".format(mode))
self._mode = mode
def value(self, val=None):
"""Set or return the Pin Value"""
# Digital In / Out
if self._mode in (Pin.IN, Pin.OUT):
# digital read
if val is None:
return self._pin.get_state()
# digital write
if val in (Pin.LOW, Pin.HIGH):
self._pin.set_state(val)
return None
# nope
raise ValueError("Invalid value for pin.")
# Analog In
if self._mode == Pin.ADC:
if val is None:
# Read ADC here
return self._pin.read_samples()[0]
# read only
raise AttributeError("'AnalogIn' object has no attribute 'value'")
# Analog Out
if self._mode == Pin.DAC:
if val is None:
# write only
raise AttributeError("unreadable attribute")
# Set DAC Here
self._pin.set_value(int(val))
return None
raise RuntimeError(
"No action for mode {} with value {}".format(self._mode, val)
)
# create pin instances for each pin
# J1 Header Pins
J1_P3 = Pin("J1_P3")
J1_P4 = Pin("J1_P4")
J1_P5 = Pin("J1_P5")
J1_P6 = Pin("J1_P6")
J1_P7 = Pin("J1_P7")
J1_P8 = Pin("J1_P8")
J1_P9 = Pin("J1_P9")
J1_P10 = Pin("J1_P10")
J1_P12 = Pin("J1_P12")
J1_P13 = Pin("J1_P13")
J1_P14 = Pin("J1_P14")
J1_P15 = Pin("J1_P15")
J1_P16 = Pin("J1_P16")
J1_P17 = Pin("J1_P17")
J1_P18 = Pin("J1_P18")
J1_P19 = Pin("J1_P19")
J1_P20 = Pin("J1_P20")
J1_P21 = Pin("J1_P21")
J1_P22 = Pin("J1_P22")
J1_P23 = Pin("J1_P23")
J1_P24 = Pin("J1_P24")
J1_P25 = Pin("J1_P25")
J1_P26 = Pin("J1_P26")
J1_P27 = Pin("J1_P27")
J1_P28 = Pin("J1_P28")
J1_P29 = Pin("J1_P29")
J1_P30 = Pin("J1_P30")
J1_P31 = Pin("J1_P31")
J1_P32 = Pin("J1_P32")
J1_P33 = Pin("J1_P33")
J1_P34 = Pin("J1_P34")
J1_P35 = Pin("J1_P35")
J1_P37 = Pin("J1_P37")
J1_P39 = Pin("J1_P39") # MOSI
J1_P40 = Pin("J1_P40") # MISO
# J2 Header Pins
J2_P3 = Pin("J2_P3")
J2_P4 = Pin("J2_P4")
J2_P5 = Pin("J2_P5") # ADC, ADC, DAC
J2_P6 = Pin("J2_P6")
J2_P7 = Pin("J2_P7")
J2_P8 = Pin("J2_P8")
J2_P9 = Pin("J2_P9") # ADC, GPIO
J2_P10 = Pin("J2_P10")
J2_P13 = Pin("J2_P13")
J2_P14 = Pin("J2_P14")
J2_P15 = Pin("J2_P15")
J2_P16 = Pin("J2_P16") # GPIO, ADC
J2_P18 = Pin("J2_P18")
J2_P19 = Pin("J2_P19")
J2_P20 = Pin("J2_P20")
J2_P22 = Pin("J2_P22")
J2_P23 = Pin("J2_P23")
J2_P24 = Pin("J2_P24")
J2_P25 = Pin("J2_P25")
J2_P27 = Pin("J2_P27")
J2_P28 = Pin("J2_P28")
J2_P29 = Pin("J2_P29")
J2_P30 = Pin("J2_P30")
J2_P31 = Pin("J2_P31")
J2_P33 = Pin("J2_P33")
J2_P34 = Pin("J2_P34")
J2_P35 = Pin("J2_P35")
J2_P36 = Pin("J2_P36")
J2_P37 = Pin("J2_P37")
J2_P38 = Pin("J2_P38")
# Bonus Row Pins
J7_P2 = Pin("J7_P2")
J7_P3 = Pin("J7_P3")
J7_P4 = Pin("J7_P4") # ADC, ADC
J7_P5 = Pin("J7_P5") # ADC, ADC
J7_P6 = Pin("J7_P6")
J7_P7 = Pin("J7_P7")
J7_P8 = Pin("J7_P8")
J7_P13 = Pin("J7_P13")
J7_P14 = Pin("J7_P14")
J7_P15 = Pin("J7_P15")
J7_P16 = Pin("J7_P16")
J7_P17 = Pin("J7_P17")
J7_P18 = Pin("J7_P18")
SCL = Pin()
SDA = Pin()
SCK = Pin()
MOSI = J1_P39
MISO = J1_P40
TX = J1_P33
RX = J1_P34
# ordered as uartId, txId, rxId
uartPorts = ((0, TX, RX),)
# pwm outputs: pwm channel and pin
pwmOuts = (
(0, J1_P4),
(1, J1_P6),
(2, J1_P28),
(3, J1_P30),
(4, J2_P36),
(5, J2_P34),
(6, J2_P33),
(7, J1_P34),
(8, J2_P9),
(9, J1_P6),
(10, J1_P25),
(11, J1_P32),
(12, J1_P31),
(13, J2_P3),
(14, J1_P3),
(15, J1_P5),
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/nxp_lpc4330/pin.py | pin.py |
"""SPI Class for NXP LPC4330"""
from greatfet import GreatFET
class SPI:
"""Custom I2C Class for NXP LPC4330"""
MSB = 0
def __init__(self):
self._gf = GreatFET()
self._frequency = None
self.buffer_size = 255
self._mode = 0
self._spi = None
self._presets = {
204000: (100, 9),
408000: (100, 4),
680000: (100, 2),
1020000: (100, 1),
2040000: (50, 1),
4250000: (24, 1),
8500000: (12, 1),
12750000: (8, 1),
17000000: (6, 1),
20400000: (2, 4),
25500000: (4, 1),
34000000: (2, 2),
51000000: (2, 1),
102000000: (2, 0),
}
# pylint: disable=too-many-arguments,unused-argument
def init(
self,
baudrate=100000,
polarity=0,
phase=0,
bits=8,
firstbit=MSB,
sck=None,
mosi=None,
miso=None,
):
"""Initialize the Port"""
# Figure out the mode based on phase and polarity
polarity = int(polarity)
phase = int(phase)
self._mode = (polarity << 1) | phase
# Using API due to possible interface change
self._spi = self._gf.apis.spi
# Check baudrate against presets and adjust to the closest one
if self._frequency is None:
preset = self._find_closest_preset(baudrate)
else:
preset = self._presets[self._frequency]
clock_prescale_rate, serial_clock_rate = preset
self._spi.init(serial_clock_rate, clock_prescale_rate)
# Set the polarity and phase (the "SPI mode").
self._spi.set_clock_polarity_and_phase(self._mode)
# pylint: enable=too-many-arguments
def _find_closest_preset(self, target_frequency):
"""Loop through self._frequencies and find the closest
setting. Return the preset values and set the frequency
to the found value
"""
closest_preset = None
for frequency, preset in self._presets.items():
if self._frequency is None or abs(frequency - target_frequency) < abs(
self._frequency - target_frequency
):
self._frequency = frequency
closest_preset = preset
return closest_preset
@property
def frequency(self):
"""Return the current frequency"""
return self._frequency
def write(self, buf, start=0, end=None):
"""Write data from the buffer to SPI"""
end = end if end else len(buf)
self._transmit(buf[start:end])
# pylint: disable=unused-argument
def readinto(self, buf, start=0, end=None, write_value=0):
"""Read data from SPI and into the buffer"""
end = end if end else len(buf)
result = self._transmit([write_value] * (end - start), end - start)
for i, b in enumerate(result):
buf[start + i] = b
# pylint: enable=unused-argument
# pylint: disable=too-many-arguments
def write_readinto(
self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
):
"""Perform a half-duplex write from buffer_out and then
read data into buffer_in
"""
out_end = out_end if out_end else len(buffer_out)
in_end = in_end if in_end else len(buffer_in)
result = self._transmit(buffer_out[out_start:out_end], in_end - in_start)
for i, b in enumerate(result):
buffer_in[in_start + i] = b
# pylint: enable=too-many-arguments
def _transmit(self, data, receive_length=None):
data_to_transmit = bytearray(data)
data_received = bytearray()
if receive_length is None:
receive_length = len(data)
# If we need to receive more than we've transmitted, extend the data out.
if receive_length > len(data):
padding = receive_length - len(data)
data_to_transmit.extend([0] * padding)
# Transmit our data in chunks of the buffer size.
while data_to_transmit:
# Extract a single data chunk from the transmit buffer.
chunk = data_to_transmit[0 : self.buffer_size]
del data_to_transmit[0 : self.buffer_size]
# Finally, exchange the data.
response = self._spi.clock_data(len(chunk), bytes(chunk))
data_received.extend(response)
# Once we're done, return the data received.
return bytes(data_received) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/nxp_lpc4330/spi.py | spi.py |
"""RP2040 pins"""
from ..generic_micropython import Pin
GP0 = Pin(0)
GP1 = Pin(1)
GP2 = Pin(2)
GP3 = Pin(3)
GP4 = Pin(4)
GP5 = Pin(5)
GP6 = Pin(6)
GP7 = Pin(7)
GP8 = Pin(8)
GP9 = Pin(9)
GP10 = Pin(10)
GP11 = Pin(11)
GP12 = Pin(12)
GP13 = Pin(13)
GP14 = Pin(14)
GP15 = Pin(15)
GP16 = Pin(16)
GP17 = Pin(17)
GP18 = Pin(18)
GP19 = Pin(19)
GP20 = Pin(20)
GP21 = Pin(21)
GP22 = Pin(22)
GP23 = Pin(23)
GP24 = Pin(24)
GP25 = Pin(25)
GP26 = Pin(26)
GP27 = Pin(27)
GP28 = Pin(28)
GP29 = Pin(29)
# ordered as spiId, sckId, mosiId (tx), misoId (rx)
spiPorts = (
(0, GP2, GP3, GP0),
(0, GP2, GP3, GP4),
(0, GP2, GP3, GP16),
(0, GP2, GP3, GP20),
(0, GP2, GP7, GP0),
(0, GP2, GP7, GP4),
(0, GP2, GP7, GP16),
(0, GP2, GP7, GP20),
(0, GP2, GP19, GP0),
(0, GP2, GP19, GP4),
(0, GP2, GP19, GP16),
(0, GP2, GP19, GP20),
(0, GP6, GP3, GP0),
(0, GP6, GP3, GP4),
(0, GP6, GP3, GP16),
(0, GP6, GP3, GP20),
(0, GP6, GP7, GP0),
(0, GP6, GP7, GP4),
(0, GP6, GP7, GP16),
(0, GP6, GP7, GP20),
(0, GP6, GP19, GP0),
(0, GP6, GP19, GP4),
(0, GP6, GP19, GP16),
(0, GP6, GP19, GP20),
(0, GP18, GP3, GP0),
(0, GP18, GP3, GP4),
(0, GP18, GP3, GP16),
(0, GP18, GP3, GP20),
(0, GP18, GP7, GP0),
(0, GP18, GP7, GP4),
(0, GP18, GP7, GP16),
(0, GP18, GP7, GP20),
(0, GP18, GP19, GP0),
(0, GP18, GP19, GP4),
(0, GP18, GP19, GP16),
(0, GP18, GP19, GP20),
(1, GP10, GP11, GP8),
(1, GP10, GP11, GP12),
(1, GP10, GP15, GP8),
(1, GP10, GP15, GP12),
(1, GP14, GP11, GP8),
(1, GP14, GP11, GP12),
(1, GP14, GP15, GP8),
(1, GP14, GP15, GP12),
)
# ordered as uartId, txId, rxId
uartPorts = (
(0, GP0, GP1),
(0, GP0, GP13),
(0, GP12, GP1),
(0, GP12, GP13),
(1, GP4, GP5),
(1, GP4, GP9),
(1, GP8, GP5),
(1, GP8, GP9),
)
# ordered as scl, sda
i2cPorts = (
(0, GP1, GP0),
(0, GP1, GP4),
(0, GP1, GP8),
(0, GP1, GP12),
(0, GP1, GP16),
(0, GP1, GP20),
(0, GP1, GP24),
(0, GP1, GP28),
(1, GP3, GP2),
(1, GP3, GP6),
(1, GP3, GP10),
(1, GP3, GP14),
(1, GP3, GP18),
(1, GP3, GP22),
(1, GP3, GP26),
(0, GP5, GP0),
(0, GP5, GP4),
(0, GP5, GP8),
(0, GP5, GP12),
(0, GP5, GP16),
(0, GP5, GP20),
(0, GP5, GP24),
(0, GP5, GP28),
(1, GP7, GP2),
(1, GP7, GP6),
(1, GP7, GP10),
(1, GP7, GP14),
(1, GP7, GP18),
(1, GP7, GP22),
(1, GP7, GP26),
(0, GP9, GP0),
(0, GP9, GP4),
(0, GP9, GP8),
(0, GP9, GP12),
(0, GP9, GP16),
(0, GP9, GP20),
(0, GP9, GP24),
(0, GP9, GP28),
(1, GP11, GP2),
(1, GP11, GP6),
(1, GP11, GP10),
(1, GP11, GP14),
(1, GP11, GP18),
(1, GP11, GP22),
(1, GP11, GP26),
(0, GP13, GP0),
(0, GP13, GP4),
(0, GP13, GP8),
(0, GP13, GP12),
(0, GP13, GP16),
(0, GP13, GP20),
(0, GP13, GP24),
(0, GP13, GP28),
(1, GP15, GP2),
(1, GP15, GP6),
(1, GP15, GP10),
(1, GP15, GP14),
(1, GP15, GP18),
(1, GP15, GP22),
(1, GP15, GP26),
(0, GP17, GP0),
(0, GP17, GP4),
(0, GP17, GP8),
(0, GP17, GP12),
(0, GP17, GP16),
(0, GP17, GP20),
(0, GP17, GP24),
(0, GP17, GP28),
(1, GP19, GP2),
(1, GP19, GP6),
(1, GP19, GP10),
(1, GP19, GP14),
(1, GP19, GP18),
(1, GP19, GP22),
(1, GP19, GP26),
(0, GP21, GP0),
(0, GP21, GP4),
(0, GP21, GP8),
(0, GP21, GP12),
(0, GP21, GP16),
(0, GP21, GP20),
(0, GP21, GP24),
(0, GP21, GP28),
(1, GP23, GP2),
(1, GP23, GP6),
(1, GP23, GP10),
(1, GP23, GP14),
(1, GP23, GP18),
(1, GP23, GP22),
(1, GP23, GP26),
(0, GP25, GP0),
(0, GP25, GP4),
(0, GP25, GP8),
(0, GP25, GP12),
(0, GP25, GP16),
(0, GP25, GP20),
(0, GP25, GP24),
(0, GP25, GP28),
(1, GP27, GP2),
(1, GP27, GP6),
(1, GP27, GP10),
(1, GP27, GP14),
(1, GP27, GP18),
(1, GP27, GP22),
(1, GP27, GP26),
(0, GP29, GP0),
(0, GP29, GP4),
(0, GP29, GP8),
(0, GP29, GP12),
(0, GP29, GP16),
(0, GP29, GP20),
(0, GP29, GP24),
(0, GP29, GP28),
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rp2040/pin.py | pin.py |
"""SPI Class for RP2040"""
from machine import SPI as _SPI
from machine import Pin
from microcontroller.pin import spiPorts
# pylint: disable=protected-access, no-self-use
class SPI:
"""Custom SPI Class for RP2040"""
MSB = _SPI.MSB
def __init__(self, clock, MOSI=None, MISO=None, *, baudrate=1000000):
self._frequency = baudrate
for portId, portSck, portMosi, portMiso in spiPorts:
if (
(clock == portSck)
and MOSI in (portMosi, None) # Clock is required!
and MISO in (portMiso, None) # But can do with just output
): # Or just input
mosiPin = Pin(portMosi.id) if MOSI else None
misoPin = Pin(portMiso.id) if MISO else None
self._spi = _SPI(
portId,
sck=Pin(portSck.id),
mosi=mosiPin,
miso=misoPin,
baudrate=baudrate,
)
break
else:
raise ValueError(
"No Hardware SPI on (SCLK, MOSI, MISO)={}\nValid SPI ports:{}".format(
(clock, MOSI, MISO), spiPorts
)
)
# pylint: disable=too-many-arguments,unused-argument
def init(
self,
baudrate=1000000,
polarity=0,
phase=0,
bits=8,
firstbit=_SPI.MSB,
sck=None,
mosi=None,
miso=None,
):
"""Initialize the Port"""
self._frequency = baudrate
self._spi.init(
baudrate=baudrate,
polarity=polarity,
phase=phase,
bits=bits,
firstbit=firstbit,
)
# pylint: enable=too-many-arguments
@property
def frequency(self):
"""Return the current frequency"""
return self._frequency
def write(self, buf, start=0, end=None):
"""Write data from the buffer to SPI"""
self._spi.write(buf)
def readinto(self, buf, start=0, end=None, write_value=0):
"""Read data from SPI and into the buffer"""
self._spi.readinto(buf)
# pylint: disable=too-many-arguments
def write_readinto(
self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
):
"""Perform a half-duplex write from buffer_out and then
read data into buffer_in
"""
self._spi.write_readinto(
buffer_out,
buffer_in,
out_start=out_start,
out_end=out_end,
in_start=in_start,
in_end=in_end,
)
# pylint: enable=too-many-arguments | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/rp2040/spi.py | spi.py |
"""A Pin class for use with libgpiod."""
try:
import gpiod
except ImportError:
raise ImportError(
"libgpiod Python bindings not found, please install and try again! See "
"https://github.com/adafruit/Raspberry-Pi-Installer-Scripts/blob/master/libgpiod.sh"
) from ImportError
# pylint: disable=too-many-branches,too-many-statements
class Pin:
"""Pins dont exist in CPython so...lets make our own!"""
IN = 0
OUT = 1
LOW = 0
HIGH = 1
PULL_NONE = 0
PULL_UP = 1
PULL_DOWN = 2
_CONSUMER = "adafruit_blinka"
id = None
_value = LOW
_mode = IN
def __init__(self, pin_id):
self.id = pin_id
if isinstance(pin_id, tuple):
self._num = int(pin_id[1])
if hasattr(gpiod, "Chip"):
self._chip = gpiod.Chip(str(pin_id[0]), gpiod.Chip.OPEN_BY_NUMBER)
else:
self._chip = gpiod.chip(str(pin_id[0]), gpiod.chip.OPEN_BY_NUMBER)
else:
self._num = int(pin_id)
if hasattr(gpiod, "Chip"):
self._chip = gpiod.Chip("gpiochip0", gpiod.Chip.OPEN_BY_NAME)
else:
self._chip = gpiod.chip("gpiochip0", gpiod.chip.OPEN_BY_NAME)
self._line = None
def __repr__(self):
return str(self.id)
def __eq__(self, other):
return self.id == other
def init(self, mode=IN, pull=None):
"""Initialize the Pin"""
if not self._line:
self._line = self._chip.get_line(int(self._num))
# print("init line: ", self.id, self._line)
if mode is not None:
if mode == self.IN:
flags = 0
self._line.release()
if pull is not None:
if pull == self.PULL_UP:
if hasattr(gpiod, "line") and hasattr(
gpiod.line, "BIAS_PULL_UP"
):
config = gpiod.line_request()
config.consumer = self._CONSUMER
config.request_type = gpiod.line.BIAS_PULL_UP
self._line.request(config)
else:
self._line.request(
consumer=self._CONSUMER,
type=gpiod.LINE_REQ_DIR_IN,
flags=flags,
)
raise NotImplementedError(
"Internal pullups not supported in this version of libgpiod, "
"use physical resistor instead!"
)
elif pull == self.PULL_DOWN:
if hasattr(gpiod, "line") and hasattr(
gpiod.line, "BIAS_PULL_DOWN"
):
config = gpiod.line_request()
config.consumer = self._CONSUMER
config.request_type = gpiod.line.BIAS_PULL_DOWN
self._line.request(config)
else:
raise NotImplementedError(
"Internal pulldowns not supported in this version of libgpiod, "
"use physical resistor instead!"
)
elif pull == self.PULL_NONE:
if hasattr(gpiod, "line") and hasattr(
gpiod.line, "BIAS_DISABLE"
):
config = gpiod.line_request()
config.consumer = self._CONSUMER
config.request_type = gpiod.line.BIAS_DISABLE
self._line.request(config)
else:
raise RuntimeError(f"Invalid pull for pin: {self.id}")
self._mode = self.IN
self._line.release()
if hasattr(gpiod, "LINE_REQ_DIR_IN"):
self._line.request(
consumer=self._CONSUMER, type=gpiod.LINE_REQ_DIR_IN, flags=flags
)
else:
config = gpiod.line_request()
config.consumer = self._CONSUMER
config.request_type = gpiod.line_request.DIRECTION_INPUT
self._line.request(config)
elif mode == self.OUT:
if pull is not None:
raise RuntimeError("Cannot set pull resistor on output")
self._mode = self.OUT
self._line.release()
if hasattr(gpiod, "LINE_REQ_DIR_OUT"):
self._line.request(
consumer=self._CONSUMER, type=gpiod.LINE_REQ_DIR_OUT
)
else:
config = gpiod.line_request()
config.consumer = self._CONSUMER
config.request_type = gpiod.line_request.DIRECTION_OUTPUT
self._line.request(config)
else:
raise RuntimeError("Invalid mode for pin: %s" % self.id)
def value(self, val=None):
"""Set or return the Pin Value"""
if val is None:
return self._line.get_value()
if val in (self.LOW, self.HIGH):
self._value = val
self._line.set_value(val)
return None
raise RuntimeError("Invalid value for pin") | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/generic_linux/libgpiod_pin.py | libgpiod_pin.py |
import os
import errno
import time
# pylint: disable=unnecessary-pass
class GPIOError(IOError):
"""Base class for GPIO errors."""
pass
# pylint: enable=unnecessary-pass
class Pin:
"""SysFS GPIO Pin Class"""
# Number of retries to check for GPIO export or direction write on open
GPIO_OPEN_RETRIES = 10
# Delay between check for GPIO export or direction write on open (100ms)
GPIO_OPEN_DELAY = 0.1
IN = "in"
OUT = "out"
LOW = 0
HIGH = 1
PULL_NONE = 0
PULL_UP = 1
PULL_DOWN = 2
id = None
_value = LOW
_mode = IN
# Sysfs paths
_sysfs_path = "/sys/class/gpio/"
_channel_path = "gpiochip{}"
# Channel paths
_export_path = "export"
_unexport_path = "unexport"
_pin_path = "gpio{}"
def __init__(self, pin_id):
"""Instantiate a Pin object and open the sysfs GPIO with the specified
pin number.
Args:
pin_id (int): GPIO pin number.
Returns:
SysfsGPIO: GPIO object.
Raises:
GPIOError: if an I/O or OS error occurs.
TypeError: if `line` or `direction` types are invalid.
ValueError: if `direction` value is invalid.
TimeoutError: if waiting for GPIO export times out.
"""
if not isinstance(pin_id, int):
raise TypeError("Invalid Pin ID, should be integer.")
self.id = pin_id
self._fd = None
self._line = None
self._path = None
def __del__(self):
self._close()
def __enter__(self):
return self
def __exit__(self, t, value, traceback):
self._close()
def init(self, mode=IN, pull=None):
"""Initialize the Pin"""
if mode is not None:
if mode == self.IN:
self._mode = self.IN
self._open(self.IN)
elif mode == self.OUT:
self._mode = self.OUT
self._open(self.OUT)
else:
raise RuntimeError("Invalid mode for pin: %s" % self.id)
if pull is not None:
if pull == self.PULL_UP:
raise NotImplementedError(
"Internal pullups not supported in periphery, "
"use physical resistor instead!"
)
if pull == self.PULL_DOWN:
raise NotImplementedError(
"Internal pulldowns not supported in periphery, "
"use physical resistor instead!"
)
raise RuntimeError("Invalid pull for pin: %s" % self.id)
def value(self, val=None):
"""Set or return the Pin Value"""
if val is not None:
if val == self.LOW:
self._value = val
self._write(False)
return None
if val == self.HIGH:
self._value = val
self._write(True)
return None
raise RuntimeError("Invalid value for pin")
return self.HIGH if self._read() else self.LOW
# pylint: disable=too-many-branches
def _open(self, direction):
if not isinstance(direction, str):
raise TypeError("Invalid direction type, should be string.")
if direction.lower() not in ["in", "out", "high", "low"]:
raise ValueError('Invalid direction, can be: "in", "out", "high", "low".')
gpio_path = "/sys/class/gpio/gpio{:d}".format(self.id)
if not os.path.isdir(gpio_path):
# Export the line
try:
with open("/sys/class/gpio/export", "w", encoding="utf-8") as f_export:
f_export.write("{:d}\n".format(self.id))
except IOError as e:
raise GPIOError(e.errno, "Exporting GPIO: " + e.strerror) from IOError
# Loop until GPIO is exported
exported = False
for i in range(self.GPIO_OPEN_RETRIES):
if os.path.isdir(gpio_path):
exported = True
break
time.sleep(self.GPIO_OPEN_DELAY)
if not exported:
raise TimeoutError(
'Exporting GPIO: waiting for "{:s}" timed out'.format(gpio_path)
)
# Write direction, looping in case of EACCES errors due to delayed udev
# permission rule application after export
for i in range(self.GPIO_OPEN_RETRIES):
try:
with open(
os.path.join(gpio_path, "direction"), "w", encoding="utf-8"
) as f_direction:
f_direction.write(direction.lower() + "\n")
break
except IOError as e:
if e.errno != errno.EACCES or (
e.errno == errno.EACCES and i == self.GPIO_OPEN_RETRIES - 1
):
raise GPIOError(
e.errno, "Setting GPIO direction: " + e.strerror
) from IOError
time.sleep(self.GPIO_OPEN_DELAY)
else:
# Write direction
try:
with open(
os.path.join(gpio_path, "direction"), "w", encoding="utf-8"
) as f_direction:
f_direction.write(direction.lower() + "\n")
except IOError as e:
raise GPIOError(
e.errno, "Setting GPIO direction: " + e.strerror
) from IOError
# Open value
try:
self._fd = os.open(os.path.join(gpio_path, "value"), os.O_RDWR)
except OSError as e:
raise GPIOError(e.errno, "Opening GPIO: " + e.strerror) from OSError
self._path = gpio_path
# pylint: enable=too-many-branches
def _close(self):
if self._fd is None:
return
try:
os.close(self._fd)
except OSError as e:
raise GPIOError(e.errno, "Closing GPIO: " + e.strerror) from OSError
self._fd = None
# Unexport the line
try:
unexport_fd = os.open("/sys/class/gpio/unexport", os.O_WRONLY)
os.write(unexport_fd, "{:d}\n".format(self.id).encode())
os.close(unexport_fd)
except OSError as e:
raise GPIOError(e.errno, "Unexporting GPIO: " + e.strerror) from OSError
def _read(self):
# Read value
try:
buf = os.read(self._fd, 2)
except OSError as e:
raise GPIOError(e.errno, "Reading GPIO: " + e.strerror) from OSError
# Rewind
try:
os.lseek(self._fd, 0, os.SEEK_SET)
except OSError as e:
raise GPIOError(e.errno, "Rewinding GPIO: " + e.strerror) from OSError
if buf[0] == b"0"[0]:
return False
if buf[0] == b"1"[0]:
return True
raise GPIOError(None, "Unknown GPIO value: {}".format(buf))
def _write(self, value):
if not isinstance(value, bool):
raise TypeError("Invalid value type, should be bool.")
# Write value
try:
if value:
os.write(self._fd, b"1\n")
else:
os.write(self._fd, b"0\n")
except OSError as e:
raise GPIOError(e.errno, "Writing GPIO: " + e.strerror) from OSError
# Rewind
try:
os.lseek(self._fd, 0, os.SEEK_SET)
except OSError as e:
raise GPIOError(e.errno, "Rewinding GPIO: " + e.strerror) from OSError
@property
def chip_name(self):
"""Return the Chip Name"""
gpio_path = os.path.join(self._path, "device")
gpiochip_path = os.readlink(gpio_path)
if "/" not in gpiochip_path:
raise GPIOError(
None,
'Reading gpiochip name: invalid device symlink "{:s}"'.format(
gpiochip_path
),
)
return gpiochip_path.split("/")[-1]
@property
def chip_label(self):
"""Return the Chip Label"""
gpio_path = "/sys/class/gpio/{:s}/label".format(self.chip_name)
try:
with open(gpio_path, "r", encoding="utf-8") as f_label:
label = f_label.read()
except (GPIOError, IOError) as e:
if isinstance(e, IOError):
raise GPIOError(
e.errno, "Reading gpiochip label: " + e.strerror
) from IOError
raise GPIOError(
None, "Reading gpiochip label: " + e.strerror
) from GPIOError
return label.strip()
# Mutable properties
def _get_direction(self):
# Read direction
try:
with open(
os.path.join(self._path, "direction"), "r", encoding="utf-8"
) as f_direction:
direction = f_direction.read()
except IOError as e:
raise GPIOError(
e.errno, "Getting GPIO direction: " + e.strerror
) from IOError
return direction.strip()
def _set_direction(self, direction):
if not isinstance(direction, str):
raise TypeError("Invalid direction type, should be string.")
if direction.lower() not in ["in", "out", "high", "low"]:
raise ValueError('Invalid direction, can be: "in", "out", "high", "low".')
# Write direction
try:
with open(
os.path.join(self._path, "direction"), "w", encoding="utf-8"
) as f_direction:
f_direction.write(direction.lower() + "\n")
except IOError as e:
raise GPIOError(
e.errno, "Setting GPIO direction: " + e.strerror
) from IOError
direction = property(_get_direction, _set_direction)
def __str__(self):
try:
str_direction = self.direction
except GPIOError:
str_direction = "<error>"
try:
str_chip_name = self.chip_name
except GPIOError:
str_chip_name = "<error>"
try:
str_chip_label = self.chip_label
except GPIOError:
str_chip_label = "<error>"
output = "Pin {:d} (dev={:s}, fd={:d}, dir={:s}, chip_name='{:s}', chip_label='{:s}')"
return output.format(
self.id, self._path, self._fd, str_direction, str_chip_name, str_chip_label
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/generic_linux/sysfs_pin.py | sysfs_pin.py |
import os
from adafruit_blinka import ContextManaged
try:
from microcontroller.pin import analogOuts
except ImportError:
raise RuntimeError("No Analog Outputs defined for this board") from ImportError
class AnalogOut(ContextManaged):
"""Analog Output Class"""
# Sysfs paths
_sysfs_path = "/sys/bus/iio/devices/"
_device_path = "iio:device{}"
# Channel paths
_channel_path = "out_voltage{}_raw"
_scale_path = "out_voltage_scale"
def __init__(self, dac_id):
"""Instantiate an AnalogOut object and verify the sysfs IIO
corresponding to the specified channel and pin.
Args:
dac_id (int): Analog Output ID as defined in microcontroller.pin
Returns:
AnalogOut: AnalogOut object.
Raises:
TypeError: if `channel` or `pin` types are invalid.
ValueError: if AnalogOut channel does not exist.
"""
self.id = dac_id
self._device = None
self._channel = None
self._open(dac_id)
def __enter__(self):
return self
def _open(self, dac_id):
self._device = None
for dacpair in analogOuts:
if dacpair[0] == dac_id:
self._device = dacpair[1]
self._channel = dacpair[2]
if self._device is None:
raise RuntimeError("No AnalogOut device found for the given ID")
device_path = os.path.join(
self._sysfs_path, self._device_path.format(self._device)
)
if not os.path.isdir(device_path):
raise ValueError(
"AnalogOut device does not exist, check that the required modules are loaded."
)
@property
def value(self):
"""Return an error. This is output only."""
# emulate what CircuitPython does
raise AttributeError("unreadable attribute")
@value.setter
def value(self, value):
"""Write to the DAC"""
path = os.path.join(
self._sysfs_path,
self._device_path.format(self._device),
self._channel_path.format(self._channel),
)
with open(path, "w", encoding="utf-8") as analog_out:
return analog_out.write(value + "\n")
def deinit(self):
self._device = None
self._channel = None | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/generic_linux/sysfs_analogout.py | sysfs_analogout.py |
"""A Pin class for use with periphery."""
try:
from periphery import GPIO
except ImportError:
raise ImportError(
"Periphery Python bindings not found, please install and try again! "
"Try running 'pip3 install python-periphery'"
) from ImportError
class Pin:
"""Pins dont exist in CPython so...lets make our own!"""
IN = "in"
OUT = "out"
LOW = 0
HIGH = 1
PULL_NONE = 0
PULL_UP = 1
PULL_DOWN = 2
id = None
_value = LOW
_mode = IN
def __init__(self, pin_id):
self.id = pin_id
if isinstance(pin_id, tuple):
self._num = int(pin_id[1])
self._chippath = "/dev/gpiochip{}".format(pin_id[0])
else:
self._num = int(pin_id)
self._chippath = "/dev/gpiochip0"
self._line = None
def __repr__(self):
return str(self.id)
def __eq__(self, other):
return self.id == other
def init(self, mode=IN, pull=None):
"""Initialize the Pin"""
if mode is not None:
if mode == self.IN:
self._mode = self.IN
if self._line is not None:
self._line.close()
self._line = GPIO(self._chippath, int(self._num), self.IN)
elif mode == self.OUT:
self._mode = self.OUT
if self._line is not None:
self._line.close()
self._line = GPIO(self._chippath, int(self._num), self.OUT)
else:
raise RuntimeError("Invalid mode for pin: %s" % self.id)
if pull is not None:
if pull == self.PULL_UP:
raise NotImplementedError(
"Internal pullups not supported in periphery, "
"use physical resistor instead!"
)
if pull == self.PULL_DOWN:
raise NotImplementedError(
"Internal pulldowns not supported in periphery, "
"use physical resistor instead!"
)
raise RuntimeError("Invalid pull for pin: %s" % self.id)
def value(self, val=None):
"""Set or return the Pin Value"""
if val is not None:
if val == self.LOW:
self._value = val
self._line.write(False)
return None
if val == self.HIGH:
self._value = val
self._line.write(True)
return None
raise RuntimeError("Invalid value for pin")
return self.HIGH if self._line.read() else self.LOW | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/generic_linux/periphery_pin.py | periphery_pin.py |
import os
from adafruit_blinka import ContextManaged
try:
from microcontroller.pin import analogIns
except ImportError:
raise RuntimeError("No Analog Inputs defined for this board") from ImportError
class AnalogIn(ContextManaged):
"""Analog Input Class"""
# Sysfs paths
_sysfs_path = "/sys/bus/iio/devices/"
_device_path = "iio:device{}"
# Channel paths
_channel_path = "in_voltage{}_raw"
_scale_path = "in_voltage_scale"
def __init__(self, adc_id):
"""Instantiate an AnalogIn object and verify the sysfs IIO
corresponding to the specified channel and pin.
Args:
adc_id (int): Analog Input ID as defined in microcontroller.pin
Returns:
AnalogIn: AnalogIn object.
Raises:
TypeError: if `channel` or `pin` types are invalid.
ValueError: if AnalogIn channel does not exist.
"""
self.id = adc_id
self._device = None
self._channel = None
self._open(adc_id)
def __enter__(self):
return self
def _open(self, adc_id):
self._device = None
for adcpair in analogIns:
if adcpair[0] == adc_id:
self._device = adcpair[1]
self._channel = adcpair[2]
if self._device is None:
raise RuntimeError("No AnalogIn device found for the given ID")
device_path = os.path.join(
self._sysfs_path, self._device_path.format(self._device)
)
if not os.path.isdir(device_path):
raise ValueError(
"AnalogIn device does not exist, check that the required modules are loaded."
)
@property
def value(self):
"""Read the ADC and return the value as an integer"""
path = os.path.join(
self._sysfs_path,
self._device_path.format(self._device),
self._channel_path.format(self._channel),
)
with open(path, "r", encoding="utf-8") as analog_in:
return int(analog_in.read().strip())
# pylint: disable=no-self-use
@value.setter
def value(self, value):
# emulate what CircuitPython does
raise AttributeError("'AnalogIn' object has no attribute 'value'")
# pylint: enable=no-self-use
def deinit(self):
self._device = None
self._channel = None | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/generic_linux/sysfs_analogin.py | sysfs_analogin.py |
"""Generic Linux I2C class using PureIO's smbus class"""
from Adafruit_PureIO import smbus
class I2C:
"""I2C class"""
MASTER = 0
SLAVE = 1
_baudrate = None
_mode = None
_i2c_bus = None
# pylint: disable=unused-argument
def __init__(self, bus_num, mode=MASTER, baudrate=None):
if mode != self.MASTER:
raise NotImplementedError("Only I2C Master supported!")
_mode = self.MASTER
# if baudrate != None:
# print("I2C frequency is not settable in python, ignoring!")
try:
self._i2c_bus = smbus.SMBus(bus_num)
except FileNotFoundError:
raise RuntimeError(
"I2C Bus #%d not found, check if enabled in config!" % bus_num
) from RuntimeError
# pylint: enable=unused-argument
def scan(self):
"""Try to read a byte from each address, if you get an OSError
it means the device isnt there"""
found = []
for addr in range(0, 0x80):
try:
self._i2c_bus.read_byte(addr)
except OSError:
continue
found.append(addr)
return found
# pylint: disable=unused-argument
def writeto(self, address, buffer, *, start=0, end=None, stop=True):
"""Write data from the buffer to an address"""
if end is None:
end = len(buffer)
self._i2c_bus.write_bytes(address, buffer[start:end])
def readfrom_into(self, address, buffer, *, start=0, end=None, stop=True):
"""Read data from an address and into the buffer"""
if end is None:
end = len(buffer)
readin = self._i2c_bus.read_bytes(address, end - start)
for i in range(end - start):
buffer[i + start] = readin[i]
# pylint: enable=unused-argument
def writeto_then_readfrom(
self,
address,
buffer_out,
buffer_in,
*,
out_start=0,
out_end=None,
in_start=0,
in_end=None,
stop=False,
):
"""Write data from buffer_out to an address and then
read data from an address and into buffer_in
"""
if out_end is None:
out_end = len(buffer_out)
if in_end is None:
in_end = len(buffer_in)
if stop:
# To generate a stop in linux, do in two transactions
self.writeto(address, buffer_out, start=out_start, end=out_end, stop=True)
self.readfrom_into(address, buffer_in, start=in_start, end=in_end)
else:
# To generate without a stop, do in one block transaction
readin = self._i2c_bus.read_i2c_block_data(
address, buffer_out[out_start:out_end], in_end - in_start
)
for i in range(in_end - in_start):
buffer_in[i + in_start] = readin[i] | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/generic_linux/i2c.py | i2c.py |
"""Generic Linux SPI class using PureIO's SPI class"""
from Adafruit_PureIO import spi
from adafruit_blinka.agnostic import detector
class SPI:
"""SPI Class"""
MSB = 0
LSB = 1
CPHA = 1
CPOL = 2
baudrate = 100000
mode = 0
bits = 8
def __init__(self, portid):
if isinstance(portid, tuple):
self._spi = spi.SPI(device=portid)
else:
self._spi = spi.SPI(device=(portid, 0))
self.clock_pin = None
self.mosi_pin = None
self.miso_pin = None
self.chip = None
# pylint: disable=too-many-arguments,unused-argument
def init(
self,
baudrate=100000,
polarity=0,
phase=0,
bits=8,
firstbit=MSB,
sck=None,
mosi=None,
miso=None,
):
"""Initialize SPI"""
mode = 0
if polarity:
mode |= self.CPOL
if phase:
mode |= self.CPHA
self.baudrate = baudrate
self.mode = mode
self.bits = bits
self.chip = detector.chip
# Pins are not used
self.clock_pin = sck
self.mosi_pin = mosi
self.miso_pin = miso
# pylint: enable=too-many-arguments,unused-argument
# pylint: disable=unnecessary-pass
def set_no_cs(self):
"""Setting so that SPI doesn't automatically set the CS pin"""
# No kernel seems to support this, so we're just going to pass
pass
# pylint: enable=unnecessary-pass
@property
def frequency(self):
"""Return the current baudrate"""
return self.baudrate
def write(self, buf, start=0, end=None):
"""Write data from the buffer to SPI"""
if not buf:
return
if end is None:
end = len(buf)
try:
# self._spi.open(self._port, 0)
self.set_no_cs()
self._spi.max_speed_hz = self.baudrate
self._spi.mode = self.mode
self._spi.bits_per_word = self.bits
self._spi.writebytes(buf[start:end])
# self._spi.close()
except FileNotFoundError:
print("Could not open SPI device - check if SPI is enabled in kernel!")
raise
def readinto(self, buf, start=0, end=None, write_value=0):
"""Read data from SPI and into the buffer"""
if not buf:
return
if end is None:
end = len(buf)
try:
# self._spi.open(self._port, 0)
# self.set_no_cs()
self._spi.max_speed_hz = self.baudrate
self._spi.mode = self.mode
self._spi.bits_per_word = self.bits
data = self._spi.transfer([write_value] * (end - start))
for i in range(end - start): # 'readinto' the given buffer
buf[start + i] = data[i]
# self._spi.close()
except FileNotFoundError:
print("Could not open SPI device - check if SPI is enabled in kernel!")
raise
# pylint: disable=too-many-arguments
def write_readinto(
self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
):
"""Perform a half-duplex write from buffer_out and then
read data into buffer_in
"""
if not buffer_out or not buffer_in:
return
if out_end is None:
out_end = len(buffer_out)
if in_end is None:
in_end = len(buffer_in)
if out_end - out_start != in_end - in_start:
raise RuntimeError("Buffer slices must be of equal length.")
try:
# self._spi.open(self._port, 0)
# self.set_no_cs()
self._spi.max_speed_hz = self.baudrate
self._spi.mode = self.mode
self._spi.bits_per_word = self.bits
data = self._spi.transfer(list(buffer_out[out_start : out_end + 1]))
for i in range((in_end - in_start)):
buffer_in[i + in_start] = data[i]
# self._spi.close()
except FileNotFoundError:
print("Could not open SPI device - check if SPI is enabled in kernel!")
raise
# pylint: enable=too-many-arguments | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/generic_linux/spi.py | spi.py |
import os
from time import sleep
from errno import EACCES
try:
from microcontroller.pin import pwmOuts
except ImportError:
raise RuntimeError("No PWM outputs defined for this board") from ImportError
# pylint: disable=unnecessary-pass
class PWMError(IOError):
"""Base class for PWM errors."""
pass
# pylint: enable=unnecessary-pass
class PWMOut:
"""Pulse Width Modulation Output Class"""
# Number of retries to check for successful PWM export on open
PWM_STAT_RETRIES = 10
# Delay between check for scucessful PWM export on open (100ms)
PWM_STAT_DELAY = 0.1
# Sysfs paths
_sysfs_path = "/sys/class/pwm/"
_channel_path = "pwmchip{}"
# Channel paths
_export_path = "export"
_unexport_path = "unexport"
_pin_path = "pwm{}"
# Pin attribute paths
_pin_period_path = "period"
_pin_duty_cycle_path = "duty_cycle"
_pin_polarity_path = "polarity"
_pin_enable_path = "enable"
def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
"""Instantiate a PWM object and open the sysfs PWM corresponding to the
specified channel and pin.
Args:
pin (Pin): CircuitPython Pin object to output to
duty_cycle (int) : The fraction of each pulse which is high. 16-bit
frequency (int) : target frequency in Hertz (32-bit)
variable_frequency (bool) : True if the frequency will change over time
Returns:
PWMOut: PWMOut object.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if `channel` or `pin` types are invalid.
ValueError: if PWM channel does not exist.
"""
self._pwmpin = None
self._channel = None
self._period = 0
self._open(pin, duty_cycle, frequency, variable_frequency)
def __del__(self):
self.deinit()
def __enter__(self):
return self
def __exit__(self, t, value, traceback):
self.deinit()
def _open(self, pin, duty=0, freq=500, variable_frequency=False):
self._channel = None
for pwmpair in pwmOuts:
if pwmpair[1] == pin:
self._channel = pwmpair[0][0]
self._pwmpin = pwmpair[0][1]
self._pin = pin
if self._channel is None:
raise RuntimeError("No PWM channel found for this Pin")
if variable_frequency:
print("Variable Frequency is not supported, continuing without it...")
channel_path = os.path.join(
self._sysfs_path, self._channel_path.format(self._channel)
)
if not os.path.isdir(channel_path):
raise ValueError(
"PWM channel does not exist, check that the required modules are loaded."
)
try:
with open(
os.path.join(channel_path, self._unexport_path), "w", encoding="utf-8"
) as f_unexport:
f_unexport.write("%d\n" % self._pwmpin)
except IOError:
pass # not unusual, it doesnt already exist
try:
with open(
os.path.join(channel_path, self._export_path), "w", encoding="utf-8"
) as f_export:
f_export.write("%d\n" % self._pwmpin)
except IOError as e:
raise PWMError(e.errno, "Exporting PWM pin: " + e.strerror) from IOError
# Loop until 'period' is writable, because application of udev rules
# after the above pin export is asynchronous.
# Without this loop, the following properties may not be writable yet.
for i in range(PWMOut.PWM_STAT_RETRIES):
try:
with open(
os.path.join(
channel_path, self._pin_path.format(self._pwmpin), "period"
),
"w",
encoding="utf-8",
):
break
except IOError as e:
if e.errno != EACCES or (
e.errno == EACCES and i == PWMOut.PWM_STAT_RETRIES - 1
):
raise PWMError(e.errno, "Opening PWM period: " + e.strerror) from e
sleep(PWMOut.PWM_STAT_DELAY)
# self._set_enabled(False) # This line causes a write error when trying to enable
# Look up the period, for fast duty cycle updates
self._period = self._get_period()
# self.duty_cycle = 0 # This line causes a write error when trying to enable
# set frequency
self.frequency = freq
# set duty
self.duty_cycle = duty
self._set_enabled(True)
def deinit(self):
"""Deinit the sysfs PWM."""
if self._channel is not None:
self.duty_cycle = 0
try:
channel_path = os.path.join(
self._sysfs_path, self._channel_path.format(self._channel)
)
with open(
os.path.join(channel_path, self._unexport_path),
"w",
encoding="utf-8",
) as f_unexport:
f_unexport.write("%d\n" % self._pwmpin)
except IOError as e:
raise PWMError(
e.errno, "Unexporting PWM pin: " + e.strerror
) from IOError
self._channel = None
self._pwmpin = None
def _is_deinited(self):
if self._pwmpin is None:
raise ValueError(
"Object has been deinitialize and can no longer "
"be used. Create a new object."
)
def _write_pin_attr(self, attr, value):
# Make sure the pin is active
self._is_deinited()
path = os.path.join(
self._sysfs_path,
self._channel_path.format(self._channel),
self._pin_path.format(self._pwmpin),
attr,
)
with open(path, "w", encoding="utf-8") as f_attr:
# print(value, path)
f_attr.write(value + "\n")
def _read_pin_attr(self, attr):
# Make sure the pin is active
self._is_deinited()
path = os.path.join(
self._sysfs_path,
self._channel_path.format(self._channel),
self._pin_path.format(self._pwmpin),
attr,
)
with open(path, "r", encoding="utf-8") as f_attr:
return f_attr.read().strip()
# Mutable properties
def _get_period(self):
period_ns = self._read_pin_attr(self._pin_period_path)
try:
period_ns = int(period_ns)
except ValueError:
raise PWMError(
None, 'Unknown period value: "%s"' % period_ns
) from ValueError
# Convert period from nanoseconds to seconds
period = period_ns / 1e9
# Update our cached period
self._period = period
return period
def _set_period(self, period):
if not isinstance(period, (int, float)):
raise TypeError("Invalid period type, should be int or float.")
# Convert period from seconds to integer nanoseconds
period_ns = int(period * 1e9)
self._write_pin_attr(self._pin_period_path, "{}".format(period_ns))
# Update our cached period
self._period = float(period)
period = property(_get_period, _set_period)
"""Get or set the PWM's output period in seconds.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
:type: int, float
"""
def _get_duty_cycle(self):
duty_cycle_ns = self._read_pin_attr(self._pin_duty_cycle_path)
try:
duty_cycle_ns = int(duty_cycle_ns)
except ValueError:
raise PWMError(
None, 'Unknown duty cycle value: "%s"' % duty_cycle_ns
) from ValueError
# Convert duty cycle from nanoseconds to seconds
duty_cycle = duty_cycle_ns / 1e9
# Convert duty cycle to ratio from 0.0 to 1.0
duty_cycle = duty_cycle / self._period
# convert to 16-bit
duty_cycle = int(duty_cycle * 65535)
return duty_cycle
def _set_duty_cycle(self, duty_cycle):
if not isinstance(duty_cycle, (int, float)):
raise TypeError("Invalid duty cycle type, should be int or float.")
# convert from 16-bit
duty_cycle /= 65535.0
if not 0.0 <= duty_cycle <= 1.0:
raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
# Convert duty cycle from ratio to seconds
duty_cycle = duty_cycle * self._period
# Convert duty cycle from seconds to integer nanoseconds
duty_cycle_ns = int(duty_cycle * 1e9)
self._write_pin_attr(self._pin_duty_cycle_path, "{}".format(duty_cycle_ns))
duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
"""Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
ValueError: if value is out of bounds of 0.0 to 1.0.
:type: int, float
"""
def _get_frequency(self):
return 1.0 / self._get_period()
def _set_frequency(self, frequency):
if not isinstance(frequency, (int, float)):
raise TypeError("Invalid frequency type, should be int or float.")
self._set_period(1.0 / frequency)
frequency = property(_get_frequency, _set_frequency)
"""Get or set the PWM's output frequency in Hertz.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
:type: int, float
"""
def _get_enabled(self):
enabled = self._read_pin_attr(self._pin_enable_path)
if enabled == "1":
return True
if enabled == "0":
return False
raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
def _set_enabled(self, value):
"""Get or set the PWM's output enabled state.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not bool.
:type: bool
"""
if not isinstance(value, bool):
raise TypeError("Invalid enabled type, should be string.")
self._write_pin_attr(self._pin_enable_path, "1" if value else "0")
# String representation
def __str__(self):
return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
self._channel,
self._pin,
self.frequency,
self.duty_cycle * 100,
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/generic_linux/sysfs_pwmout.py | sysfs_pwmout.py |
"""PWMOut Class for Binho Nova"""
try:
from microcontroller.pin import pwmOuts
except ImportError:
raise RuntimeError("No PWM outputs defined for this board") from ImportError
from microcontroller.pin import Pin
# pylint: disable=unnecessary-pass
class PWMError(IOError):
"""Base class for PWM errors."""
pass
# pylint: enable=unnecessary-pass
class PWMOut:
"""Pulse Width Modulation Output Class"""
# Nova instance
_nova = None
MAX_CYCLE_LEVEL = 1024
def __init__(self, pin, *, frequency=750, duty_cycle=0, variable_frequency=False):
"""Instantiate a PWM object and open the sysfs PWM corresponding to the
specified channel and pin.
Args:
pin (Pin): CircuitPython Pin object to output to
duty_cycle (int) : The fraction of each pulse which is high. 16-bit
frequency (int) : target frequency in Hertz (32-bit)
variable_frequency (bool) : True if the frequency will change over time
Returns:
PWMOut: PWMOut object.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if `channel` or `pin` types are invalid.
ValueError: if PWM channel does not exist.
"""
if PWMOut._nova is None:
# pylint: disable=import-outside-toplevel
from adafruit_blinka.microcontroller.nova import Connection
# pylint: enable=import-outside-toplevel
PWMOut._nova = Connection.getInstance()
PWMOut._nova.setOperationMode(0, "IO")
self._pwmpin = None
self._channel = None
self._enable = False
self._open(pin, duty_cycle, frequency, variable_frequency)
def __del__(self):
self.deinit()
PWMOut._nova.close()
def __enter__(self):
return self
def __exit__(self, t, value, traceback):
self.deinit()
def _open(self, pin, duty=0, freq=750, variable_frequency=False):
self._channel = None
for pwmpair in pwmOuts:
if pwmpair[1] == pin:
self._channel = pwmpair[0][0]
self._pwmpin = pwmpair[0][1]
self._pin = pin
if self._channel is None:
raise RuntimeError("No PWM channel found for this Pin")
if variable_frequency:
print("Variable Frequency is not supported, continuing without it...")
PWMOut._nova.setIOpinMode(self._pwmpin, Pin.PWM)
# set frequency
self.frequency = freq
# set period
self._period = self._get_period()
# set duty
self.duty_cycle = duty
self._set_enabled(True)
def deinit(self):
"""Deinit the Nova PWM."""
# pylint: disable=broad-except
try:
if self._channel is not None:
# self.duty_cycle = 0
self._set_enabled(False) # make to disable before unexport
except Exception as e:
# due to a race condition for which I have not yet been
# able to find the root cause, deinit() often fails
# but it does not effect future usage of the pwm pin
print(
"warning: failed to deinitialize pwm pin {0}:{1} due to: {2}\n".format(
self._channel, self._pwmpin, type(e).__name__
)
)
finally:
self._channel = None
self._pwmpin = None
# pylint: enable=broad-except
def _is_deinited(self):
if self._pwmpin is None:
raise ValueError(
"Object has been deinitialize and can no longer "
"be used. Create a new object."
)
# Mutable properties
def _get_period(self):
return 1.0 / self._get_frequency()
def _set_period(self, period):
if not isinstance(period, (int, float)):
raise TypeError("Invalid period type, should be int or float.")
self._set_frequency(1.0 / period)
period = property(_get_period, _set_period)
"""Get or set the PWM's output period in seconds.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
:type: int, float
"""
def _get_duty_cycle(self):
duty_cycle = Pin._nova.getIOpinValue(self._pwmpin)
# Convert duty cycle to ratio from 0.0 to 1.0
duty_cycle = duty_cycle / PWMOut.MAX_CYCLE_LEVEL
# convert to 16-bit
duty_cycle = int(duty_cycle * 65535)
return duty_cycle
def _set_duty_cycle(self, duty_cycle):
if not isinstance(duty_cycle, (int, float)):
raise TypeError("Invalid duty cycle type, should be int or float.")
# convert from 16-bit
duty_cycle /= 65535.0
if not 0.0 <= duty_cycle <= 1.0:
raise ValueError("Invalid duty cycle value, should be between 0.0 and 1.0.")
# Convert duty cycle from ratio to 1024 levels
duty_cycle = duty_cycle * PWMOut.MAX_CYCLE_LEVEL
# Set duty cycle
# pylint: disable=protected-access
Pin._nova.setIOpinValue(self._pwmpin, duty_cycle)
# pylint: enable=protected-access
duty_cycle = property(_get_duty_cycle, _set_duty_cycle)
"""Get or set the PWM's output duty cycle as a ratio from 0.0 to 1.0.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
ValueError: if value is out of bounds of 0.0 to 1.0.
:type: int, float
"""
def _get_frequency(self):
return int(PWMOut._nova.getIOpinPWMFreq(self._pwmpin).split("PWMFREQ ")[1])
def _set_frequency(self, frequency):
if not isinstance(frequency, (int, float)):
raise TypeError("Invalid frequency type, should be int or float.")
PWMOut._nova.setIOpinPWMFreq(self._pwmpin, frequency)
frequency = property(_get_frequency, _set_frequency)
"""Get or set the PWM's output frequency in Hertz.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
:type: int, float
"""
def _get_enabled(self):
enabled = self._enable
if enabled == "1":
return True
if enabled == "0":
return False
raise PWMError(None, 'Unknown enabled value: "%s"' % enabled)
def _set_enabled(self, value):
"""Get or set the PWM's output enabled state.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not bool.
:type: bool
"""
if not isinstance(value, bool):
raise TypeError("Invalid enabled type, should be string.")
self._enable = value
if not self._enable:
self._set_duty_cycle(0.0)
# String representation
def __str__(self):
return "PWM%d, pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
self._pin,
self._pin,
self.frequency,
self.duty_cycle * 100,
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/nova/pwmout.py | pwmout.py |
"""UART Class for Binho Nova"""
from adafruit_blinka.microcontroller.nova import Connection
class UART:
"""Custom UART Class for Binho Nova"""
ESCAPE_SEQUENCE = "+++UART0"
# pylint: disable=too-many-arguments,unused-argument
def __init__(
self,
portid,
baudrate=9600,
bits=8,
parity=None,
stop=1,
timeout=1000,
read_buf_len=None,
flow=None,
):
self._nova = Connection.getInstance()
self._id = portid
self._baudrate = baudrate
self._parity = parity
self._bits = bits
self._stop = stop
self._timeout = timeout
if flow is not None: # default 0
raise NotImplementedError(
"Parameter '{}' unsupported on Binho Nova".format("flow")
)
self._nova.setOperationMode(self._id, "UART")
self._nova.setBaudRateUART(self._id, baudrate)
self._nova.setDataBitsUART(self._id, bits)
self._nova.setParityUART(self._id, parity)
self._nova.setStopBitsUART(self._id, stop)
self._nova.setEscapeSequenceUART(self._id, UART.ESCAPE_SEQUENCE)
self._nova.beginBridgeUART(self._id)
# pylint: enable=too-many-arguments,unused-argument
def __del__(self):
"""Close Nova on delete"""
self.deinit()
self._nova.close()
def deinit(self):
"""Deinitialize"""
self._nova.writeBridgeUART(UART.ESCAPE_SEQUENCE)
self._nova.stopBridgeUART(UART.ESCAPE_SEQUENCE)
def read(self, nbytes=None):
"""Read data from UART and return it"""
if nbytes is None:
return None
data = bytearray()
for _ in range(nbytes):
data.append(ord(self._nova.readBridgeUART()))
return data
def readinto(self, buf, nbytes=None):
"""Read data from UART and into the buffer"""
if nbytes is None:
return None
for _ in range(nbytes):
buf.append(ord(self._nova.readBridgeUART()))
return buf
def readline(self):
"""Read a single line of data from UART"""
out = self._nova.readBridgeUART()
line = out
while out != "\r":
out = self._nova.readBridgeUART()
line += out
return line
def write(self, buf):
"""Write data from the buffer to UART"""
return self._nova.writeBridgeUART(buf) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/nova/uart.py | uart.py |
"""I2C Class for Binho Nova"""
from adafruit_blinka.microcontroller.nova import Connection
class I2C:
"""Custom I2C Class for Binho Nova"""
WHR_PAYLOAD_MAX_LENGTH = 1024
def __init__(self, *, frequency=400000):
self._nova = Connection.getInstance()
self._nova.setNumericalBase(10)
self._nova.setOperationMode(0, "I2C")
self._nova.setPullUpStateI2C(0, "EN")
self._nova.setClockI2C(0, frequency)
self._novaCMDVer = "0"
if hasattr(self._nova, "getCommandVer"):
response = self._nova.getCommandVer().split(" ")
if response[0] != "-NG":
self._novaCMDVer = response[1]
def __del__(self):
"""Close Nova on delete"""
self._nova.close()
def scan(self):
"""Perform an I2C Device Scan"""
scanResults = []
for i in range(8, 121):
result = self._nova.scanAddrI2C(0, i << 1)
resp = result.split(" ")
if resp[3] == "OK":
scanResults.append(i)
return scanResults
def writeto(self, address, buffer, *, start=0, end=None, stop=True):
"""Write data from the buffer to an address"""
end = end if end else len(buffer)
readBytes = 0
if int(self._novaCMDVer) >= 1:
chunks, rest = divmod(end - start, self.WHR_PAYLOAD_MAX_LENGTH)
for i in range(chunks):
chunk_start = start + i * self.WHR_PAYLOAD_MAX_LENGTH
chunk_end = chunk_start + self.WHR_PAYLOAD_MAX_LENGTH
self._nova.writeToReadFromI2C(
0,
address << 1,
stop,
readBytes,
chunk_end - chunk_start,
buffer[chunk_start:chunk_end],
)
if rest:
self._nova.writeToReadFromI2C(
0, address << 1, stop, readBytes, rest, buffer[-1 * rest :]
)
else:
self._nova.startI2C(0, address << 1)
for i in range(start, end):
self._nova.writeByteI2C(0, buffer[i])
if stop:
self._nova.endI2C(0)
else:
self._nova.endI2C(0, True)
# pylint: disable=unused-argument
def readfrom_into(self, address, buffer, *, start=0, end=None, stop=True):
"""Read data from an address and into the buffer"""
end = end if end else len(buffer)
result = self._nova.readBytesI2C(0, address << 1, len(buffer[start:end]))
if result != "-NG":
resp = result.split(" ")
for i in range(len(buffer[start:end])):
buffer[start + i] = int(resp[2 + i])
else:
raise RuntimeError(
"Received error response from Binho Nova, result = " + result
)
# pylint: disable=too-many-locals,too-many-branches
def writeto_then_readfrom(
self,
address,
buffer_out,
buffer_in,
*,
out_start=0,
out_end=None,
in_start=0,
in_end=None,
stop=False,
):
"""Write data from buffer_out to an address and then
read data from an address and into buffer_in
"""
out_end = out_end if out_end else len(buffer_out)
in_end = in_end if in_end else len(buffer_in)
if int(self._novaCMDVer) >= 1:
totalIn = in_end - in_start
totalOut = out_end - out_start
totalBytes = totalIn
if totalOut > totalIn:
totalBytes = totalOut
chunks, rest = divmod(totalBytes, self.WHR_PAYLOAD_MAX_LENGTH)
if rest > 0:
chunks += 1
for i in range(chunks):
# calculate the number of bytes to be written and read
numInBytes = self.WHR_PAYLOAD_MAX_LENGTH
if totalIn < self.WHR_PAYLOAD_MAX_LENGTH:
numInBytes = totalIn
numOutBytes = self.WHR_PAYLOAD_MAX_LENGTH
if totalOut < self.WHR_PAYLOAD_MAX_LENGTH:
numOutBytes = totalOut
# setup the buffer out chunk offset
buffer = "0"
if numOutBytes > 0:
chunk_start = out_start + i * self.WHR_PAYLOAD_MAX_LENGTH
chunk_end = chunk_start + numOutBytes
buffer = buffer_out[chunk_start:chunk_end]
result = self._nova.writeToReadFromI2C(
0, address << 1, stop, numInBytes, numOutBytes, buffer
)
totalIn -= numInBytes
totalOut -= numOutBytes
if result != "-NG":
if numInBytes:
resp = result.split(" ")
resp = resp[2]
for j in range(numInBytes):
buffer_in[
in_start + i * self.WHR_PAYLOAD_MAX_LENGTH + j
] = int(resp[j * 2] + resp[j * 2 + 1], 16)
else:
raise RuntimeError(
"Received error response from Binho Nova, result = " + result
)
else:
self._nova.startI2C(0, address << 1)
for i in range(out_start, out_end):
self._nova.writeByteI2C(0, buffer_out[i])
if stop:
self._nova.endI2C(0)
else:
self._nova.endI2C(0, True)
result = self._nova.readBytesI2C(
0, address << 1, len(buffer_in[in_start:in_end])
)
if result != "-NG":
resp = result.split(" ")
for i in range(len(buffer_in[in_start:in_end])):
buffer_in[in_start + i] = int(resp[2 + i])
else:
raise RuntimeError(
"Received error response from Binho Nova, result = " + result
)
# pylint: enable=unused-argument,too-many-locals,too-many-branches | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/nova/i2c.py | i2c.py |
"""SPI Class for Binho Nova"""
from adafruit_blinka.microcontroller.nova import Connection
class SPI:
"""Custom SPI Class for Binho Nova"""
MSB = 0
BUFFER_PAYLOAD_MAX_LENGTH = 64
WHR_PAYLOAD_MAX_LENGTH = 1024
def __init__(self, clock):
self._nova = Connection.getInstance()
self._nova.setNumericalBase(10)
self._nova.setOperationMode(0, "SPI")
self._nova.setClockSPI(0, clock)
self._nova.setModeSPI(0, 0)
self._nova.setIOpinMode(0, "DOUT")
self._nova.setIOpinMode(1, "DOUT")
self._nova.beginSPI(0)
self._novaCMDVer = "0"
if hasattr(self._nova, "getCommandVer"):
response = self._nova.getCommandVer().split(" ")
if response[0] != "-NG":
self._novaCMDVer = response[1]
# Cpol and Cpha set by mode
# Mode Cpol Cpha
# 0 0 0
# 1 0 1
# 2 1 0
# 3 1 1
def __del__(self):
"""Close Nova on delete"""
self._nova.close()
# pylint: disable=too-many-arguments,unused-argument
def init(
self,
baudrate=1000000,
polarity=0,
phase=0,
bits=8,
firstbit=MSB,
sck=None,
mosi=None,
miso=None,
):
"""Initialize the Port"""
self._nova.setClockSPI(0, baudrate)
self._nova.setModeSPI(0, (polarity << 1) | (phase))
# pylint: enable=too-many-arguments,unused-argument
@staticmethod
def get_received_data(lineOutput):
"""Return any received data"""
return lineOutput.split("RXD ")[1]
@property
def frequency(self):
"""Return the current frequency"""
return self._nova.getClockSPI(0).split("CLK ")[1]
def write(self, buf, start=0, end=None):
"""Write data from the buffer to SPI"""
end = end if end else len(buf)
payloadMaxLength = self.BUFFER_PAYLOAD_MAX_LENGTH
if int(self._novaCMDVer) >= 1:
payloadMaxLength = self.WHR_PAYLOAD_MAX_LENGTH
chunks, rest = divmod(end - start, payloadMaxLength)
for i in range(chunks):
chunk_start = start + i * payloadMaxLength
chunk_end = chunk_start + payloadMaxLength
if int(self._novaCMDVer) >= 1:
self._nova.writeToReadFromSPI(
0, True, False, chunk_end - chunk_start, buf[chunk_start:chunk_end]
)
else:
self._nova.clearBuffer(0)
self._nova.writeToBuffer(0, 0, buf[chunk_start:chunk_end])
self._nova.transferBufferSPI(0, chunk_end - chunk_start + 1)
if rest:
if int(self._novaCMDVer) >= 1:
self._nova.writeToReadFromSPI(0, True, False, rest, buf[-1 * rest :])
else:
self._nova.clearBuffer(0)
self._nova.writeToBuffer(0, 0, buf[-1 * rest :])
self._nova.transferBufferSPI(0, rest)
def readinto(self, buf, start=0, end=None, write_value=0):
"""Read data from SPI and into the buffer"""
end = end if end else len(buf)
if int(self._novaCMDVer) >= 1:
chunks, rest = divmod(end - start, self.WHR_PAYLOAD_MAX_LENGTH)
i = 0
for i in range(chunks):
chunk_start = start + i * self.WHR_PAYLOAD_MAX_LENGTH
chunk_end = chunk_start + self.WHR_PAYLOAD_MAX_LENGTH
result = self._nova.writeToReadFromSPI(
0, False, True, chunk_end - chunk_start, write_value
)
if result != "-NG":
resp = result.split(" ")
resp = resp[2]
# loop over half of resp len as we're reading 2 chars at a time to form a byte
loops = int(len(resp) / 2)
for j in range(loops):
buf[(i * self.WHR_PAYLOAD_MAX_LENGTH) + start + j] = int(
resp[j * 2] + resp[j * 2 + 1], 16
)
else:
raise RuntimeError(
"Received error response from Binho Nova, result = " + result
)
if rest:
result = self._nova.writeToReadFromSPI(
0, False, True, rest, write_value
)
if result != "-NG":
resp = result.split(" ")
resp = resp[2]
# loop over half of resp len as we're reading 2 chars at a time to form a byte
loops = int(len(resp) / 2)
for j in range(loops):
buf[(i * self.WHR_PAYLOAD_MAX_LENGTH) + start + j] = int(
resp[j * 2] + resp[j * 2 + 1], 16
)
else:
raise RuntimeError(
"Received error response from Binho Nova, result = " + result
)
else:
for i in range(start, end):
buf[start + i] = int(
self.get_received_data(self._nova.transferSPI(0, write_value))
)
# pylint: disable=too-many-arguments,too-many-locals,too-many-branches
def write_readinto(
self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
):
"""Perform a half-duplex write from buffer_out and then
read data into buffer_in
"""
out_end = out_end if out_end else len(buffer_out)
in_end = in_end if in_end else len(buffer_in)
readlen = in_end - in_start
writelen = out_end - out_start
if readlen > writelen:
# resize out and pad with 0's
tmp = bytearray(buffer_out)
tmp.extend([0] * (readlen - len(buffer_out)))
buffer_out = tmp
if int(self._novaCMDVer) >= 1:
chunks, rest = divmod(len(buffer_out), self.WHR_PAYLOAD_MAX_LENGTH)
i = 0
for i in range(chunks):
chunk_start = out_start + i * self.WHR_PAYLOAD_MAX_LENGTH
chunk_end = chunk_start + self.WHR_PAYLOAD_MAX_LENGTH
result = self._nova.writeToReadFromSPI(
0,
True,
True,
chunk_end - chunk_start,
buffer_out[chunk_start:chunk_end],
)
if result != "-NG":
resp = result.split(" ")
resp = resp[2]
# loop over half of resp len as we're reading 2 chars at a time to form a byte
loops = int(len(resp) / 2)
for j in range(loops):
buffer_in[
(i * self.WHR_PAYLOAD_MAX_LENGTH) + in_start + j
] = int(resp[j * 2] + resp[j * 2 + 1], 16)
else:
raise RuntimeError(
"Received error response from Binho Nova, result = " + result
)
if rest:
result = self._nova.writeToReadFromSPI(
0, True, True, rest, buffer_out[-1 * rest :]
)
if result != "-NG":
resp = result.split(" ")
resp = resp[2]
# loop over half of resp len as we're reading 2 chars at a time to form a byte
loops = int(len(resp) / 2)
for j in range(loops):
buffer_in[
(i * self.WHR_PAYLOAD_MAX_LENGTH) + in_start + j
] = int(resp[j * 2] + resp[j * 2 + 1], 16)
else:
raise RuntimeError(
"Received error response from Binho Nova, result = " + result
)
print(buffer_in)
else:
for data_out in buffer_out:
data_in = int(
self.get_received_data(self._nova.transferSPI(0, data_out))
)
if i < readlen:
buffer_in[in_start + i] = data_in
i += 1
# pylint: enable=too-many-arguments,too-many-locals,too-many-branches | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/nova/spi.py | spi.py |
"""BCM283x NeoPixel Driver Class"""
import time
import atexit
import _rpi_ws281x as ws
# LED configuration.
# pylint: disable=redefined-outer-name,too-many-branches,too-many-statements
# pylint: disable=global-statement,protected-access
LED_CHANNEL = 0
LED_FREQ_HZ = 800000 # Frequency of the LED signal. We only support 800KHz
LED_DMA_NUM = 10 # DMA channel to use, can be 0-14.
LED_BRIGHTNESS = 255 # We manage the brightness in the neopixel library
LED_INVERT = 0 # We don't support inverted logic
LED_STRIP = None # We manage the color order within the neopixel library
# a 'static' object that we will use to manage our PWM DMA channel
# we only support one LED strip per raspi
_led_strip = None
_buf = None
def neopixel_write(gpio, buf):
"""NeoPixel Writing Function"""
global _led_strip # we'll have one strip we init if its not at first
global _buf # we save a reference to the buf, and if it changes we will cleanup and re-init.
if _led_strip is None or buf is not _buf:
# This is safe to call since it doesn't do anything if _led_strip is None
neopixel_cleanup()
# Create a ws2811_t structure from the LED configuration.
# Note that this structure will be created on the heap so you
# need to be careful that you delete its memory by calling
# delete_ws2811_t when it's not needed.
_led_strip = ws.new_ws2811_t()
_buf = buf
# Initialize all channels to off
for channum in range(2):
channel = ws.ws2811_channel_get(_led_strip, channum)
ws.ws2811_channel_t_count_set(channel, 0)
ws.ws2811_channel_t_gpionum_set(channel, 0)
ws.ws2811_channel_t_invert_set(channel, 0)
ws.ws2811_channel_t_brightness_set(channel, 0)
channel = ws.ws2811_channel_get(_led_strip, LED_CHANNEL)
# Initialize the channel in use
count = 0
if len(buf) % 3 == 0:
# most common, divisible by 3 is likely RGB
LED_STRIP = ws.WS2811_STRIP_RGB
count = len(buf) // 3
elif len(buf) % 4 == 0:
LED_STRIP = ws.SK6812_STRIP_RGBW
count = len(buf) // 4
else:
raise RuntimeError("We only support 3 or 4 bytes-per-pixel")
ws.ws2811_channel_t_count_set(
channel, count
) # we manage 4 vs 3 bytes in the library
ws.ws2811_channel_t_gpionum_set(channel, gpio._pin.id)
ws.ws2811_channel_t_invert_set(channel, LED_INVERT)
ws.ws2811_channel_t_brightness_set(channel, LED_BRIGHTNESS)
ws.ws2811_channel_t_strip_type_set(channel, LED_STRIP)
# Initialize the controller
ws.ws2811_t_freq_set(_led_strip, LED_FREQ_HZ)
ws.ws2811_t_dmanum_set(_led_strip, LED_DMA_NUM)
resp = ws.ws2811_init(_led_strip)
if resp != ws.WS2811_SUCCESS:
if resp == -5:
raise RuntimeError(
"NeoPixel support requires running with sudo, please try again!"
)
message = ws.ws2811_get_return_t_str(resp)
raise RuntimeError(
"ws2811_init failed with code {0} ({1})".format(resp, message)
)
atexit.register(neopixel_cleanup)
channel = ws.ws2811_channel_get(_led_strip, LED_CHANNEL)
if gpio._pin.id != ws.ws2811_channel_t_gpionum_get(channel):
raise RuntimeError("Raspberry Pi neopixel support is for one strip only!")
if ws.ws2811_channel_t_strip_type_get(channel) == ws.WS2811_STRIP_RGB:
bpp = 3
else:
bpp = 4
# assign all colors!
for i in range(len(buf) // bpp):
r = buf[bpp * i]
g = buf[bpp * i + 1]
b = buf[bpp * i + 2]
if bpp == 3:
pixel = (r << 16) | (g << 8) | b
else:
w = buf[bpp * i + 3]
pixel = (w << 24) | (r << 16) | (g << 8) | b
ws.ws2811_led_set(channel, i, pixel)
resp = ws.ws2811_render(_led_strip)
if resp != ws.WS2811_SUCCESS:
message = ws.ws2811_get_return_t_str(resp)
raise RuntimeError(
"ws2811_render failed with code {0} ({1})".format(resp, message)
)
time.sleep(0.001 * ((len(buf) // 100) + 1)) # about 1ms per 100 bytes
def neopixel_cleanup():
"""Cleanup when we're done"""
global _led_strip
if _led_strip is not None:
# Ensure ws2811_fini is called before the program quits.
ws.ws2811_fini(_led_strip)
# Example of calling delete function to clean up structure memory. Isn't
# strictly necessary at the end of the program execution here, but is good practice.
ws.delete_ws2811_t(_led_strip)
_led_strip = None | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/bcm283x/neopixel.py | neopixel.py |
"""Broadcom BCM283x pin names"""
from RPi import GPIO
GPIO.setmode(GPIO.BCM) # Use BCM pins D4 = GPIO #4
GPIO.setwarnings(False) # shh!
class Pin:
"""Pins dont exist in CPython so...lets make our own!"""
IN = 0
OUT = 1
LOW = 0
HIGH = 1
PULL_NONE = 0
PULL_UP = 1
PULL_DOWN = 2
id = None
_value = LOW
_mode = IN
def __init__(self, bcm_number):
self.id = bcm_number
def __repr__(self):
return str(self.id)
def __eq__(self, other):
return self.id == other
def init(self, mode=IN, pull=None):
"""Initialize the Pin"""
if mode is not None:
if mode == self.IN:
self._mode = self.IN
GPIO.setup(self.id, GPIO.IN)
elif mode == self.OUT:
self._mode = self.OUT
GPIO.setup(self.id, GPIO.OUT)
else:
raise RuntimeError("Invalid mode for pin: %s" % self.id)
if pull is not None:
if self._mode != self.IN:
raise RuntimeError("Cannot set pull resistor on output")
if pull == self.PULL_UP:
GPIO.setup(self.id, GPIO.IN, pull_up_down=GPIO.PUD_UP)
elif pull == self.PULL_DOWN:
GPIO.setup(self.id, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
else:
raise RuntimeError("Invalid pull for pin: %s" % self.id)
def value(self, val=None):
"""Set or return the Pin Value"""
if val is not None:
if val == self.LOW:
self._value = val
GPIO.output(self.id, val)
elif val == self.HIGH:
self._value = val
GPIO.output(self.id, val)
else:
raise RuntimeError("Invalid value for pin")
return None
return GPIO.input(self.id)
# Pi 1B rev1 only?
D0 = Pin(0)
D1 = Pin(1)
D2 = Pin(2)
SDA = Pin(2)
D3 = Pin(3)
SCL = Pin(3)
D4 = Pin(4)
D5 = Pin(5)
D6 = Pin(6)
D7 = Pin(7)
CE1 = Pin(7)
D8 = Pin(8)
CE0 = Pin(8)
D9 = Pin(9)
MISO = Pin(9)
D10 = Pin(10)
MOSI = Pin(10)
D11 = Pin(11)
SCLK = Pin(11) # Raspberry Pi naming
SCK = Pin(11) # CircuitPython naming
D12 = Pin(12)
D13 = Pin(13)
D14 = Pin(14)
TXD = Pin(14)
D15 = Pin(15)
RXD = Pin(15)
D16 = Pin(16)
D17 = Pin(17)
D18 = Pin(18)
D19 = Pin(19)
MISO_1 = Pin(19)
D20 = Pin(20)
MOSI_1 = Pin(20)
D21 = Pin(21)
SCLK_1 = Pin(21)
SCK_1 = Pin(21)
D22 = Pin(22)
D23 = Pin(23)
D24 = Pin(24)
D25 = Pin(25)
D26 = Pin(26)
D27 = Pin(27)
D28 = Pin(28)
D29 = Pin(29)
D30 = Pin(30)
D31 = Pin(31)
D32 = Pin(32)
D33 = Pin(33)
D34 = Pin(34)
D35 = Pin(35)
D36 = Pin(36)
D37 = Pin(37)
D38 = Pin(38)
D39 = Pin(39)
D40 = Pin(40)
MISO_2 = Pin(40)
D41 = Pin(41)
MOSI_2 = Pin(41)
D42 = Pin(42)
SCLK_2 = Pin(42)
SCK_2 = Pin(43)
D43 = Pin(43)
D44 = Pin(44)
D45 = Pin(45)
# ordered as spiId, sckId, mosiId, misoId
spiPorts = (
(0, SCLK, MOSI, MISO),
(1, SCLK_1, MOSI_1, MISO_1),
(2, SCLK_2, MOSI_2, MISO_2),
)
# ordered as uartId, txId, rxId
uartPorts = ((1, TXD, RXD),)
# These are the known hardware I2C ports / pins.
# For software I2C ports created with the i2c-gpio overlay, see:
# https://github.com/adafruit/Adafruit_Python_Extended_Bus
i2cPorts = (
(1, SCL, SDA),
(0, D1, D0), # both pi 1 and pi 2 i2c ports!
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/bcm283x/pin.py | pin.py |
"""Custom PWMOut Wrapper for Rpi.GPIO PWM Class"""
from RPi import GPIO
GPIO.setmode(GPIO.BCM) # Use BCM pins D4 = GPIO #4
GPIO.setwarnings(False) # shh!
# pylint: disable=unnecessary-pass
class PWMError(IOError):
"""Base class for PWM errors."""
pass
# pylint: enable=unnecessary-pass
class PWMOut:
"""Pulse Width Modulation Output Class"""
def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
self._pwmpin = None
self._period = 0
self._open(pin, duty_cycle, frequency, variable_frequency)
def __del__(self):
self.deinit()
def __enter__(self):
return self
def __exit__(self, t, value, traceback):
self.deinit()
def _open(self, pin, duty=0, freq=500, variable_frequency=False):
self._pin = pin
GPIO.setup(pin.id, GPIO.OUT)
self._pwmpin = GPIO.PWM(pin.id, freq)
if variable_frequency:
print("Variable Frequency is not supported, continuing without it...")
# set frequency
self.frequency = freq
# set duty
self.duty_cycle = duty
self.enabled = True
def deinit(self):
"""Deinit the PWM."""
if self._pwmpin is not None:
self._pwmpin.stop()
GPIO.cleanup(self._pin.id)
self._pwmpin = None
def _is_deinited(self):
if self._pwmpin is None:
raise ValueError(
"Object has been deinitialize and can no longer "
"be used. Create a new object."
)
@property
def period(self):
"""Get or set the PWM's output period in seconds.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
:type: int, float
"""
return 1.0 / self.frequency
@period.setter
def period(self, period):
if not isinstance(period, (int, float)):
raise TypeError("Invalid period type, should be int or float.")
self.frequency = 1.0 / period
@property
def duty_cycle(self):
"""Get or set the PWM's output duty cycle which is the fraction of
each pulse which is high. 16-bit
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
ValueError: if value is out of bounds of 0.0 to 1.0.
:type: int, float
"""
return int(self._duty_cycle * 65535)
@duty_cycle.setter
def duty_cycle(self, duty_cycle):
if not isinstance(duty_cycle, (int, float)):
raise TypeError("Invalid duty cycle type, should be int or float.")
if not 0 <= duty_cycle <= 65535:
raise ValueError("Invalid duty cycle value, should be between 0 and 65535")
# convert from 16-bit
duty_cycle /= 65535.0
self._duty_cycle = duty_cycle
self._pwmpin.ChangeDutyCycle(round(self._duty_cycle * 100))
@property
def frequency(self):
"""Get or set the PWM's output frequency in Hertz.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
:type: int, float
"""
return self._frequency
@frequency.setter
def frequency(self, frequency):
if not isinstance(frequency, (int, float)):
raise TypeError("Invalid frequency type, should be int or float.")
self._pwmpin.ChangeFrequency(round(frequency))
self._frequency = frequency
@property
def enabled(self):
"""Get or set the PWM's output enabled state.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not bool.
:type: bool
"""
return self._enabled
@enabled.setter
def enabled(self, value):
if not isinstance(value, bool):
raise TypeError("Invalid enabled type, should be string.")
if value:
self._pwmpin.start(round(self._duty_cycle * 100))
else:
self._pwmpin.stop()
self._enabled = value
# String representation
def __str__(self):
return "pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
self._pin,
self.frequency,
self.duty_cycle,
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/bcm283x/pwmio/PWMOut.py | PWMOut.py |
"""Custom PulseIn Class to read PWM signals"""
import time
import subprocess
import os
import atexit
import random
import struct
import sysv_ipc
DEBUG = False
queues = []
procs = []
# The message queues live outside of python space, and must be formally cleaned!
def final():
"""In case the program is cancelled or quit, we need to clean up the PulseIn
helper process and also the message queue, this is called at exit to do so"""
if DEBUG:
print("Cleaning up message queues", queues)
print("Cleaning up processes", procs)
for q in queues:
q.remove()
for proc in procs:
proc.terminate()
atexit.register(final)
# pylint: disable=c-extension-no-member
class PulseIn:
"""PulseIn Class to read PWM signals"""
def __init__(self, pin, maxlen=2, idle_state=False):
"""Create a PulseIn object associated with the given pin.
The object acts as a read-only sequence of pulse lengths with
a given max length. When it is active, new pulse lengths are
added to the end of the list. When there is no more room
(len() == maxlen) the oldest pulse length is removed to make room."""
self._pin = pin
self._maxlen = maxlen
self._idle_state = idle_state
self._queue_key = random.randint(1, 9999)
try:
self._mq = sysv_ipc.MessageQueue(None, flags=sysv_ipc.IPC_CREX)
if DEBUG:
print("Message Queue Key: ", self._mq.key)
queues.append(self._mq)
except sysv_ipc.ExistentialError:
raise RuntimeError(
"Message queue creation failed"
) from sysv_ipc.ExistentialError
# Check if OS is 64-bit
if struct.calcsize("P") * 8 == 64: # pylint: disable=no-member
libgpiod_filename = "libgpiod_pulsein64"
else:
libgpiod_filename = "libgpiod_pulsein"
dir_path = os.path.dirname(os.path.realpath(__file__))
cmd = [
dir_path + "/" + libgpiod_filename,
"--pulses",
str(maxlen),
"--queue",
str(self._mq.key),
]
if idle_state:
cmd.append("-i")
cmd.append("gpiochip0")
cmd.append(str(pin))
if DEBUG:
print(cmd)
self._process = subprocess.Popen(cmd) # pylint: disable=consider-using-with
procs.append(self._process)
# wait for it to start up
if DEBUG:
print("Waiting for startup success message from subprocess")
message = self._wait_receive_msg(timeout=0.25)
if message[0] != b"!":
raise RuntimeError("Could not establish message queue with subprocess")
self._paused = False
# pylint: disable=redefined-builtin
def _wait_receive_msg(self, timeout=0, type=2):
"""Internal helper that will wait for new messages of a given type,
and throw an exception on timeout"""
if timeout > 0:
stamp = time.monotonic()
while (time.monotonic() - stamp) < timeout:
try:
message = self._mq.receive(block=False, type=type)
return message
except sysv_ipc.BusyError:
time.sleep(0.001) # wait a bit then retry!
# uh-oh timed out
raise RuntimeError(
"Timed out waiting for PulseIn message. Make sure libgpiod is installed."
)
message = self._mq.receive(block=True, type=type)
return message
# pylint: enable=redefined-builtin
def deinit(self):
"""Deinitialises the PulseIn and releases any hardware and software
resources for reuse."""
# Clean up after ourselves
self._process.terminate()
procs.remove(self._process)
self._mq.remove()
queues.remove(self._mq)
def __enter__(self):
"""No-op used by Context Managers."""
return self
def __exit__(self, exc_type, exc_value, tb):
"""Automatically deinitializes the hardware when exiting a context."""
self.deinit()
def resume(self, trigger_duration=0):
"""Resumes pulse capture after an optional trigger pulse."""
if trigger_duration != 0:
self._mq.send("t%d" % trigger_duration, True, type=1)
else:
self._mq.send("r", True, type=1)
self._paused = False
def pause(self):
"""Pause pulse capture"""
self._mq.send("p", True, type=1)
self._paused = True
@property
def paused(self):
"""True when pulse capture is paused as a result of pause() or
an error during capture such as a signal that is too fast."""
return self._paused
@property
def maxlen(self):
"""The maximum length of the PulseIn. When len() is equal to maxlen,
it is unclear which pulses are active and which are idle."""
return self._maxlen
def clear(self):
"""Clears all captured pulses"""
self._mq.send("c", True, type=1)
def popleft(self):
"""Removes and returns the oldest read pulse."""
self._mq.send("^", True, type=1)
message = self._wait_receive_msg()
reply = int(message[0].decode("utf-8"))
# print(reply)
if reply == -1:
raise IndexError("pop from empty list")
return reply
def __len__(self):
"""Returns the current pulse length"""
self._mq.send("l", True, type=1)
message = self._wait_receive_msg()
return int(message[0].decode("utf-8"))
# pylint: disable=redefined-builtin
def __getitem__(self, index, type=None):
"""Returns the value at the given index or values in slice."""
self._mq.send("i%d" % index, True, type=1)
message = self._wait_receive_msg()
ret = int(message[0].decode("utf-8"))
if ret == -1:
raise IndexError("list index out of range")
return ret
# pylint: enable=redefined-builtin | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py | PulseIn.py |
"""SnapDragon APQ8016 pin names"""
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
GPIO_0 = Pin((0, 0))
GPIO_1 = Pin((0, 1))
GPIO_2 = Pin((0, 2))
GPIO_3 = Pin((0, 3))
GPIO_4 = Pin((0, 4))
GPIO_5 = Pin((0, 5))
GPIO_6 = Pin((0, 6))
GPIO_7 = Pin((0, 7))
GPIO_8 = Pin((0, 8))
GPIO_9 = Pin((0, 9))
GPIO_10 = Pin((0, 10))
GPIO_11 = Pin((0, 11))
GPIO_12 = Pin((0, 12))
GPIO_13 = Pin((0, 13))
GPIO_14 = Pin((0, 14))
GPIO_15 = Pin((0, 15))
GPIO_16 = Pin((0, 16))
GPIO_17 = Pin((0, 17))
GPIO_18 = Pin((0, 18))
GPIO_19 = Pin((0, 19))
GPIO_20 = Pin((0, 20))
GPIO_22 = Pin((0, 22))
GPIO_23 = Pin((0, 23))
GPIO_24 = Pin((0, 24))
GPIO_25 = Pin((0, 25))
GPIO_26 = Pin((0, 26))
GPIO_27 = Pin((0, 27))
GPIO_28 = Pin((0, 28))
GPIO_29 = Pin((0, 29))
GPIO_30 = Pin((0, 30))
GPIO_33 = Pin((0, 33))
GPIO_34 = Pin((0, 34))
GPIO_35 = Pin((0, 35))
GPIO_36 = Pin((0, 36))
GPIO_37 = Pin((0, 37))
GPIO_39 = Pin((0, 39))
GPIO_40 = Pin((0, 40))
GPIO_41 = Pin((0, 41))
GPIO_42 = Pin((0, 42))
GPIO_43 = Pin((0, 43))
GPIO_44 = Pin((0, 44))
GPIO_45 = Pin((0, 45))
GPIO_46 = Pin((0, 46))
GPIO_47 = Pin((0, 47))
GPIO_48 = Pin((0, 48))
GPIO_49 = Pin((0, 49))
GPIO_50 = Pin((0, 50))
GPIO_51 = Pin((0, 51))
GPIO_52 = Pin((0, 52))
GPIO_53 = Pin((0, 53))
GPIO_54 = Pin((0, 54))
GPIO_55 = Pin((0, 55))
GPIO_56 = Pin((0, 56))
GPIO_57 = Pin((0, 57))
GPIO_58 = Pin((0, 58))
GPIO_59 = Pin((0, 59))
GPIO_60 = Pin((0, 60))
GPIO_61 = Pin((0, 61))
GPIO_62 = Pin((0, 62))
GPIO_63 = Pin((0, 63))
GPIO_64 = Pin((0, 64))
GPIO_65 = Pin((0, 65))
GPIO_66 = Pin((0, 66))
GPIO_67 = Pin((0, 67))
GPIO_68 = Pin((0, 68))
GPIO_69 = Pin((0, 69))
GPIO_70 = Pin((0, 70))
GPIO_71 = Pin((0, 71))
GPIO_72 = Pin((0, 72))
GPIO_73 = Pin((0, 73))
GPIO_74 = Pin((0, 74))
GPIO_75 = Pin((0, 75))
GPIO_76 = Pin((0, 76))
GPIO_77 = Pin((0, 77))
GPIO_78 = Pin((0, 78))
GPIO_79 = Pin((0, 79))
GPIO_80 = Pin((0, 80))
GPIO_81 = Pin((0, 81))
GPIO_82 = Pin((0, 82))
GPIO_83 = Pin((0, 83))
GPIO_84 = Pin((0, 84))
GPIO_85 = Pin((0, 85))
GPIO_86 = Pin((0, 86))
GPIO_87 = Pin((0, 87))
GPIO_88 = Pin((0, 88))
GPIO_89 = Pin((0, 89))
GPIO_90 = Pin((0, 90))
GPIO_91 = Pin((0, 91))
GPIO_92 = Pin((0, 92))
GPIO_93 = Pin((0, 93))
GPIO_94 = Pin((0, 94))
GPIO_95 = Pin((0, 95))
GPIO_96 = Pin((0, 96))
GPIO_97 = Pin((0, 97))
GPIO_98 = Pin((0, 98))
GPIO_99 = Pin((0, 99))
GPIO_100 = Pin((0, 100))
GPIO_101 = Pin((0, 101))
GPIO_102 = Pin((0, 102))
GPIO_103 = Pin((0, 103))
GPIO_104 = Pin((0, 104))
GPIO_105 = Pin((0, 105))
GPIO_106 = Pin((0, 106))
GPIO_108 = Pin((0, 108))
GPIO_109 = Pin((0, 109))
GPIO_110 = Pin((0, 110))
GPIO_111 = Pin((0, 111))
GPIO_112 = Pin((0, 112))
GPIO_113 = Pin((0, 113))
GPIO_114 = Pin((0, 114))
GPIO_115 = Pin((0, 115))
GPIO_116 = Pin((0, 116))
GPIO_117 = Pin((0, 117))
GPIO_118 = Pin((0, 118))
GPIO_119 = Pin((0, 119))
PM_GPIO_0 = Pin((1, 0))
PM_GPIO_1 = Pin((1, 1))
PM_GPIO_2 = Pin((1, 2))
PM_GPIO_3 = Pin((1, 3))
PM_MPP_1 = Pin((2, 0))
PM_MPP_2 = Pin((2, 1))
PM_MPP_3 = Pin((2, 2))
PM_MPP_4 = Pin((2, 3))
I2C0_SDA = GPIO_6
I2C0_SCL = GPIO_7
I2C1_SDA = GPIO_22
I2C1_SCL = GPIO_23
UART0_TX = GPIO_0
UART0_RX = GPIO_1
UART1_TX = GPIO_4
UART1_RX = GPIO_5
SPI0_SCLK = GPIO_19
SPI0_MISO = GPIO_17
SPI0_MOSI = GPIO_16
SPI0_CS = GPIO_18
i2cPorts = (
(0, I2C0_SCL, I2C0_SDA),
(1, I2C1_SCL, I2C1_SDA),
)
# ordered as spiId, sckId, mosiId, misoId
spiPorts = ((0, SPI0_SCLK, SPI0_MOSI, SPI0_MISO),)
# ordered as uartId, txId, rxId
uartPorts = (
(0, UART0_TX, UART0_RX),
(1, UART1_TX, UART1_RX),
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/snapdragon/apq8016/pin.py | pin.py |
"""Allwinner H616 Pin Names"""
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
PC0 = Pin((1, 64))
SPI0_SCLK = PC0
PC1 = Pin((1, 65))
PC2 = Pin((1, 66))
SPI0_MOSI = PC2
PC3 = Pin((1, 67))
SPI0_CS0 = PC3
PC4 = Pin((1, 68))
SPI0_MISO = PC4
PC5 = Pin((1, 69))
PC6 = Pin((1, 70))
PC7 = Pin((1, 71))
PC8 = Pin((1, 72))
PC9 = Pin((1, 73))
PC10 = Pin((1, 74))
PC11 = Pin((1, 75))
PC12 = Pin((1, 76))
PC13 = Pin((1, 77))
PC14 = Pin((1, 78))
PC15 = Pin((1, 79))
PF0 = Pin((1, 160))
PF1 = Pin((1, 161))
PF2 = Pin((1, 162))
PF3 = Pin((1, 163))
PF4 = Pin((1, 164))
PF5 = Pin((1, 165))
PF6 = Pin((1, 166))
PG0 = Pin((1, 192))
PG1 = Pin((1, 193))
PG2 = Pin((1, 194))
PG3 = Pin((1, 195))
PG4 = Pin((1, 196))
PG5 = Pin((1, 197))
PG6 = Pin((1, 198))
PG7 = Pin((1, 199))
PG8 = Pin((1, 200))
PG9 = Pin((1, 201))
PG10 = Pin((1, 202))
PG11 = Pin((1, 203))
PG12 = Pin((1, 204))
PG13 = Pin((1, 205))
PG14 = Pin((1, 206))
PG15 = Pin((1, 207))
PG16 = Pin((1, 208))
PG17 = Pin((1, 209))
PG18 = Pin((1, 210))
PG19 = Pin((1, 211))
PH0 = Pin((1, 224))
PH1 = Pin((1, 225))
PH2 = Pin((1, 226))
UART5_TX = PH2
PH3 = Pin((1, 227))
UART5_RX = PH3
PH4 = Pin((1, 228))
TWI3_SCL = PH4
PH5 = Pin((1, 229))
UART2_TX = PH5
TWI3_SDA = PH5
SPI1_CS0 = PH5
PH6 = Pin((1, 230))
UART2_RX = PH6
SPI1_SCLK = PH6
PH7 = Pin((1, 231))
SPI1_MOSI = PH7
PH8 = Pin((1, 232))
SPI1_MISO = PH8
PH9 = Pin((1, 233))
SPI1_CS1 = PH9
PH10 = Pin((1, 234))
PI0 = Pin((1, 256))
PI1 = Pin((1, 257))
PI2 = Pin((1, 258))
PI3 = Pin((1, 259))
PI4 = Pin((1, 260))
PI5 = Pin((1, 261))
PI6 = Pin((1, 262))
PI7 = Pin((1, 263))
PI8 = Pin((1, 264))
PI9 = Pin((1, 265))
PI10 = Pin((1, 266))
PI11 = Pin((1, 267))
PI12 = Pin((1, 268))
PI13 = Pin((1, 269))
PI14 = Pin((1, 270))
PI15 = Pin((1, 271))
PI16 = Pin((1, 272))
i2cPorts = ((3, TWI3_SCL, TWI3_SDA),)
# ordered as spiId, sckId, mosiId, misoId
spiPorts = (
(0, SPI0_SCLK, SPI0_MOSI, SPI0_MISO),
(1, SPI1_SCLK, SPI1_MOSI, SPI1_MISO),
)
# ordered as uartId, txId, rxId
uartPorts = (
(2, UART2_TX, UART2_RX),
(5, UART5_TX, UART5_RX),
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/allwinner/h616/pin.py | pin.py |
"""Chip Definition for MCP2221"""
import os
import time
import atexit
import hid
# Here if you need it
MCP2221_HID_DELAY = float(os.environ.get("BLINKA_MCP2221_HID_DELAY", 0))
# Use to set delay between reset and device reopen. if negative, don't reset at all
MCP2221_RESET_DELAY = float(os.environ.get("BLINKA_MCP2221_RESET_DELAY", 0.5))
# from the C driver
# http://ww1.microchip.com/downloads/en/DeviceDoc/mcp2221_0_1.tar.gz
# others (???) determined during driver developement
RESP_ERR_NOERR = 0x00
RESP_ADDR_NACK = 0x25
RESP_READ_ERR = 0x7F
RESP_READ_COMPL = 0x55
RESP_READ_PARTIAL = 0x54 # ???
RESP_I2C_IDLE = 0x00
RESP_I2C_START_TOUT = 0x12
RESP_I2C_RSTART_TOUT = 0x17
RESP_I2C_WRADDRL_TOUT = 0x23
RESP_I2C_WRADDRL_WSEND = 0x21
RESP_I2C_WRADDRL_NACK = 0x25
RESP_I2C_WRDATA_TOUT = 0x44
RESP_I2C_RDDATA_TOUT = 0x52
RESP_I2C_STOP_TOUT = 0x62
RESP_I2C_MOREDATA = 0x43 # ???
RESP_I2C_PARTIALDATA = 0x41 # ???
RESP_I2C_WRITINGNOSTOP = 0x45 # ???
MCP2221_RETRY_MAX = 50
MCP2221_MAX_I2C_DATA_LEN = 60
MASK_ADDR_NACK = 0x40
class MCP2221:
"""MCP2221 Device Class Definition"""
VID = 0x04D8
PID = 0x00DD
GP_GPIO = 0b000
GP_DEDICATED = 0b001
GP_ALT0 = 0b010
GP_ALT1 = 0b011
GP_ALT2 = 0b100
def __init__(self):
self._hid = hid.device()
self._hid.open(MCP2221.VID, MCP2221.PID)
# make sure the device gets closed before exit
atexit.register(self.close)
if MCP2221_RESET_DELAY >= 0:
self._reset()
self._gp_config = [0x07] * 4 # "don't care" initial value
for pin in range(4):
self.gp_set_mode(pin, self.GP_GPIO) # set to GPIO mode
self.gpio_set_direction(pin, 1) # set to INPUT
def close(self):
"""Close the hid device. Does nothing if the device is not open."""
self._hid.close()
def __del__(self):
# try to close the device before destroying the instance
self.close()
def _hid_xfer(self, report, response=True):
"""Perform HID Transfer"""
# first byte is report ID, which =0 for MCP2221
# remaing bytes = 64 byte report data
# https://github.com/libusb/hidapi/blob/083223e77952e1ef57e6b77796536a3359c1b2a3/hidapi/hidapi.h#L185
self._hid.write(b"\0" + report + b"\0" * (64 - len(report)))
time.sleep(MCP2221_HID_DELAY)
if response:
# return is 64 byte response report
return self._hid.read(64)
return None
# ----------------------------------------------------------------
# MISC
# ----------------------------------------------------------------
def gp_get_mode(self, pin):
"""Get Current Pin Mode"""
return self._hid_xfer(b"\x61")[22 + pin] & 0x07
def gp_set_mode(self, pin, mode):
"""Set Current Pin Mode"""
# already set to that mode?
mode &= 0x07
if mode == (self._gp_config[pin] & 0x07):
return
# update GP mode for pin
self._gp_config[pin] = mode
# empty report, this is safe since 0's = no change
report = bytearray(b"\x60" + b"\x00" * 63)
# set the alter GP flag byte
report[7] = 0xFF
# add GP setttings
report[8] = self._gp_config[0]
report[9] = self._gp_config[1]
report[10] = self._gp_config[2]
report[11] = self._gp_config[3]
# and make it so
self._hid_xfer(report)
def _pretty_report(self, register):
report = self._hid_xfer(register)
print(" 0 1 2 3 4 5 6 7 8 9")
index = 0
for row in range(7):
print("{} : ".format(row), end="")
for _ in range(10):
print("{:02x} ".format(report[index]), end="")
index += 1
if index > 63:
break
print()
def _status_dump(self):
self._pretty_report(b"\x10")
def _sram_dump(self):
self._pretty_report(b"\x61")
def _reset(self):
self._hid_xfer(b"\x70\xAB\xCD\xEF", response=False)
self._hid.close()
time.sleep(MCP2221_RESET_DELAY)
start = time.monotonic()
while time.monotonic() - start < 5:
try:
self._hid.open(MCP2221.VID, MCP2221.PID)
except OSError:
# try again
time.sleep(0.1)
continue
return
raise OSError("open failed")
# ----------------------------------------------------------------
# GPIO
# ----------------------------------------------------------------
def gpio_set_direction(self, pin, mode):
"""Set Current GPIO Pin Direction"""
if mode:
# set bit 3 for INPUT
self._gp_config[pin] |= 1 << 3
else:
# clear bit 3 for OUTPUT
self._gp_config[pin] &= ~(1 << 3)
report = bytearray(b"\x50" + b"\x00" * 63) # empty set GPIO report
offset = 4 * (pin + 1)
report[offset] = 0x01 # set pin direction
report[offset + 1] = mode # to this
self._hid_xfer(report)
def gpio_set_pin(self, pin, value):
"""Set Current GPIO Pin Value"""
if value:
# set bit 4
self._gp_config[pin] |= 1 << 4
else:
# clear bit 4
self._gp_config[pin] &= ~(1 << 4)
report = bytearray(b"\x50" + b"\x00" * 63) # empty set GPIO report
offset = 2 + 4 * pin
report[offset] = 0x01 # set pin value
report[offset + 1] = value # to this
self._hid_xfer(report)
def gpio_get_pin(self, pin):
"""Get Current GPIO Pin Value"""
resp = self._hid_xfer(b"\x51")
offset = 2 + 2 * pin
if resp[offset] == 0xEE:
raise RuntimeError("Pin is not set for GPIO operation.")
return resp[offset]
# ----------------------------------------------------------------
# I2C
# ----------------------------------------------------------------
def _i2c_status(self):
resp = self._hid_xfer(b"\x10")
if resp[1] != 0:
raise RuntimeError("Couldn't get I2C status")
return resp
def _i2c_state(self):
return self._i2c_status()[8]
def _i2c_cancel(self):
resp = self._hid_xfer(b"\x10\x00\x10")
if resp[1] != 0x00:
raise RuntimeError("Couldn't cancel I2C")
if resp[2] == 0x10:
# bus release will need "a few hundred microseconds"
time.sleep(0.001)
# pylint: disable=too-many-arguments,too-many-branches
def _i2c_write(self, cmd, address, buffer, start=0, end=None):
if self._i2c_state() != 0x00:
self._i2c_cancel()
end = end if end else len(buffer)
length = end - start
retries = 0
while (end - start) > 0 or not buffer:
chunk = min(end - start, MCP2221_MAX_I2C_DATA_LEN)
# write out current chunk
resp = self._hid_xfer(
bytes([cmd, length & 0xFF, (length >> 8) & 0xFF, address << 1])
+ buffer[start : (start + chunk)]
)
# check for success
if resp[1] != 0x00:
if resp[2] in (
RESP_I2C_START_TOUT,
RESP_I2C_WRADDRL_TOUT,
RESP_I2C_WRADDRL_NACK,
RESP_I2C_WRDATA_TOUT,
RESP_I2C_STOP_TOUT,
):
raise RuntimeError("Unrecoverable I2C state failure")
retries += 1
if retries >= MCP2221_RETRY_MAX:
raise RuntimeError("I2C write error, max retries reached.")
time.sleep(0.001)
continue # try again
# yay chunk sent!
while self._i2c_state() == RESP_I2C_PARTIALDATA:
time.sleep(0.001)
if not buffer:
break
start += chunk
retries = 0
# check status in another loop
for _ in range(MCP2221_RETRY_MAX):
status = self._i2c_status()
if status[20] & MASK_ADDR_NACK:
raise RuntimeError("I2C slave address was NACK'd")
usb_cmd_status = status[8]
if usb_cmd_status == 0:
break
if usb_cmd_status == RESP_I2C_WRITINGNOSTOP and cmd == 0x94:
break # this is OK too!
if usb_cmd_status in (
RESP_I2C_START_TOUT,
RESP_I2C_WRADDRL_TOUT,
RESP_I2C_WRADDRL_NACK,
RESP_I2C_WRDATA_TOUT,
RESP_I2C_STOP_TOUT,
):
raise RuntimeError("Unrecoverable I2C state failure")
time.sleep(0.001)
else:
raise RuntimeError("I2C write error: max retries reached.")
# whew success!
def _i2c_read(self, cmd, address, buffer, start=0, end=None):
if self._i2c_state() not in (RESP_I2C_WRITINGNOSTOP, 0):
self._i2c_cancel()
end = end if end else len(buffer)
length = end - start
# tell it we want to read
resp = self._hid_xfer(
bytes([cmd, length & 0xFF, (length >> 8) & 0xFF, (address << 1) | 0x01])
)
# check for success
if resp[1] != 0x00:
raise RuntimeError("Unrecoverable I2C read failure")
# and now the read part
while (end - start) > 0:
for _ in range(MCP2221_RETRY_MAX):
# the actual read
resp = self._hid_xfer(b"\x40")
# check for success
if resp[1] == RESP_I2C_PARTIALDATA:
time.sleep(0.001)
continue
if resp[1] != 0x00:
raise RuntimeError("Unrecoverable I2C read failure")
if resp[2] == RESP_ADDR_NACK:
raise RuntimeError("I2C NACK")
if resp[3] == 0x00 and resp[2] == 0x00:
break
if resp[3] == RESP_READ_ERR:
time.sleep(0.001)
continue
if resp[2] in (RESP_READ_COMPL, RESP_READ_PARTIAL):
break
else:
raise RuntimeError("I2C read error: max retries reached.")
# move data into buffer
chunk = min(end - start, 60)
for i, k in enumerate(range(start, start + chunk)):
buffer[k] = resp[4 + i]
start += chunk
# pylint: enable=too-many-arguments
def _i2c_configure(self, baudrate=100000):
"""Configure I2C"""
self._hid_xfer(
bytes(
[
0x10, # set parameters
0x00, # don't care
0x00, # no effect
0x20, # next byte is clock divider
12000000 // baudrate - 3,
]
)
)
def i2c_writeto(self, address, buffer, *, start=0, end=None):
"""Write data from the buffer to an address"""
self._i2c_write(0x90, address, buffer, start, end)
def i2c_readfrom_into(self, address, buffer, *, start=0, end=None):
"""Read data from an address and into the buffer"""
self._i2c_read(0x91, address, buffer, start, end)
def i2c_writeto_then_readfrom(
self,
address,
out_buffer,
in_buffer,
*,
out_start=0,
out_end=None,
in_start=0,
in_end=None,
):
"""Write data from buffer_out to an address and then
read data from an address and into buffer_in
"""
self._i2c_write(0x94, address, out_buffer, out_start, out_end)
self._i2c_read(0x93, address, in_buffer, in_start, in_end)
def i2c_scan(self, *, start=0, end=0x79):
"""Perform an I2C Device Scan"""
found = []
for addr in range(start, end + 1):
# try a write
try:
self.i2c_writeto(addr, b"\x00")
except RuntimeError: # no reply!
continue
# store if success
found.append(addr)
return found
# ----------------------------------------------------------------
# ADC
# ----------------------------------------------------------------
def adc_configure(self, vref=0):
"""Configure the Analog-to-Digital Converter"""
report = bytearray(b"\x60" + b"\x00" * 63)
report[5] = 1 << 7 | (vref & 0b111)
self._hid_xfer(report)
def adc_read(self, pin):
"""Read from the Analog-to-Digital Converter"""
resp = self._hid_xfer(b"\x10")
return resp[49 + 2 * pin] << 8 | resp[48 + 2 * pin]
# ----------------------------------------------------------------
# DAC
# ----------------------------------------------------------------
def dac_configure(self, vref=0):
"""Configure the Digital-to-Analog Converter"""
report = bytearray(b"\x60" + b"\x00" * 63)
report[3] = 1 << 7 | (vref & 0b111)
self._hid_xfer(report)
# pylint: disable=unused-argument
def dac_write(self, pin, value):
"""Write to the Digital-to-Analog Converter"""
report = bytearray(b"\x60" + b"\x00" * 63)
report[4] = 1 << 7 | (value & 0b11111)
self._hid_xfer(report)
# pylint: enable=unused-argument
mcp2221 = MCP2221() | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/mcp2221/mcp2221.py | mcp2221.py |
"""MCP2221 pin names"""
from .mcp2221 import mcp2221
class Pin:
"""A basic Pin class for use with MCP2221."""
# pin modes
OUT = 0
IN = 1
ADC = 2
DAC = 3
# pin values
LOW = 0
HIGH = 1
def __init__(self, pin_id=None):
self.id = pin_id
self._mode = None
def init(self, mode=IN, pull=None):
"""Initialize the Pin"""
if self.id is None:
raise RuntimeError("Can not init a None type pin.")
if pull is not None:
raise NotImplementedError("Internal pullups and pulldowns not supported")
if mode in (Pin.IN, Pin.OUT):
# All pins can do GPIO
mcp2221.gp_set_mode(self.id, mcp2221.GP_GPIO)
mcp2221.gpio_set_direction(self.id, mode)
elif mode == Pin.ADC:
# ADC only available on these pins
if self.id not in (1, 2, 3):
raise ValueError("Pin does not have ADC capabilities")
mcp2221.gp_set_mode(self.id, mcp2221.GP_ALT0)
mcp2221.adc_configure()
elif mode == Pin.DAC:
# DAC only available on these pins
if self.id not in (2, 3):
raise ValueError("Pin does not have DAC capabilities")
mcp2221.gp_set_mode(self.id, mcp2221.GP_ALT1)
mcp2221.dac_configure()
else:
raise ValueError("Incorrect pin mode: {}".format(mode))
self._mode = mode
def value(self, val=None):
"""Set or return the Pin Value"""
# Digital In / Out
if self._mode in (Pin.IN, Pin.OUT):
# digital read
if val is None:
return mcp2221.gpio_get_pin(self.id)
# digital write
if val in (Pin.LOW, Pin.HIGH):
mcp2221.gpio_set_pin(self.id, val)
return None
# nope
raise ValueError("Invalid value for pin.")
# Analog In
if self._mode == Pin.ADC:
if val is None:
# MCP2221 ADC is 10 bit, scale to 16 bit per CP API
return mcp2221.adc_read(self.id) * 64
# read only
raise AttributeError("'AnalogIn' object has no attribute 'value'")
# Analog Out
if self._mode == Pin.DAC:
if val is None:
# write only
raise AttributeError("unreadable attribute")
# scale 16 bit value to MCP2221 5 bit DAC (yes 5 bit)
mcp2221.dac_write(self.id, val // 2048)
return None
raise RuntimeError(
"No action for mode {} with value {}".format(self._mode, val)
)
# create pin instances for each pin
G0 = Pin(0)
G1 = Pin(1)
G2 = Pin(2)
G3 = Pin(3)
SCL = Pin()
SDA = Pin() | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/mcp2221/pin.py | pin.py |
"""DRA74x pin names"""
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
# BeagleBone AI
# P8_1 = DGND # DGND
# P8_2 = DGND # DGND
P8_3 = Pin((0, 24)) # GPIO1_24 - GPIO_24
P8_4 = Pin((0, 25)) # GPIO1_25 - GPIO_25
P8_5 = Pin((6, 1)) # GPIO7_1 - GPIO_193
P8_6 = Pin((6, 2)) # GPIO7_2 - GPIO_194
P8_7 = Pin((5, 5)) # TIMER4 - GPIO_165
P8_8 = Pin((5, 6)) # TIMER7 - GPIO_166
P8_9 = Pin((5, 18)) # TIMER5 - GPIO_178
P8_10 = Pin((5, 4)) # TIMER6 - GPIO_164
P8_11 = Pin((2, 11)) # GPIO3_11 - GPIO_75
P8_12 = Pin((2, 10)) # GPIO3_10 - GPIO_74
P8_13 = Pin((3, 11)) # EHRPWM2B - GPIO_107
P8_14 = Pin((3, 13)) # GPIO4_13 - GPIO_109
P8_15 = Pin((3, 3)) # GPIO4_3 - GPIO_99
P8_16 = Pin((3, 29)) # GPIO4_29 - GPIO_125
P8_17 = Pin((7, 18)) # GPIO8_18 - GPIO_242
P8_18 = Pin((3, 9)) # GPIO4_9 - GPIO_105
P8_19 = Pin((3, 10)) # EHRPWM2A - GPIO_106
P8_20 = Pin((5, 30)) # GPIO6_30 - GPIO_190
P8_21 = Pin((5, 29)) # GPIO6_29 - GPIO_189
P8_22 = Pin((0, 23)) # GPIO1_23 - GPIO_23
P8_23 = Pin((0, 22)) # GPIO1_22 - GPIO_22
P8_24 = Pin((6, 0)) # GPIO7_0 - GPIO_192
P8_25 = Pin((5, 31)) # GPIO6_31 - GPIO_191
P8_26 = Pin((3, 28)) # GPIO4_28 - GPIO_124
P8_27 = Pin((3, 23)) # GPIO4_23 - GPIO_119
P8_28 = Pin((3, 19)) # GPIO4_19 - GPIO_115
P8_29 = Pin((3, 22)) # GPIO4_22 - GPIO_118
P8_30 = Pin((3, 20)) # GPIO4_20 - GPIO_116
P8_31 = Pin((7, 14)) # UART5_CTSN - GPIO_238
P8_32 = Pin((7, 15)) # UART5_RTSN - GPIO_239
P8_33 = Pin((7, 13)) # UART4_RTSN - GPIO_237
P8_34 = Pin((7, 11)) # UART3_RTSN - GPIO_235
P8_35 = Pin((7, 12)) # UART4_CTSN - GPIO_236
P8_36 = Pin((7, 10)) # UART3_CTSN - GPIO_234
P8_37 = Pin((7, 8)) # UART5_TXD - GPIO_232
P8_38 = Pin((7, 9)) # UART5_RXD - GPIO_233
P8_39 = Pin((7, 6)) # GPIO8_6 - GPIO_230
P8_40 = Pin((7, 7)) # GPIO8_7 - GPIO_231
P8_41 = Pin((7, 4)) # GPIO8_4 - GPIO_228
P8_42 = Pin((7, 5)) # GPIO8_5 - GPIO_229
P8_43 = Pin((7, 2)) # GPIO8_2 - GPIO_226
P8_44 = Pin((7, 3)) # GPIO8_3 - GPIO_227
P8_45 = Pin((7, 0)) # GPIO8_0 - GPIO_224
P8_46 = Pin((7, 1)) # GPIO8_1 - GPIO_225
# P9_1 = DGND # DGND - GPIO_0
# P9_2 = DGND # DGND - GPIO_0
# P9_3 = VDD_3V3 # VDD_3V3 - GPIO_0
# P9_4 = VDD_3V3 # VDD_3V3 - GPIO_0
# P9_5 = VDD_5V # VDD_5V - GPIO_0
# P9_6 = VDD_5V # VDD_5V - GPIO_0
# P9_7 = SYS_5V # SYS_5V - GPIO_0
# P9_8 = SYS_5V # SYS_5V - GPIO_0
# P9_9 = PWR_BUT # PWR_BUT - GPIO_0
# P9_10 = SYS_RESETN # SYS_RESETn - GPIO_0
P9_11 = Pin((7, 17)) # UART4_RXD - GPIO_241
P9_12 = Pin((4, 0)) # GPIO5_0 - GPIO_128
P9_13 = Pin((5, 12)) # UART4_TXD - GPIO_172
P9_14 = Pin((3, 25)) # EHRPWM1A - GPIO_121
P9_15 = Pin((2, 12)) # GPIO3_12 - GPIO_76
P9_16 = Pin((3, 26)) # EHRPWM1B - GPIO_122
P9_17 = Pin((6, 17)) # I2C1_SCL - GPIO_209
P9_18 = Pin((6, 16)) # I2C1_SDA - GPIO_208
P9_19 = Pin((6, 3)) # I2C2_SCL - GPIO_195
P9_20 = Pin((6, 4)) # I2C2_SDA - GPIO_196
P9_21 = Pin((2, 3)) # UART3_TXD - GPIO_67
P9_22 = Pin((5, 19)) # UART3_RXD - GPIO_179
P9_23 = Pin((6, 11)) # GPIO7_11 - GPIO_203
P9_24 = Pin((5, 15)) # UART1_TXD - GPIO_175
P9_25 = Pin((5, 17)) # GPIO6_17 - GPIO_177
P9_26 = Pin((5, 14)) # UART1_RXD - GPIO_174
P9_27 = Pin((3, 15)) # GPIO4_15 - GPIO_111
P9_28 = Pin((3, 17)) # SPI1_CS0 - GPIO_113
P9_29 = Pin((4, 11)) # SPI1_D0 - GPIO_139
P9_30 = Pin((4, 12)) # SPI1_D1 - GPIO_140
P9_31 = Pin((4, 10)) # SPI1_SCLK - GPIO_138
# P9_32 = VDD_ADC # VDD_ADC - GPIO_0
# P9_33 = AIN4 # AIN4 - GPIO_0
# P9_34 = GNDA_ADC # GNDA_ADC - GPIO_0
# P9_35 = AIN6 # AIN6 - GPIO_0
# P9_36 = AIN5 # AIN5 - GPIO_0
# P9_37 = AIN2 # AIN2 - GPIO_0
# P9_38 = AIN3 # AIN3 - GPIO_0
# P9_39 = AIN0 # AIN0 - GPIO_0
# P9_40 = AIN1 # AIN1 - GPIO_0
P9_41 = Pin((5, 20)) # CLKOUT2 - GPIO_180
P9_42 = Pin((3, 18)) # GPIO4_18 - GPIO_114
# P9_43 = DGND # DGND - GPIO_0
# P9_44 = DGND # DGND - GPIO_0
# P9_45 = DGND # DGND - GPIO_0
# P9_46 = DGND # DGND - GPIO_0
##########################################
# User LEDs
USR0 = Pin((2, 17)) # USR0 - GPIO3_17
USR1 = Pin((4, 5)) # USR1 - GPIO5_5
USR2 = Pin((2, 15)) # USR2 - GPIO3_15
USR3 = Pin((2, 14)) # USR3 - GPIO3_14
USR4 = Pin((2, 7)) # USR4 - GPIO3_7
# I2C4
I2C4_SCL = P9_19 # i2c4_scl
I2C4_SDA = P9_20 # i2c4_sda
# I2C5
I2C5_SCL = P9_17 # i2c5_scl
I2C5_SDA = P9_18 # i2c5_sda
# SPI0
SPI0_CS0 = P9_17
SPI0_D1 = P9_18
SPI0_D0 = P9_21
SPI0_SCLK = P9_22
# SPI1
SPI1_CS0 = P9_28
SPI1_CS1 = P9_42
SPI1_SCLK = P9_31
SPI1_D0 = P9_30
SPI1_D1 = P9_29
# UART0
UART0_TXD = P8_44
UART0_RXD = P8_36
UART0_RTSn = P8_34
UART0_CTSn = P8_45
# UART3
UART3_TXD = P9_21
UART3_RXD = P9_22
UART3_RTSn = P9_17
UART3_CTSn = P9_18
# UART5
UART5_TXD = P9_13
UART5_RXD = P9_11
UART5_RTSn = P8_6
UART5_CTSn = P8_5
# UART8
UART8_TXD = P8_37
UART8_RXD = P8_38
UART8_RTSn = P8_32
UART8_CTSn = P8_31
# UART10
UART10_TXD = P9_24
UART10_RXD = P9_26
UART10_RTSn = P8_4
UART10_CTSn = P8_3
# PWM
TIMER10 = P8_10
TIMER11 = P8_7
TIMER12 = P8_8
TIMER14 = P8_9
# ordered as i2cId, SCL, SDA
i2cPorts = (
(3, I2C4_SCL, I2C4_SDA), # default config
(4, I2C4_SCL, I2C4_SDA), # roboticscape config
(3, I2C5_SCL, I2C5_SDA), # roboticscape config
)
# ordered as spiId, sckId, mosiId, misoId
spiPorts = (
(0, SPI0_SCLK, SPI0_D0, SPI0_D1),
(1, SPI1_SCLK, SPI1_D1, SPI1_D0),
)
# ordered as uartId, txId, rxId
uartPorts = (
(0, UART0_TXD, UART0_RXD),
(3, UART3_TXD, UART3_RXD),
(5, UART5_TXD, UART5_RXD),
(8, UART8_TXD, UART8_RXD),
(10, UART10_TXD, UART10_RXD),
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/dra74x/pin.py | pin.py |
# pylint: disable=pointless-string-statement
# pylint: disable=ungrouped-imports,wrong-import-position,unused-import
# pylint: disable=import-outside-toplevel
"""Custom PWMOut Wrapper for am65xx"""
"""
Much code from https://github.com/vsergeev/python-periphery/blob/master/periphery/pwm.py
Copyright (c) 2015-2016 vsergeev / Ivan (Vanya) A. Sergeev
License: MIT
"""
import mraa
from adafruit_blinka.microcontroller.am65xx.pin import Pin
# pylint: disable=unnecessary-pass
class PWMError(IOError):
"""Base class for PWM errors."""
pass
# pylint: enable=unnecessary-pass
class PWMOut:
"""Pulse Width Modulation Output Class"""
def __init__(self, pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
self._frequency = None
self._duty_cycle = None
self._pwmpin = None
self._period = 0
self._enabled = False
self._varfreq = variable_frequency
# check pin for PWM support
self._pin = Pin(pin.id)
self._pin.init(mode=Pin.PWM)
# initialize pin
self._open(pin, duty_cycle, frequency, variable_frequency)
def __del__(self):
self.deinit()
def __enter__(self):
return self
def __exit__(self, t, value, traceback):
self.deinit()
def _open(self, pin, duty=0, freq=500, variable_frequency=False):
self._pwmpin = mraa.Pwm(pin.id)
self.frequency = freq
self.enabled = True
self._varfreq = variable_frequency
self.duty_cycle = duty
def deinit(self):
"""Deinit the PWM."""
if self._pwmpin is not None:
self._pwmpin.enable(False)
self._pwmpin = None
def _is_deinited(self):
if self._pwmpin is None:
raise ValueError(
"Object has been deinitialize and can no longer "
"be used. Create a new object."
)
@property
def period(self):
"""Get or set the PWM's output period in seconds.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
:type: int, float
"""
return 1.0 / self.frequency
@period.setter
def period(self, period):
if not isinstance(period, (int, float)):
raise TypeError("Invalid period type, should be int or float.")
self.frequency = 1.0 / period
@property
def duty_cycle(self):
"""Get or set the PWM's output duty cycle which is the fraction of
each pulse which is high. 16-bit
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
ValueError: if value is out of bounds of 0.0 to 1.0.
:type: int, float
"""
return int(self._duty_cycle * 65535)
@duty_cycle.setter
def duty_cycle(self, duty_cycle):
if not isinstance(duty_cycle, (int, float)):
raise TypeError("Invalid duty cycle type, should be int or float.")
if not 0 <= duty_cycle <= 65535:
raise ValueError("Invalid duty cycle value, should be between 0 and 65535")
# convert from 16-bit
duty_cycle /= 65535.0
self._duty_cycle = duty_cycle
# self._pwmpin.ChangeDutyCycle(round(self._duty_cycle * 100))
self._pwmpin.write(self._duty_cycle) # mraa duty_cycle 0.0f - 1.0f
@property
def frequency(self):
"""Get or set the PWM's output frequency in Hertz.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not int or float.
:type: int, float
"""
return self._frequency
@frequency.setter
def frequency(self, frequency):
if not isinstance(frequency, (int, float)):
raise TypeError("Invalid frequency type, should be int or float.")
if self._enabled and not self._varfreq:
raise TypeError(
" Set variable_frequency = True to allow changing frequency "
)
# mraa has different variants in seconds,milli(_ms),micro(_us)
self._pwmpin.period((1 / frequency))
self._frequency = frequency
@property
def enabled(self):
"""Get or set the PWM's output enabled state.
Raises:
PWMError: if an I/O or OS error occurs.
TypeError: if value type is not bool.
:type: bool
"""
return self._enabled
@enabled.setter
def enabled(self, value):
if not isinstance(value, bool):
raise TypeError("Invalid enabled type, should be string.")
if value:
self._pwmpin.enable(True)
self._enabled = value
else:
self._pwmpin.enable(False)
self._enabled(False)
# String representation
def __str__(self):
return "pin %s (freq=%f Hz, duty_cycle=%f%%)" % (
self._pin,
self.frequency,
self.duty_cycle,
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/am65xx/pwmout.py | pwmout.py |
"""TI AM65XX pin names"""
import mraa
# pylint: disable=too-many-branches,too-many-statements
# pylint: disable=pointless-string-statement
class Pin:
"""Pins don't exist in CPython so...lets make our own!"""
# pin modes
IN = 0
OUT = 1
ADC = 2
DAC = 3
PWM = 4
# pin values
LOW = 0
HIGH = 1
# pin pulls
PULL_NONE = 0
PULL_UP = 1
PULL_DOWN = 2
id = None
_value = LOW
_mode = IN
def __init__(self, pin_id=None):
self.id = pin_id
self._mode = None
self._pull = None
self._pin = None
def __repr__(self):
return str(self.id)
def __eq__(self, other):
return self.id == other
def init(self, mode=IN, pull=None):
"""Initialize the Pin"""
if self.id is None:
raise RuntimeError("Can not init a None type pin.")
if mode is not None:
if mode == self.IN:
self._mode = self.IN
mypin = mraa.Gpio(self.id)
mypin.dir(mraa.DIR_IN)
elif mode == self.OUT:
self._mode = self.OUT
mypin = mraa.Gpio(self.id)
mypin.dir(mraa.DIR_OUT)
elif mode in (self.ADC, self.DAC):
# ADC (DAC not available) only available on Pin 0-5 (X12 Pin 1-6)
if self.id not in (0, 1, 2, 3, 4, 5):
raise ValueError("Pin does not have ADC capabilities")
self._pin = mraa.Aio(self.id)
elif mode == self.PWM:
# PWM only available on Pin 4-9 (X10 Pin 1-2, X11 Pin 5-8)
if self.id not in (4, 5, 6, 7, 8, 9):
raise ValueError("Pin does not have PWM capabilities")
return
else:
raise RuntimeError("Invalid mode for pin: %s" % self.id)
self._mode = mode
if pull is not None:
if self._mode != self.IN:
raise RuntimeError("Cannot set pull resistor on output")
if pull == self.PULL_UP:
mypin = mraa.Gpio(self.id)
mypin.dir(mraa.DIR_IN)
elif pull == self.PULL_DOWN:
mypin = mraa.Gpio(self.id)
mypin.dir(mraa.DIR_IN)
else:
raise RuntimeError("Invalid pull for pin: %s" % self.id)
def value(self, val=None):
"""Set or return the Pin Value"""
# Digital In / Out
if self._mode in (Pin.IN, Pin.OUT):
if val is not None:
if val == self.LOW:
self._value = val
mypin = mraa.Gpio(self.id)
mypin.write(0)
elif val == self.HIGH:
self._value = val
mypin = mraa.Gpio(self.id)
mypin.write(1)
else:
raise RuntimeError("Invalid value for pin")
return None
return mraa.Gpio.read(mraa.Gpio(self.id))
# Analog In
if self._mode == Pin.ADC:
if val is None:
# Read ADC here
mypin = mraa.Aio(self.id)
mypin.read()
return mypin.read()
# read only
raise AttributeError("'AnalogIn' object has no attribute 'value'")
# Analog Out
if self._mode == Pin.DAC:
"""if val is None:
# write only
raise AttributeError("unreadable attribute")
# Set DAC here
mypin = mraa.Aio(self.id)
mypin.setBit(val)"""
raise AttributeError(
"AM65xx doesn't have an DAC! No Analog Output possible!"
)
raise RuntimeError(
"No action for mode {} with value {}".format(self._mode, val)
)
# Digital Pins (GPIO 0-19)
D0 = Pin(0)
D1 = Pin(1)
D2 = Pin(2)
D3 = Pin(3)
D4 = Pin(4)
D5 = Pin(5)
D6 = Pin(6)
D7 = Pin(7)
D8 = Pin(8)
D9 = Pin(9)
D10 = Pin(10)
D11 = Pin(11)
D12 = Pin(12)
D13 = Pin(13)
D14 = Pin(14)
D15 = Pin(15)
D16 = Pin(16)
D17 = Pin(17)
D18 = Pin(18)
D19 = Pin(19)
# Analog Pins (AIO 0-5, only ADC!)
A0 = Pin(0)
A1 = Pin(1)
A2 = Pin(2)
A3 = Pin(3)
A4 = Pin(4)
A5 = Pin(5)
# I2C allocation
I2C_SCL = "SCL"
I2C_SDA = "SDA"
# SPI allocation
SPIO_SCLK = D13
SPIO_MISO = D12
SPIO_MOSI = D11
SPIO_SS = D10
# UART allocation
UART_TX = "TX"
UART_RX = "RX"
# pwmOuts (GPIO 4-9)
PWM_4 = D4
PWM_5 = D5
PWM_6 = D6
PWM_7 = D7
PWM_8 = D8
PWM_9 = D9
# I2C
# ordered as sclID, sdaID
# i2c-4 (/dev/i2c-4) -> X10 Pin9, Pin10 (SDA, SCL)
i2cPorts = ((4, I2C_SCL, I2C_SDA),)
# SPI
# ordered as spiId, sckId, mosiID, misoID
spiPorts = ((0, SPIO_SCLK, SPIO_MOSI, SPIO_MISO),)
# UART
# use pySerial = dev/ttyS1
# ordered as uartID, txID, rxID
uartPorts = ((0, UART_TX, UART_RX),)
# PWM
pwmOuts = (
((0, 0), PWM_4),
((0, 1), PWM_5),
((2, 0), PWM_6),
((2, 1), PWM_7),
((4, 0), PWM_8),
((4, 1), PWM_9),
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/am65xx/pin.py | pin.py |
"""Generic Linux I2C class using PureIO's smbus class"""
from Adafruit_PureIO import smbus
class I2C:
"""I2C class"""
MASTER = 0
SLAVE = 1
_baudrate = None
_mode = None
_i2c_bus = None
# pylint: disable=unused-argument
def __init__(self, bus_num, mode=MASTER, baudrate=None):
if mode != self.MASTER:
raise NotImplementedError("Only I2C Master supported!")
_mode = self.MASTER
# if baudrate != None:
# print("I2C frequency is not settable in python, ignoring!")
try:
self._i2c_bus = smbus.SMBus(bus_num)
except FileNotFoundError:
raise RuntimeError(
"I2C Bus #%d not found, check if enabled in config!" % bus_num
) from RuntimeError
# pylint: enable=unused-argument
def scan(self):
"""Try to read a byte from each address, if you get an OSError
it means the device isnt there"""
found = []
for addr in range(0, 0x80):
try:
self._i2c_bus.read_byte(addr)
except OSError:
continue
found.append(addr)
return found
# pylint: disable=unused-argument
def writeto(self, address, buffer, *, start=0, end=None, stop=True):
"""Write data from the buffer to an address"""
if end is None:
end = len(buffer)
self._i2c_bus.write_bytes(address, buffer[start:end])
def readfrom_into(self, address, buffer, *, start=0, end=None, stop=True):
"""Read data from an address and into the buffer"""
if end is None:
end = len(buffer)
readin = self._i2c_bus.read_bytes(address, end - start)
for i in range(end - start):
buffer[i + start] = readin[i]
# pylint: enable=unused-argument
def writeto_then_readfrom(
self,
address,
buffer_out,
buffer_in,
*,
out_start=0,
out_end=None,
in_start=0,
in_end=None,
stop=False
):
"""Write data from buffer_out to an address and then
read data from an address and into buffer_in
"""
if out_end is None:
out_end = len(buffer_out)
if in_end is None:
in_end = len(buffer_in)
if stop:
# To generate a stop in linux, do in two transactions
self.writeto(address, buffer_out, start=out_start, end=out_end, stop=True)
self.readfrom_into(address, buffer_in, start=in_start, end=in_end)
else:
# To generate without a stop, do in one block transaction
readin = self._i2c_bus.read_i2c_block_data(
address, buffer_out[out_start:out_end], in_end - in_start
)
for i in range(in_end - in_start):
buffer_in[i + in_start] = readin[i] | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/am65xx/i2c.py | i2c.py |
"""am65xx SPI class using PureIO's SPI class"""
from Adafruit_PureIO import spi
# import Adafruit_PureIO.spi as spi
from adafruit_blinka.agnostic import detector
class SPI:
"""SPI Class"""
MSB = 0
LSB = 1
CPHA = 1
CPOL = 2
baudrate = 100000
mode = 0
bits = 8
def __init__(self, portid):
if isinstance(portid, tuple):
self._spi = spi.SPI(device=portid)
else:
self._spi = spi.SPI(device=(portid, 0))
self.clock_pin = None
self.mosi_pin = None
self.miso_pin = None
self.chip = None
# pylint: disable=too-many-arguments,unused-argument
def init(
self,
baudrate=100000,
polarity=0,
phase=0,
bits=8,
firstbit=MSB,
sck=None,
mosi=None,
miso=None,
):
"""Initialize SPI"""
mode = 0
if polarity:
mode |= self.CPOL
if phase:
mode |= self.CPHA
self.baudrate = baudrate
self.mode = mode
self.bits = bits
self.chip = detector.chip
# Pins are not used
self.clock_pin = sck
self.mosi_pin = mosi
self.miso_pin = miso
# pylint: enable=too-many-arguments,unused-argument
# pylint: disable=unnecessary-pass
def set_no_cs(self):
"""Setting so that SPI doesn't automatically set the CS pin"""
# No kernel seems to support this, so we're just going to pass
pass
# pylint: enable=unnecessary-pass
@property
def frequency(self):
"""Return the current baudrate"""
return self.baudrate
def write(self, buf, start=0, end=None):
"""Write data from the buffer to SPI"""
if not buf:
return
if end is None:
end = len(buf)
try:
# self._spi.open(self._port, 0)
self.set_no_cs()
self._spi.max_speed_hz = self.baudrate
self._spi.mode = self.mode
self._spi.bits_per_word = self.bits
self._spi.writebytes(buf[start:end])
# self._spi.close()
except FileNotFoundError:
print("Could not open SPI device - check if SPI is enabled in kernel!")
raise
def readinto(self, buf, start=0, end=None, write_value=0):
"""Read data from SPI and into the buffer"""
if not buf:
return
if end is None:
end = len(buf)
try:
# self._spi.open(self._port, 0)
# self.set_no_cs()
self._spi.max_speed_hz = self.baudrate
self._spi.mode = self.mode
self._spi.bits_per_word = self.bits
data = self._spi.transfer([write_value] * (end - start))
for i in range(end - start): # 'readinto' the given buffer
buf[start + i] = data[i]
# self._spi.close()
except FileNotFoundError:
print("Could not open SPI device - check if SPI is enabled in kernel!")
raise
# pylint: disable=too-many-arguments
def write_readinto(
self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
):
"""Perform a half-duplex write from buffer_out and then
read data into buffer_in
"""
if not buffer_out or not buffer_in:
return
if out_end is None:
out_end = len(buffer_out)
if in_end is None:
in_end = len(buffer_in)
if out_end - out_start != in_end - in_start:
raise RuntimeError("Buffer slices must be of equal length.")
try:
# self._spi.open(self._port, 0)
# self.set_no_cs()
self._spi.max_speed_hz = self.baudrate
self._spi.mode = self.mode
self._spi.bits_per_word = self.bits
data = self._spi.transfer(list(buffer_out[out_start : out_end + 1]))
for i in range((in_end - in_start)):
buffer_in[i + in_start] = data[i]
# self._spi.close()
except FileNotFoundError:
print("Could not open SPI device - check if SPI is enabled in kernel!")
raise
# pylint: enable=too-many-arguments | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/am65xx/spi.py | spi.py |
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
GPIOA0_0 = GPIO171 = Pin((26, 0))
GPIOA0_1 = GPIO172 = Pin((26, 1))
GPIOA0_2 = GPIO173 = Pin((26, 2))
GPIOA0_3 = GPIO174 = Pin((26, 3))
GPIOA0_4 = GPIO175 = Pin((26, 4))
GPIOA0_5 = GPIO176 = Pin((26, 5))
GPIOA0_6 = GPIO177 = Pin((26, 6))
GPIOA0_6 = GPIO178 = Pin((26, 7))
GPIOA2_0 = GPIO185 = Pin((28, 0))
GPIOA2_1 = GPIO186 = Pin((28, 1))
GPIOA2_2 = GPIO187 = Pin((28, 2))
GPIOA2_3 = GPIO188 = Pin((28, 3))
GPIOA2_4 = GPIO189 = Pin((28, 4))
GPIOA2_5 = GPIO190 = Pin((28, 5))
GPIOA2_6 = GPIO191 = Pin((28, 6))
GPIOA2_7 = GPIO192 = Pin((28, 7))
GPIOB3_0 = GPIO207 = Pin((32, 0))
GPIOB3_1 = GPIO208 = Pin((32, 1))
GPIOB3_2 = GPIO209 = Pin((32, 2))
GPIOB3_3 = GPIO210 = Pin((32, 3))
GPIOB3_4 = GPIO211 = Pin((32, 4))
GPIOB3_5 = GPIO212 = Pin((32, 5))
GPIOB3_6 = GPIO213 = Pin((32, 6))
GPIOB3_7 = GPIO214 = Pin((32, 7))
GPIOX1_0 = GPIO16 = Pin((2, 0))
GPIOX1_1 = GPIO17 = Pin((2, 1))
GPIOX1_2 = GPIO18 = Pin((2, 2))
GPIOX1_3 = GPIO19 = Pin((2, 3))
GPIOX1_4 = GPIO20 = Pin((2, 4))
GPIOX1_5 = GPIO21 = Pin((2, 5))
GPIOX1_6 = GPIO22 = Pin((2, 6))
GPIOX1_7 = GPIO23 = Pin((2, 7))
GPIOX2_0 = GPIO24 = Pin((3, 0))
GPIOX2_1 = GPIO25 = Pin((3, 1))
GPIOX2_2 = GPIO26 = Pin((3, 2))
GPIOX2_3 = GPIO27 = Pin((3, 3))
GPIOX2_4 = GPIO28 = Pin((3, 4))
GPIOX2_5 = GPIO29 = Pin((3, 5))
GPIOX2_6 = GPIO30 = Pin((3, 6))
GPIOX2_7 = GPIO31 = Pin((3, 7))
GPIOX3_0 = GPIO32 = Pin((4, 0))
GPIOX3_1 = GPIO33 = Pin((4, 1))
GPIOX3_2 = GPIO34 = Pin((4, 2))
GPIOX3_3 = GPIO35 = Pin((4, 3))
GPIOX3_4 = GPIO36 = Pin((4, 4))
GPIOX3_5 = GPIO37 = Pin((4, 5))
GPIOX3_6 = GPIO38 = Pin((4, 6))
GPIOX3_7 = GPIO39 = Pin((4, 7))
I2C1_SDA = GPIOB3_2
I2C1_SCL = GPIOB3_3
I2C5_SDA = GPIOA2_2
I2C5_SCL = GPIOA2_3
UART0_TX = GPIOA0_1
UART0_RX = GPIOA0_0
SPI1_SCLK = GPIOA2_4
SPI1_MISO = GPIOA2_6
SPI1_MOSI = GPIOA2_7
SPI1_CS0 = GPIOA2_5
# ordered as i2cId, sclId, sdaId
i2cPorts = (
(1, I2C1_SCL, I2C1_SDA),
(5, I2C5_SCL, I2C5_SDA),
)
# ordered as spiId, sckId, mosiId, misoId
spiPorts = ((1, SPI1_SCLK, SPI1_MOSI, SPI1_MISO),)
# ordered as uartId, txId, rxId
uartPorts = ((0, UART0_TX, UART0_RX),) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/samsung/exynos5422/pin.py | pin.py |
"""NXP IMX6ULL pin names"""
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
# GPIO num = reconment function = Pin((chip, line))
GPIO31 = I2C2_SDA = Pin((0, 31)) # GPIO1_IO31
GPIO30 = I2C2_SCL = Pin((0, 30)) # GPIO1_IO30
GPIO29 = I2C3_SDA = Pin((0, 29)) # GPIO1_IO29
GPIO28 = I2C3_SCL = Pin((0, 28)) # GPIO1_IO28
GPIO24 = UART3_TXD = Pin((0, 24)) # GPIO1_IO24
GPIO25 = UART3_RXD = Pin((0, 25)) # GPIO1_IO25
GPIO22 = ECSPI3_MOSI = Pin((0, 22)) # GPIO1_IO22
GPIO23 = ECSPI3_MISO = Pin((0, 23)) # GPIO1_IO23
GPIO21 = ECSPI3_SCLK = Pin((0, 21)) # GPIO1_IO21
GPIO20 = ECSPI3_SS0 = Pin((0, 20)) # GPIO1_IO20
GPIO18 = ECSPI3_SS1 = Pin((0, 18)) # GPIO1_IO18
GPIO0 = ADC_IN0 = Pin((0, 0)) # GPIO1_IO0
GPIO1 = ADC_IN1 = Pin((0, 1)) # GPIO1_IO2
GPIO2 = ADC_IN2 = Pin((0, 2)) # GPIO1_IO2
GPIO3 = ADC_IN3 = Pin((0, 3)) # GPIO1_IO3
GPIO4 = PWM_C3 = Pin((0, 4)) # GPIO1_IO4
GPIO26 = Pin((0, 26)) # GPIO1_IO26
GPIO27 = Pin((0, 27)) # GPIO1_IO27
GPIO113 = Pin((3, 17)) # GPIO4_IO17
GPIO114 = Pin((3, 18)) # GPIO4_IO18
GPIO115 = PWM_C7 = Pin((3, 19)) # GPIO4_IO19
GPIO116 = PWM_C8 = Pin((3, 20)) # GPIO4_IO20
GPIO117 = Pin((3, 21)) # GPIO4_IO21
GPIO118 = Pin((3, 22)) # GPIO4_IO22
GPIO119 = Pin((3, 23)) # GPIO4_IO23
GPIO120 = Pin((3, 24)) # GPIO4_IO24
GPIO121 = Pin((3, 25)) # GPIO4_IO25
GPIO112 = Pin((3, 26)) # GPIO4_IO26
GPIO123 = Pin((3, 27)) # GPIO4_IO27
GPIO124 = Pin((3, 28)) # GPIO4_IO28
GPIO129 = Pin((4, 1)) # GPIO5_IO1
i2cPorts = (
(1, I2C2_SCL, I2C2_SDA),
(2, I2C3_SCL, I2C3_SDA),
)
# ordered as spiId, sckId, mosiId, misoId
spiPorts = ((2, ECSPI3_SCLK, ECSPI3_MOSI, ECSPI3_MISO),)
# UART3_TXD/RXD on /dev/ttymxc2
uartPorts = ((2, UART3_TXD, UART3_RXD),)
# SysFS pwm outputs, pwm channel and pin in first tuple
pwmOuts = (
((2, 0), PWM_C3),
((6, 0), PWM_C7),
((7, 0), PWM_C8),
)
# SysFS analog inputs, Ordered as analog analogInId, device, and channel
analogIns = (
(ADC_IN0, 0, 0),
(ADC_IN1, 0, 1),
(ADC_IN2, 0, 2),
(ADC_IN3, 0, 3),
) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/nxp_imx6ull/pin.py | pin.py |
"""STM32MP157 pins"""
from adafruit_blinka.microcontroller.generic_linux.periphery_pin import Pin
PA0 = Pin((0, 0))
PA1 = Pin((0, 1))
PA2 = Pin((0, 2))
PA3 = Pin((0, 3))
PA4 = Pin((0, 4))
PA5 = Pin((0, 5))
PA6 = Pin((0, 6))
PA7 = Pin((0, 7))
PA8 = Pin((0, 8))
PA9 = Pin((0, 9))
PA11 = Pin((0, 11))
PA12 = Pin((0, 12))
PA13 = Pin((0, 13))
PA14 = Pin((0, 14))
PA15 = Pin((0, 15))
PB0 = Pin((1, 0))
PB1 = Pin((1, 1))
PB2 = Pin((1, 2))
PB3 = Pin((1, 3))
PB4 = Pin((1, 4))
PB5 = Pin((1, 5))
PB6 = Pin((1, 6))
PB7 = Pin((1, 7))
PB8 = Pin((1, 8))
PB9 = Pin((1, 9))
PB10 = Pin((1, 10))
PB11 = Pin((1, 11))
PB12 = Pin((1, 12))
PB13 = Pin((1, 13))
PB14 = Pin((1, 14))
PB15 = Pin((1, 15))
PC0 = Pin((2, 0))
PC1 = Pin((2, 1))
PC2 = Pin((2, 2))
PC3 = Pin((2, 3))
PC4 = Pin((2, 4))
PC5 = Pin((2, 5))
PC6 = Pin((2, 6))
PC7 = Pin((2, 7))
PC8 = Pin((2, 8))
PC9 = Pin((2, 9))
PC10 = Pin((2, 10))
PC11 = Pin((2, 11))
PC12 = Pin((2, 12))
PC13 = Pin((2, 13))
PD0 = Pin((3, 0))
PD1 = Pin((3, 1))
PD2 = Pin((3, 2))
PD3 = Pin((3, 3))
PD4 = Pin((3, 4))
PD5 = Pin((3, 5))
PD6 = Pin((3, 6))
PD7 = Pin((3, 7))
PD8 = Pin((3, 8))
PD9 = Pin((3, 9))
PD10 = Pin((3, 10))
PD11 = Pin((3, 11))
PD12 = Pin((3, 12))
PD13 = Pin((3, 13))
PD14 = Pin((3, 14))
PD15 = Pin((3, 15))
PE0 = Pin((4, 0))
PE1 = Pin((4, 1))
PE2 = Pin((4, 2))
PE3 = Pin((4, 3))
PE4 = Pin((4, 4))
PE5 = Pin((4, 5))
PE6 = Pin((4, 6))
PE7 = Pin((4, 7))
PE8 = Pin((4, 8))
PE9 = Pin((4, 9))
PE10 = Pin((4, 10))
PE11 = Pin((4, 11))
PE12 = Pin((4, 12))
PE13 = Pin((4, 13))
PE14 = Pin((4, 14))
PE15 = Pin((4, 15))
PF0 = Pin((5, 0))
PF1 = Pin((5, 1))
PF2 = Pin((5, 2))
PF3 = Pin((5, 3))
PF4 = Pin((5, 4))
PF5 = Pin((5, 5))
PF6 = Pin((5, 6))
PF7 = Pin((5, 7))
PF8 = Pin((5, 8))
PF9 = Pin((5, 9))
PF10 = Pin((5, 10))
PF11 = Pin((5, 11))
PF12 = Pin((5, 12))
PF13 = Pin((5, 13))
PF14 = Pin((5, 14))
PF15 = Pin((5, 15))
PG0 = Pin((6, 0))
PG1 = Pin((6, 1))
PG2 = Pin((6, 2))
PG3 = Pin((6, 3))
PG4 = Pin((6, 4))
PG5 = Pin((6, 5))
PG6 = Pin((6, 6))
PG7 = Pin((6, 7))
PG8 = Pin((6, 8))
PG9 = Pin((6, 9))
PG10 = Pin((6, 10))
PG11 = Pin((6, 11))
PG12 = Pin((6, 12))
PG13 = Pin((6, 13))
PG14 = Pin((6, 14))
PG15 = Pin((6, 15))
PH2 = Pin((7, 2))
PH3 = Pin((7, 3))
PH4 = Pin((7, 4))
PH5 = Pin((7, 5))
PH6 = Pin((7, 6))
PH7 = Pin((7, 7))
PH8 = Pin((7, 8))
PH9 = Pin((7, 9))
PH10 = Pin((7, 10))
PH11 = Pin((7, 11))
PH12 = Pin((7, 12))
PH13 = Pin((7, 13))
PH14 = Pin((7, 14))
PH15 = Pin((7, 15))
PI0 = Pin((8, 0))
PI1 = Pin((8, 1))
PI2 = Pin((8, 2))
PI3 = Pin((8, 3))
PI4 = Pin((8, 4))
PI5 = Pin((8, 5))
PI6 = Pin((8, 6))
PI7 = Pin((8, 7))
PI8 = Pin((8, 8))
PI9 = Pin((8, 9))
PI10 = Pin((8, 10))
PI11 = Pin((8, 11))
PZ0 = Pin((9, 0))
PZ1 = Pin((9, 1))
PZ2 = Pin((9, 2))
PZ3 = Pin((9, 3))
PZ4 = Pin((9, 4))
PZ5 = Pin((9, 5))
PZ6 = Pin((9, 6))
PZ7 = Pin((9, 7))
# ordered as uartId, txId, rxId
UART_PORTS = ((3, PB10, PB12),)
# ordered as i2cId, sclId, sdaId
I2C_PORTS = (
(1, PD12, PF15),
(5, PA11, PA12),
)
# support busio port check
# 0 - linux system -> i2c-0
# 1 - linux system -> i2c-1
i2cPorts = (
(0, PF14, PF15),
(1, PZ0, PZ1),
)
# SysFS analog inputs, Ordered as analog analogInId, device, and channel
# Because stm32mp157 analog io used special port name,it doesn't like gpiod named form
# so support analog io in this way
PAN0 = 0
PAN1 = 0
analogIns = ((PAN0, 0, 0),) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/stm32/stm32mp157/pin.py | pin.py |
from typing import Optional
import os
import re
try:
import gpiod
except ImportError:
raise ImportError(
"libgpiod Python bindings not found, please install and try again!"
) from ImportError
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
if hasattr(gpiod, "Chip"):
chip0 = gpiod.Chip("0")
chip1 = gpiod.Chip("1")
else:
chip0 = gpiod.chip("0")
chip1 = gpiod.chip("1")
if chip0.num_lines < 20:
aobus = 0
periphs = 1
periphs_offset = chip1.num_lines - 85
else:
aobus = 1
periphs = 0
periphs_offset = chip0.num_lines - 85
del chip0
del chip1
GPIOAO_0 = GPIO496 = Pin((aobus, 0))
GPIOAO_1 = GPIO497 = Pin((aobus, 1))
GPIOAO_2 = GPIO498 = Pin((aobus, 2))
GPIOAO_3 = GPIO499 = Pin((aobus, 3))
GPIOAO_4 = GPIO500 = Pin((aobus, 4))
GPIOAO_5 = GPIO501 = Pin((aobus, 5))
GPIOAO_6 = GPIO502 = Pin((aobus, 6))
GPIOAO_7 = GPIO503 = Pin((aobus, 7))
GPIOAO_8 = GPIO504 = Pin((aobus, 8))
GPIOAO_9 = GPIO505 = Pin((aobus, 9))
GPIOAO_10 = GPIO506 = Pin((aobus, 10))
GPIOAO_11 = GPIO507 = Pin((aobus, 11))
GPIOE_0 = GPIO508 = Pin((aobus, 12))
GPIOE_1 = GPIO509 = Pin((aobus, 13))
GPIOE_2 = GPIO510 = Pin((aobus, 14))
GPIO_TEST_N = GPIO511 = Pin((aobus, 15))
GPIOH_0 = GPIO427 = Pin((periphs, 16 + periphs_offset))
GPIOH_1 = GPIO428 = Pin((periphs, 17 + periphs_offset))
GPIOH_2 = GPIO429 = Pin((periphs, 18 + periphs_offset))
GPIOH_3 = GPIO430 = Pin((periphs, 19 + periphs_offset))
GPIOH_4 = GPIO431 = Pin((periphs, 20 + periphs_offset))
GPIOH_5 = GPIO432 = Pin((periphs, 21 + periphs_offset))
GPIOH_6 = GPIO433 = Pin((periphs, 22 + periphs_offset))
GPIOH_7 = GPIO434 = Pin((periphs, 23 + periphs_offset))
GPIOH_8 = GPIO435 = Pin((periphs, 24 + periphs_offset))
GPIOA_0 = GPIO460 = Pin((periphs, 49 + periphs_offset))
GPIOA_1 = GPIO461 = Pin((periphs, 50 + periphs_offset))
GPIOA_2 = GPIO462 = Pin((periphs, 51 + periphs_offset))
GPIOA_3 = GPIO463 = Pin((periphs, 52 + periphs_offset))
GPIOA_4 = GPIO464 = Pin((periphs, 53 + periphs_offset))
GPIOA_5 = GPIO465 = Pin((periphs, 54 + periphs_offset))
GPIOA_6 = GPIO466 = Pin((periphs, 55 + periphs_offset))
GPIOA_7 = GPIO467 = Pin((periphs, 56 + periphs_offset))
GPIOA_8 = GPIO468 = Pin((periphs, 57 + periphs_offset))
GPIOA_9 = GPIO469 = Pin((periphs, 58 + periphs_offset))
GPIOA_10 = GPIO470 = Pin((periphs, 59 + periphs_offset))
GPIOA_11 = GPIO471 = Pin((periphs, 60 + periphs_offset))
GPIOA_12 = GPIO472 = Pin((periphs, 61 + periphs_offset))
GPIOA_13 = GPIO473 = Pin((periphs, 62 + periphs_offset))
GPIOA_14 = GPIO474 = Pin((periphs, 63 + periphs_offset))
GPIOA_15 = GPIO475 = Pin((periphs, 64 + periphs_offset))
GPIOX_0 = GPIO476 = Pin((periphs, 65 + periphs_offset))
GPIOX_1 = GPIO477 = Pin((periphs, 66 + periphs_offset))
GPIOX_2 = GPIO478 = Pin((periphs, 67 + periphs_offset))
GPIOX_3 = GPIO479 = Pin((periphs, 68 + periphs_offset))
GPIOX_4 = GPIO480 = Pin((periphs, 69 + periphs_offset))
GPIOX_5 = GPIO481 = Pin((periphs, 70 + periphs_offset))
GPIOX_6 = GPIO482 = Pin((periphs, 71 + periphs_offset))
GPIOX_7 = GPIO483 = Pin((periphs, 72 + periphs_offset))
GPIOX_8 = GPIO484 = Pin((periphs, 73 + periphs_offset))
GPIOX_9 = GPIO485 = Pin((periphs, 74 + periphs_offset))
GPIOX_10 = GPIO486 = Pin((periphs, 75 + periphs_offset))
GPIOX_11 = GPIO487 = Pin((periphs, 76 + periphs_offset))
GPIOX_12 = GPIO488 = Pin((periphs, 77 + periphs_offset))
GPIOX_13 = GPIO489 = Pin((periphs, 78 + periphs_offset))
GPIOX_14 = GPIO490 = Pin((periphs, 79 + periphs_offset))
GPIOX_15 = GPIO491 = Pin((periphs, 80 + periphs_offset))
GPIOX_16 = GPIO492 = Pin((periphs, 81 + periphs_offset))
GPIOX_17 = GPIO493 = Pin((periphs, 82 + periphs_offset))
GPIOX_18 = GPIO494 = Pin((periphs, 83 + periphs_offset))
GPIOX_19 = GPIO495 = Pin((periphs, 84 + periphs_offset))
SPI0_SCLK = GPIOX_11
SPI0_MISO = GPIOX_9
SPI0_MOSI = GPIOX_8
SPI0_CS0 = GPIOX_10
# ordered as spiId, sckId, mosiId, misoId
spiPorts = ((0, SPI0_SCLK, SPI0_MOSI, SPI0_MISO),)
UART1_TX = GPIOX_12
UART1_RX = GPIOX_13
# ordered as uartId, txId, rxId
uartPorts = ((1, UART1_TX, UART1_RX),)
def get_dts_alias(device: str) -> Optional[str]:
"""Get the Device Tree Alias"""
uevent_path = "/sys/bus/platform/devices/" + device + "/uevent"
if os.path.exists(uevent_path):
with open(uevent_path, "r", encoding="utf-8") as fd:
pattern = r"^OF_ALIAS_0=(.*)$"
uevent = fd.read().split("\n")
for line in uevent:
match = re.search(pattern, line)
if match:
return match.group(1).upper()
return None
# ordered as i2cId, sclId, sdaId
i2cPorts = []
alias = get_dts_alias("ffd1d000.i2c")
if alias is not None:
globals()[alias + "_SCL"] = GPIOX_18
globals()[alias + "_SDA"] = GPIOX_17
i2cPorts.append((int(alias[3]), GPIOX_18, GPIOX_17))
alias = get_dts_alias("ffd1c000.i2c")
if alias is not None:
globals()[alias + "_SCL"] = GPIOA_15
globals()[alias + "_SDA"] = GPIOA_14
i2cPorts.append((int(alias[3]), GPIOA_15, GPIOA_14))
i2cPorts = tuple(i2cPorts) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/amlogic/meson_g12_common/pin.py | pin.py |
"""Custom PulseIn Class to read PWM signals"""
import time
import subprocess
import os
import atexit
import random
import sysv_ipc
DEBUG = False
queues = []
procs = []
# The message queues live outside of python space, and must be formally cleaned!
def final():
"""In case the program is cancelled or quit, we need to clean up the PulseIn
helper process and also the message queue, this is called at exit to do so"""
if DEBUG:
print("Cleaning up message queues", queues)
print("Cleaning up processes", procs)
for q in queues:
q.remove()
for proc in procs:
proc.terminate()
atexit.register(final)
# pylint: disable=c-extension-no-member
class PulseIn:
"""PulseIn Class to read PWM signals"""
def __init__(self, pin, maxlen=2, idle_state=False):
"""Create a PulseIn object associated with the given pin.
The object acts as a read-only sequence of pulse lengths with
a given max length. When it is active, new pulse lengths are
added to the end of the list. When there is no more room
(len() == maxlen) the oldest pulse length is removed to make room."""
if isinstance(pin.id, tuple):
self._pin = str(pin.id[1])
self._chip = "gpiochip{}".format(pin.id[0])
else:
self._pin = str(pin.id)
self._chip = "gpiochip0"
self._maxlen = maxlen
self._idle_state = idle_state
self._queue_key = random.randint(1, 9999)
try:
self._mq = sysv_ipc.MessageQueue(None, flags=sysv_ipc.IPC_CREX)
if DEBUG:
print("Message Queue Key: ", self._mq.key)
queues.append(self._mq)
except sysv_ipc.ExistentialError:
raise RuntimeError(
"Message queue creation failed"
) from sysv_ipc.ExistentialError
# Check if OS is 64-bit
libgpiod_filename = "libgpiod_pulsein"
dir_path = os.path.dirname(os.path.realpath(__file__))
cmd = [
dir_path + "/" + libgpiod_filename,
"--pulses",
str(maxlen),
"--queue",
str(self._mq.key),
]
if idle_state:
cmd.append("-i")
cmd.append(self._chip)
cmd.append(self._pin)
if DEBUG:
print(cmd)
self._process = subprocess.Popen(cmd) # pylint: disable=consider-using-with
procs.append(self._process)
# wait for it to start up
if DEBUG:
print("Waiting for startup success message from subprocess")
message = self._wait_receive_msg(timeout=0.25)
if message[0] != b"!":
raise RuntimeError("Could not establish message queue with subprocess")
self._paused = False
# pylint: disable=redefined-builtin
def _wait_receive_msg(self, timeout=0, type=2):
"""Internal helper that will wait for new messages of a given type,
and throw an exception on timeout"""
if timeout > 0:
stamp = time.monotonic()
while (time.monotonic() - stamp) < timeout:
try:
message = self._mq.receive(block=False, type=type)
return message
except sysv_ipc.BusyError:
time.sleep(0.001) # wait a bit then retry!
# uh-oh timed out
raise RuntimeError(
"Timed out waiting for PulseIn message. Make sure libgpiod is installed."
)
message = self._mq.receive(block=True, type=type)
return message
# pylint: enable=redefined-builtin
def deinit(self):
"""Deinitialises the PulseIn and releases any hardware and software
resources for reuse."""
# Clean up after ourselves
self._process.terminate()
procs.remove(self._process)
self._mq.remove()
queues.remove(self._mq)
def __enter__(self):
"""No-op used by Context Managers."""
return self
def __exit__(self, exc_type, exc_value, tb):
"""Automatically deinitializes the hardware when exiting a context."""
self.deinit()
def resume(self, trigger_duration=0):
"""Resumes pulse capture after an optional trigger pulse."""
if trigger_duration != 0:
self._mq.send("t%d" % trigger_duration, True, type=1)
else:
self._mq.send("r", True, type=1)
self._paused = False
def pause(self):
"""Pause pulse capture"""
self._mq.send("p", True, type=1)
self._paused = True
@property
def paused(self):
"""True when pulse capture is paused as a result of pause() or
an error during capture such as a signal that is too fast."""
return self._paused
@property
def maxlen(self):
"""The maximum length of the PulseIn. When len() is equal to maxlen,
it is unclear which pulses are active and which are idle."""
return self._maxlen
def clear(self):
"""Clears all captured pulses"""
self._mq.send("c", True, type=1)
def popleft(self):
"""Removes and returns the oldest read pulse."""
self._mq.send("^", True, type=1)
message = self._wait_receive_msg()
reply = int(message[0].decode("utf-8"))
# print(reply)
if reply == -1:
raise IndexError("pop from empty list")
return reply
def __len__(self):
"""Returns the current pulse length"""
self._mq.send("l", True, type=1)
message = self._wait_receive_msg()
return int(message[0].decode("utf-8"))
# pylint: disable=redefined-builtin
def __getitem__(self, index, type=None):
"""Returns the value at the given index or values in slice."""
self._mq.send("i%d" % index, True, type=1)
message = self._wait_receive_msg()
ret = int(message[0].decode("utf-8"))
if ret == -1:
raise IndexError("list index out of range")
return ret
# pylint: enable=redefined-builtin | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/amlogic/meson_g12_common/pulseio/PulseIn.py | PulseIn.py |
import re
import gpiod
from adafruit_blinka.microcontroller.generic_linux.libgpiod_pin import Pin
chip0 = gpiod.Chip("0")
chip1 = gpiod.Chip("1")
if chip0.num_lines() < 20:
aobus = 0
periphs = 1
periphs_offset = chip1.num_lines() - 85
else:
aobus = 1
periphs = 0
periphs_offset = chip0.num_lines() - 85
chip0.close()
chip1.close()
GPIOAO_0 = GPIO496 = Pin((aobus, 0))
GPIOAO_1 = GPIO497 = Pin((aobus, 1))
GPIOAO_2 = GPIO498 = Pin((aobus, 2))
GPIOAO_3 = GPIO499 = Pin((aobus, 3))
GPIOAO_4 = GPIO500 = Pin((aobus, 4))
GPIOAO_5 = GPIO501 = Pin((aobus, 5))
GPIOAO_6 = GPIO502 = Pin((aobus, 6))
GPIOAO_7 = GPIO503 = Pin((aobus, 7))
GPIOAO_8 = GPIO504 = Pin((aobus, 8))
GPIOAO_9 = GPIO505 = Pin((aobus, 9))
GPIOAO_10 = GPIO506 = Pin((aobus, 10))
GPIOAO_11 = GPIO507 = Pin((aobus, 11))
GPIOE_0 = GPIO508 = Pin((aobus, 12))
GPIOE_1 = GPIO509 = Pin((aobus, 13))
GPIOE_2 = GPIO510 = Pin((aobus, 14))
GPIOZ_0 = GPIO427 = Pin((periphs, 0 + periphs_offset))
GPIOZ_1 = GPIO428 = Pin((periphs, 1 + periphs_offset))
GPIOZ_2 = GPIO429 = Pin((periphs, 2 + periphs_offset))
GPIOZ_3 = GPIO430 = Pin((periphs, 3 + periphs_offset))
GPIOZ_4 = GPIO431 = Pin((periphs, 4 + periphs_offset))
GPIOZ_5 = GPIO432 = Pin((periphs, 5 + periphs_offset))
GPIOZ_6 = GPIO433 = Pin((periphs, 6 + periphs_offset))
GPIOZ_7 = GPIO434 = Pin((periphs, 7 + periphs_offset))
GPIOZ_8 = GPIO435 = Pin((periphs, 8 + periphs_offset))
GPIOZ_9 = GPIO436 = Pin((periphs, 9 + periphs_offset))
GPIOZ_10 = GPIO437 = Pin((periphs, 10 + periphs_offset))
GPIOZ_11 = GPIO438 = Pin((periphs, 11 + periphs_offset))
GPIOZ_12 = GPIO439 = Pin((periphs, 12 + periphs_offset))
GPIOZ_13 = GPIO440 = Pin((periphs, 13 + periphs_offset))
GPIOZ_14 = GPIO441 = Pin((periphs, 14 + periphs_offset))
GPIOZ_15 = GPIO442 = Pin((periphs, 15 + periphs_offset))
GPIOH_0 = GPIO443 = Pin((periphs, 16 + periphs_offset))
GPIOH_1 = GPIO444 = Pin((periphs, 17 + periphs_offset))
GPIOH_2 = GPIO445 = Pin((periphs, 18 + periphs_offset))
GPIOH_3 = GPIO446 = Pin((periphs, 19 + periphs_offset))
GPIOH_4 = GPIO447 = Pin((periphs, 20 + periphs_offset))
GPIOH_5 = GPIO448 = Pin((periphs, 21 + periphs_offset))
GPIOH_6 = GPIO449 = Pin((periphs, 22 + periphs_offset))
GPIOH_7 = GPIO450 = Pin((periphs, 23 + periphs_offset))
GPIOH_8 = GPIO451 = Pin((periphs, 24 + periphs_offset))
BOOT_0 = GPIO452 = Pin((periphs, 25 + periphs_offset))
BOOT_1 = GPIO453 = Pin((periphs, 26 + periphs_offset))
BOOT_2 = GPIO454 = Pin((periphs, 27 + periphs_offset))
BOOT_3 = GPIO455 = Pin((periphs, 28 + periphs_offset))
BOOT_4 = GPIO456 = Pin((periphs, 29 + periphs_offset))
BOOT_5 = GPIO457 = Pin((periphs, 30 + periphs_offset))
BOOT_6 = GPIO458 = Pin((periphs, 31 + periphs_offset))
BOOT_7 = GPIO459 = Pin((periphs, 32 + periphs_offset))
BOOT_8 = GPIO460 = Pin((periphs, 33 + periphs_offset))
BOOT_9 = GPIO461 = Pin((periphs, 34 + periphs_offset))
BOOT_10 = GPIO462 = Pin((periphs, 35 + periphs_offset))
BOOT_11 = GPIO463 = Pin((periphs, 36 + periphs_offset))
BOOT_12 = GPIO464 = Pin((periphs, 37 + periphs_offset))
BOOT_13 = GPIO465 = Pin((periphs, 38 + periphs_offset))
BOOT_14 = GPIO466 = Pin((periphs, 39 + periphs_offset))
BOOT_15 = GPIO467 = Pin((periphs, 40 + periphs_offset))
GPIOC_0 = GPIO468 = Pin((periphs, 41 + periphs_offset))
GPIOC_1 = GPIO469 = Pin((periphs, 42 + periphs_offset))
GPIOC_2 = GPIO470 = Pin((periphs, 43 + periphs_offset))
GPIOC_3 = GPIO471 = Pin((periphs, 44 + periphs_offset))
GPIOC_4 = GPIO472 = Pin((periphs, 45 + periphs_offset))
GPIOC_5 = GPIO473 = Pin((periphs, 46 + periphs_offset))
GPIOC_6 = GPIO474 = Pin((periphs, 47 + periphs_offset))
GPIOC_7 = GPIO475 = Pin((periphs, 48 + periphs_offset))
GPIOA_0 = GPIO460 = Pin((periphs, 49 + periphs_offset))
GPIOA_1 = GPIO461 = Pin((periphs, 50 + periphs_offset))
GPIOA_2 = GPIO462 = Pin((periphs, 51 + periphs_offset))
GPIOA_3 = GPIO463 = Pin((periphs, 52 + periphs_offset))
GPIOA_4 = GPIO464 = Pin((periphs, 53 + periphs_offset))
GPIOA_5 = GPIO465 = Pin((periphs, 54 + periphs_offset))
GPIOA_6 = GPIO466 = Pin((periphs, 55 + periphs_offset))
GPIOA_7 = GPIO467 = Pin((periphs, 56 + periphs_offset))
GPIOA_8 = GPIO468 = Pin((periphs, 57 + periphs_offset))
GPIOA_9 = GPIO469 = Pin((periphs, 58 + periphs_offset))
GPIOA_10 = GPIO470 = Pin((periphs, 59 + periphs_offset))
GPIOA_11 = GPIO471 = Pin((periphs, 60 + periphs_offset))
GPIOA_12 = GPIO472 = Pin((periphs, 61 + periphs_offset))
GPIOA_13 = GPIO473 = Pin((periphs, 62 + periphs_offset))
GPIOA_14 = GPIO474 = Pin((periphs, 63 + periphs_offset))
GPIOA_15 = GPIO475 = Pin((periphs, 64 + periphs_offset))
GPIOX_0 = GPIO476 = Pin((periphs, 65 + periphs_offset))
GPIOX_1 = GPIO477 = Pin((periphs, 66 + periphs_offset))
GPIOX_2 = GPIO478 = Pin((periphs, 67 + periphs_offset))
GPIOX_3 = GPIO479 = Pin((periphs, 68 + periphs_offset))
GPIOX_4 = GPIO480 = Pin((periphs, 69 + periphs_offset))
GPIOX_5 = GPIO481 = Pin((periphs, 70 + periphs_offset))
GPIOX_6 = GPIO482 = Pin((periphs, 71 + periphs_offset))
GPIOX_7 = GPIO483 = Pin((periphs, 72 + periphs_offset))
GPIOX_8 = GPIO484 = Pin((periphs, 73 + periphs_offset))
GPIOX_9 = GPIO485 = Pin((periphs, 74 + periphs_offset))
GPIOX_10 = GPIO486 = Pin((periphs, 75 + periphs_offset))
GPIOX_11 = GPIO487 = Pin((periphs, 76 + periphs_offset))
GPIOX_12 = GPIO488 = Pin((periphs, 77 + periphs_offset))
GPIOX_13 = GPIO489 = Pin((periphs, 78 + periphs_offset))
GPIOX_14 = GPIO490 = Pin((periphs, 79 + periphs_offset))
GPIOX_15 = GPIO491 = Pin((periphs, 80 + periphs_offset))
GPIOX_16 = GPIO492 = Pin((periphs, 81 + periphs_offset))
GPIOX_17 = GPIO493 = Pin((periphs, 82 + periphs_offset))
GPIOX_18 = GPIO494 = Pin((periphs, 83 + periphs_offset))
GPIOX_19 = GPIO495 = Pin((periphs, 84 + periphs_offset))
SPI0_SCLK = GPIOA_1
SPI0_MCLK0 = GPIOA_0
SPI0_SDO = GPIOA_3
SPI0_SDI = GPIOA_4
# ordered as spiId, sckId, mosiId, misoId
spiPorts = ((0, SPI0_SCLK, SPI0_MCLK0, SPI0_SDO, SPI0_SDI),)
UART1_TX = GPIOH_7
UART1_RX = GPIOH_6
# ordered as uartId, txId, rxId
uartPorts = ((1, UART1_TX, UART1_RX),)
def get_dts_alias(device: str) -> str:
"""Get the Device Tree Alias"""
uevent_path = "/sys/bus/platform/devices/" + device + "/uevent"
with open(uevent_path, "r", encoding="utf-8") as fd:
pattern = r"^OF_ALIAS_0=(.*)$"
uevent = fd.read().split("\n")
for line in uevent:
match = re.search(pattern, line)
if match:
return match.group(1).upper()
return None
# ordered as i2cId, sclId, sdaId
i2cPorts = []
alias = get_dts_alias("ff805000.i2c")
if alias is not None:
globals()[alias + "_SCL"] = GPIOX_18
globals()[alias + "_SDA"] = GPIOX_17
i2cPorts.append((int(alias[3]), GPIOX_18, GPIOX_17))
i2cPorts = tuple(i2cPorts) | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/amlogic/a311d/pin.py | pin.py |
"""Custom PulseIn Class to read PWM signals"""
import time
import subprocess
import os
import atexit
import random
import struct
import sysv_ipc
DEBUG = False
queues = []
procs = []
# The message queues live outside of python space, and must be formally cleaned!
def final():
"""In case the program is cancelled or quit, we need to clean up the PulseIn
helper process and also the message queue, this is called at exit to do so"""
if DEBUG:
print("Cleaning up message queues", queues)
print("Cleaning up processes", procs)
for q in queues:
q.remove()
for proc in procs:
proc.terminate()
atexit.register(final)
# pylint: disable=c-extension-no-member
class PulseIn:
"""PulseIn Class to read PWM signals"""
def __init__(self, pin, maxlen=2, idle_state=False):
"""Create a PulseIn object associated with the given pin.
The object acts as a read-only sequence of pulse lengths with
a given max length. When it is active, new pulse lengths are
added to the end of the list. When there is no more room
(len() == maxlen) the oldest pulse length is removed to make room."""
self._pin = pin
self._maxlen = maxlen
self._idle_state = idle_state
self._queue_key = random.randint(1, 9999)
try:
self._mq = sysv_ipc.MessageQueue(None, flags=sysv_ipc.IPC_CREX)
if DEBUG:
print("Message Queue Key: ", self._mq.key)
queues.append(self._mq)
except sysv_ipc.ExistentialError:
raise RuntimeError(
"Message queue creation failed"
) from sysv_ipc.ExistentialError
# Check if OS is 64-bit
if struct.calcsize("P") * 8 == 64: # pylint: disable=no-member
libgpiod_filename = "libgpiod_pulsein64"
else:
libgpiod_filename = "libgpiod_pulsein"
dir_path = os.path.dirname(os.path.realpath(__file__))
cmd = [
dir_path + "/" + libgpiod_filename,
"--pulses",
str(maxlen),
"--queue",
str(self._mq.key),
]
if idle_state:
cmd.append("-i")
cmd.append("gpiochip0")
cmd.append(str(pin))
if DEBUG:
print(cmd)
self._process = subprocess.Popen(cmd) # pylint: disable=consider-using-with
procs.append(self._process)
# wait for it to start up
if DEBUG:
print("Waiting for startup success message from subprocess")
message = self._wait_receive_msg(timeout=0.25)
if message[0] != b"!":
raise RuntimeError("Could not establish message queue with subprocess")
self._paused = False
# pylint: disable=redefined-builtin
def _wait_receive_msg(self, timeout=0, type=2):
"""Internal helper that will wait for new messages of a given type,
and throw an exception on timeout"""
if timeout > 0:
stamp = time.monotonic()
while (time.monotonic() - stamp) < timeout:
try:
message = self._mq.receive(block=False, type=type)
return message
except sysv_ipc.BusyError:
time.sleep(0.001) # wait a bit then retry!
# uh-oh timed out
raise RuntimeError(
"Timed out waiting for PulseIn message. Make sure libgpiod is installed."
)
message = self._mq.receive(block=True, type=type)
return message
# pylint: enable=redefined-builtin
def deinit(self):
"""Deinitialises the PulseIn and releases any hardware and software
resources for reuse."""
# Clean up after ourselves
self._process.terminate()
procs.remove(self._process)
self._mq.remove()
queues.remove(self._mq)
def __enter__(self):
"""No-op used by Context Managers."""
return self
def __exit__(self, exc_type, exc_value, tb):
"""Automatically deinitializes the hardware when exiting a context."""
self.deinit()
def resume(self, trigger_duration=0):
"""Resumes pulse capture after an optional trigger pulse."""
if trigger_duration != 0:
self._mq.send("t%d" % trigger_duration, True, type=1)
else:
self._mq.send("r", True, type=1)
self._paused = False
def pause(self):
"""Pause pulse capture"""
self._mq.send("p", True, type=1)
self._paused = True
@property
def paused(self):
"""True when pulse capture is paused as a result of pause() or
an error during capture such as a signal that is too fast."""
return self._paused
@property
def maxlen(self):
"""The maximum length of the PulseIn. When len() is equal to maxlen,
it is unclear which pulses are active and which are idle."""
return self._maxlen
def clear(self):
"""Clears all captured pulses"""
self._mq.send("c", True, type=1)
def popleft(self):
"""Removes and returns the oldest read pulse."""
self._mq.send("^", True, type=1)
message = self._wait_receive_msg()
reply = int(message[0].decode("utf-8"))
# print(reply)
if reply == -1:
raise IndexError("pop from empty list")
return reply
def __len__(self):
"""Returns the current pulse length"""
self._mq.send("l", True, type=1)
message = self._wait_receive_msg()
return int(message[0].decode("utf-8"))
# pylint: disable=redefined-builtin
def __getitem__(self, index, type=None):
"""Returns the value at the given index or values in slice."""
self._mq.send("i%d" % index, True, type=1)
message = self._wait_receive_msg()
ret = int(message[0].decode("utf-8"))
if ret == -1:
raise IndexError("list index out of range")
return ret
# pylint: enable=redefined-builtin | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/microcontroller/amlogic/a311d/pulseio/PulseIn.py | PulseIn.py |
"""Pin definitions for the Orangepi 4."""
from adafruit_blinka.microcontroller.rockchip.rk3399 import pin
# D pin number is ordered by physical pin sequence
# Reference: https://service.robots.org.nz/wiki/Wiki.jsp?page=OrangePi
# +------+-----+----------+------+---+OrangePi 4+---+---+--+----------+-----+------+
# | GPIO | wPi | Name | Mode | V | Physical | V | Mode | Name | wPi | GPIO |
# +------+-----+----------+------+---+----++----+---+------+----------+-----+------+
# | | | 3.3V | | | 1 || 2 | | | 5V | | |
# | 64 | 0 | I2C2_SDA | IN | 1 | 3 || 4 | | | 5V | | |
# | 65 | 1 | I2C2_SCL | IN | 1 | 5 || 6 | | | GND | | |
# | 150 | 2 | PWM1 | ALT2 | 1 | 7 || 8 | 1 | ALT2 | I2C3_SCL | 3 | 145 |
# | | | GND | | | 9 || 10 | 1 | ALT2 | I2C3_SDA | 4 | 144 |
# | 33 | 5 | GPIO1_A1 | IN | 0 | 11 || 12 | 1 | IN | GPIO1_C2 | 6 | 50 |
# | 35 | 7 | GPIO1_A3 | OUT | 1 | 13 || 14 | | | GND | | |
# | 92 | 8 | GPIO2_D4 | IN | 0 | 15 || 16 | 0 | IN | GPIO1_C6 | 9 | 54 |
# | | | 3.3V | | | 17 || 18 | 0 | IN | GPIO1_C7 | 10 | 55 |
# | 40 | 11 | SPI1_TXD | ALT3 | 0 | 19 || 20 | | | GND | | |
# | 39 | 12 | SPI1_RXD | ALT3 | 1 | 21 || 22 | 0 | IN | GPIO1_D0 | 13 | 56 |
# | 41 | 14 | SPI1_CLK | ALT3 | 1 | 23 || 24 | 1 | ALT3 | SPI1_CS | 15 | 42 |
# | | | GND | | | 25 || 26 | 0 | IN | GPIO4_C5 | 16 | 149 |
# | 64 | 17 | I2C2_SDA | IN | 1 | 27 || 28 | 1 | IN | I2C2_SCL | 18 | 65 |
# | | | I2S0_RX | | | 29 || 30 | | | GND | | |
# | | | I2S0_TX | | | 31 || 32 | | | I2S_CLK | | |
# | | | I2S0_SCK | | | 33 || 34 | | | GND | | |
# | | | I2S0_SI0 | | | 35 || 36 | | | I2S0_SO0 | | |
# | | | I2S0_SI1 | | | 37 || 38 | | | I2S0_SI2 | | |
# | | | GND | | | 39 || 40 | | | I2S0_SI3 | | |
# +------+-----+----------+------+---+----++----+---+------+----------+-----+------+
# | GPIO | wPi | Name | Mode | V | Physical | V | Mode | Name | wPi | GPIO |
# +------+-----+----------+------+---+OrangePi 4+---+---+--+----------+-----+------+
# D1 = VCC3V3_SYS
# D2 = VCC5V0_SYS
D3 = pin.I2C2_SDA # I2C2_SDA_3V0
# D4 = VCC5V0_SYS
D5 = pin.I2C2_SCL # I2C2_SCL_3V0
# D6 = GND
D7 = pin.GPIO4_C6 # GPIO4_C6/PWM1
D8 = pin.I2C3_SCL # I2C3_SCL
# D9 = GND
D10 = pin.I2C3_SDA # I2C3_SDA
D11 = pin.GPIO1_A1 # GPIO1_A1
D12 = pin.GPIO1_C2 # GPIO1_C2
D13 = pin.GPIO1_A3 # GPIO1_A3
# D14 = GND
D15 = pin.GPIO2_D4 # GPIO2_D4
D16 = pin.GPIO1_C6 # GPIO1_C6
# D17 = GND
D18 = pin.GPIO1_C7 # GPIO1_C7
D19 = pin.GPIO1_B0 # UART4_TX / SPI1_TXD
# D20 = GND
D21 = pin.GPIO1_A7 # UART4_RX / SPI1_RXD
D22 = pin.GPIO1_D0 # GPIO1_D0
D23 = pin.GPIO1_B1 # SPI1_CLK
D24 = pin.GPIO1_B2 # SPI1_CSn0
# D25 = GND
D26 = pin.GPIO4_C5 # GPIO4_C5
D27 = pin.I2C2_SDA # I2C2_SDA
D28 = pin.I2C2_SCL # I2C2_SCL
# D29 = pin.I2S0_LRCK_RX
# D30 = GND
# D31 = pin.I2S0_LRCK_TX
# D32 = pin.I2S_CLK
# D33 = pin.I2S0_SCLK
# D34 = GND
# D35 = pin.I2S0_SDI0
# D36 = pin.I2S0_SDO0
# D37 = pin.I2S0_SDI1SDO_3
# D38 = pin.I2S0_SDI2SDO2
# D39 = GND
# D40 = pin.I2S0_SDI3SDO1
# UART
UART4_TX = pin.GPIO1_B0
UART4_RX = pin.GPIO1_A7 | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/board/orangepi/orangepi4.py | orangepi4.py |
"""Pin definitions for the Odroid N2."""
from adafruit_blinka.microcontroller.amlogic.s922x import pin
GPIOX_0 = pin.GPIO476
GPIOX_1 = pin.GPIO477
GPIOX_2 = pin.GPIO478
GPIOX_3 = pin.GPIO479
GPIOX_4 = pin.GPIO480
GPIOX_5 = pin.GPIO481
GPIOX_6 = pin.GPIO482
GPIOX_7 = pin.GPIO483
GPIOX_8 = pin.GPIO484
GPIOX_9 = pin.GPIO485
GPIOX_10 = pin.GPIO486
GPIOX_11 = pin.GPIO487
GPIOX_12 = pin.GPIO488
GPIOX_13 = pin.GPIO489
GPIOX_14 = pin.GPIO490
GPIOX_15 = pin.GPIO491
GPIOX_16 = pin.GPIO492
GPIOX_17 = pin.GPIO493
GPIOX_18 = pin.GPIO494
GPIOX_19 = pin.GPIO495
GPIODV_24 = pin.GPIO493
GPIODV_25 = pin.GPIO494
GPIODV_26 = pin.GPIO474
GPIODV_27 = pin.GPIO475
GPIOA_4 = pin.GPIO464
GPIOA_12 = pin.GPIO472
GPIOA_13 = pin.GPIO473
GPIOA_14 = pin.GPIO474
GPIOA_15 = pin.GPIO475
GPIOA0_0 = pin.GPIO496
GPIOA0_1 = pin.GPIO497
GPIOA0_2 = pin.GPIO498
GPIOA0_3 = pin.GPIO499
GPIOA0_4 = pin.GPIO500
GPIOA0_5 = pin.GPIO501
GPIOA0_6 = pin.GPIO502
GPIOA0_7 = pin.GPIO503
GPIOA0_8 = pin.GPIO504
GPIOA0_9 = pin.GPIO505
GPIOA0_10 = pin.GPIO506
GPIOA0_11 = pin.GPIO507
GPIOA0_12 = pin.GPIO508
GPIOA0_13 = pin.GPIO509
GPIOA0_14 = pin.GPIO510
GPIOA0_15 = pin.GPIO511
for it in pin.i2cPorts:
globals()["SCL" + str(it[0])] = it[1]
globals()["SDA" + str(it[0])] = it[2]
# Set second i2c bus as default for backward compatibility.
SCL = pin.i2cPorts[1][1]
SDA = pin.i2cPorts[1][2]
SCLK = pin.SPI0_SCLK
MOSI = pin.SPI0_MOSI
MISO = pin.SPI0_MISO
SPI_CS0 = pin.GPIO486
D0 = GPIOX_3 # PIN_11
D1 = GPIOX_16 # PIN_12
D2 = GPIOX_4 # PIN_13
D3 = GPIOX_7 # PIN_15
D4 = GPIOX_0 # PIN_16
D5 = GPIOX_1 # PIN_18
D6 = GPIOX_2 # PIN_22
D7 = GPIOA_13 # PIN_7
D8 = GPIOX_17 # PIN_3
D9 = GPIOX_18 # PIN_5
D10 = GPIOX_10 # PIN_24
D11 = GPIOA_4 # PIN_26
D12 = GPIOX_8 # PIN_19
D13 = GPIOX_9 # PIN_21
D14 = GPIOX_11 # PIN_23
D15 = GPIOX_12 # PIN_8
D16 = GPIOX_13 # PIN_10
D21 = GPIOX_14 # PIN_29
D22 = GPIOX_15 # PIN_31
D23 = GPIOX_5 # PIN_33
D24 = GPIOX_6 # PIN_35
D26 = GPIOA_12 # PIN_32
D27 = GPIOX_19 # PIN_36
D30 = GPIOA_14 # PIN_27
D31 = GPIOA_15 # PIN_28 | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/board/hardkernel/odroidn2.py | odroidn2.py |
from adafruit_blinka.microcontroller.rockchip.rk3588 import pin
# D pin number is ordered by physical pin sequence
# D1 = +3.3V
# D2 = +5V
D3 = pin.GPIO4_B3
# D4 = +5V
D5 = pin.GPIO4_B2
# D6 = GND
D7 = pin.GPIO3_C3
D8 = pin.GPIO0_B5
# D9 = GND
D10 = pin.GPIO0_B6
D11 = pin.GPIO3_C1
D12 = pin.GPIO3_B5
D13 = pin.GPIO3_B7
# D14 = GND
D15 = pin.GPIO3_C0
D16 = pin.GPIO3_A4
# D17 = +3.3V
D18 = pin.GPIO4_C4
D19 = pin.GPIO1_B2
# D20 = GND
D21 = pin.GPIO1_B1
# D22 = ADC_IN0 // SARADC_IN4
D23 = pin.GPIO1_B3
D24 = pin.GPIO1_B4
# D25 = GND
D26 = pin.GPIO1_B5
D27 = pin.GPIO4_C6
D28 = pin.GPIO4_C5
D29 = pin.GPIO1_D7
# D30 = GND
D31 = pin.GPIO1_B7
D32 = pin.GPIO3_C2
D33 = pin.GPIO3_A7
# D34 = GND
D35 = pin.GPIO3_B6
D36 = pin.GPIO3_B1
# D37 = NC
D38 = pin.GPIO3_B2
# D39 = GND
D40 = pin.GPIO3_B3
# UART
# UART2_M0
UART2_TX = pin.GPIO0_B5
UART2_RX = pin.GPIO0_B6
# UART3_M1
UART3_TX = pin.GPIO3_B5
UART3_RX = pin.GPIO3_B6
# UART4_M2
UART4_TX = pin.GPIO1_B3
UART4_RX = pin.GPIO1_B2
# UART7_M1
UART7_TX = pin.GPIO3_C0
UART7_RX = pin.GPIO3_C1
# Default UART -> UART2_M0
TX = UART2_TX
RX = UART2_RX
TXD = UART2_TX
RXD = UART2_RX
# I2C
# I2C0_M1
I2C0_SCL = pin.GPIO4_C5
I2C0_SDA = pin.GPIO4_C6
# I2C1_M0
I2C1_SCL = pin.GPIO0_B5
I2C1_SDA = pin.GPIO0_B6
# I2C3_M1
I2C3_SCL = pin.GPIO3_B7
I2C3_SDA = pin.GPIO3_C0
# I2C7_M3
I2C7_SCL = pin.GPIO4_B2
I2C7_SDA = pin.GPIO4_B3
# I2C8_M4
I2C8_SCL = pin.GPIO3_C2
I2C8_SDA = pin.GPIO3_C3
# Default I2C -> I2C7_M3
SCL = I2C7_SCL
SDA = I2C7_SDA
# SPI
# SPI0_M2
SPI0_MOSI = pin.GPIO1_B2
SPI0_MISO = pin.GPIO1_B1
SPI0_CLK = pin.GPIO1_B3
SPI0_SCLK = SPI0_CLK
SPI0_CS0 = pin.GPIO1_B4
SPI0_CS1 = pin.GPIO1_B5
# SPI1_M1
SPI1_MOSI = pin.GPIO3_B7
SPI1_MISO = pin.GPIO3_C0
SPI1_CLK = pin.GPIO3_C1
SPI1_SCLK = SPI1_CLK
SPI1_CS0 = pin.GPIO3_C2
SPI1_CS1 = pin.GPIO3_C3
# SPI3_M0
SPI3_MISO = pin.GPIO4_C4
SPI3_MOSI = pin.GPIO4_C5
SPI3_SCK = pin.GPIO4_C6
SPI3_SCLK = SPI3_SCK
# Default SPI -> SPI0_M2
MOSI = SPI0_MOSI
MISO = SPI0_MISO
SCLK = SPI0_SCLK
CS = SPI0_CS0
CS1 = SPI0_CS1
# PWM
# PWM2_M1
PWM2 = pin.GPIO3_B1
# PWM3_IR_M1
PWM3 = pin.GPIO3_B2
# PWM5_M2
PWM5 = pin.GPIO4_C4
# PWM6_M2
PWM6 = pin.GPIO4_C5
# PWM7_IR_M3
PWM7 = pin.GPIO4_C6
# PWM8_M0
PWM8 = pin.GPIO3_A7
# PWM12_M0
PWM12 = pin.GPIO3_B5
# PWM13_M0
PWM13 = pin.GPIO3_B6
# PWM14_M0
PWM14 = pin.GPIO3_C2
# PWM15_IR_M0
PWM15 = pin.GPIO3_C3
# ADC
ADC_IN0 = pin.ADC_IN0 | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/board/radxa/rock5.py | rock5.py |
"""Pin definitions for the Radxa CM3."""
from adafruit_blinka.microcontroller.rockchip.rk3566 import pin
# CM3 IO pins
D0_B6 = pin.GPIO0_B6 # /I2C2_SDA_M0/SPI0_MOSI_M0/PWM2_M1
D0_B5 = pin.GPIO0_B5 # /I2C2_SCL_M0/SPI0_CLK_M0/PWM1_M1
D3_D5 = pin.GPIO3_D5 # /I2S1_SDI3_M1/SDMMC2_PWREN_M0
D0_D1 = pin.GPIO0_D1 # /UART2_TX_M0
D0_D0 = pin.GPIO0_D0 # /UART2_RX_M0
D0_C7 = pin.GPIO0_C7 # /PWM0_M1/UART0_CTSn
D3_C7 = pin.GPIO3_C7 # /I2S1_SCLK_TX_M1/SDMMC2_D1_M0
D0_B7 = pin.GPIO0_B7 # /PWM0_M0
D0_C3 = pin.GPIO0_C3 # /PWM4
D3_D4 = pin.GPIO3_D4 # /I2S1_SDI2_M1/SDMMC2_DET_M0
D3_D3 = pin.GPIO3_D3 # /I2S1_SDI1_M1/SDMMC2_CLK_M0
D4_B2 = pin.GPIO4_B2 # /SPI3_MOSI_M0/I2S2_SDI_M1/I2C4_SDA_M0
D4_B0 = pin.GPIO4_B0 # /SPI3_MISO_M0/I2S1_SDO1_M1
D3_C6 = pin.GPIO3_C6 # /I2S1_MCLK_M1/SDMMC2_D0_M0
D4_B3 = pin.GPIO4_B3 # /SPI3_CLK_M0/I2S2_SDO_M1/I2C4_SCL_M0
D4_A6 = pin.GPIO4_A6 # /SPI3_CS0_M0/I2S1_SCLK_RX
D4_B4 = pin.GPIO4_B4 # /I2C2_SDA_M1
D4_B5 = pin.GPIO4_B5 # /I2C2_SCL_M1/I2S1_SDO3_M1
D4_B1 = pin.GPIO4_B1 # /I2S1_SDO2_M1/ISP_PRELIGHT_TRIG
D0_C5 = pin.GPIO0_C5 # /SPI0_MISO_M0/PWM6
D4_C0 = pin.GPIO4_C0 # /PWM11_IR_M1
D0_C6 = pin.GPIO0_C6 # /SPI0_CS0_M0/PWM7_IR
D3_D0 = pin.GPIO3_D0 # /I2S1_LRCK_TX_M1/SDMMC2_D2_M0
D4_A7 = pin.GPIO4_A7 # /I2S1_LRCK_RX_M1/SPI3_CS1_M0
D0_C2 = pin.GPIO0_C2 # /PWM3_IR
D3_D2 = pin.GPIO3_D2 # /I2S1_SDI0_M1
D3_D1 = pin.GPIO3_D1 # /I2S1_SDO0_M1/SDMMC2_D3_M0
D0_B1 = pin.GPIO0_B1 # /I2C0_SCL
D0_B2 = pin.GPIO0_B2 # /I2C0_SDA
# Aliases for Raspberry Pi compute module compatibility
D2 = D0_B6
D3 = D0_B5
D4 = D3_D5
D5 = D4_B1
D6 = D0_C5
D8 = D4_A6
D9 = D4_B0
D10 = D4_B2
D11 = D4_B3
D12 = D4_C0
D13 = D0_C6
D14 = D0_D1
D15 = D0_D0
D16 = D4_A7
D17 = D0_C7
D18 = D3_C7
D19 = D3_D0
D20 = D3_D2
D21 = D3_D1
D22 = D0_C3
D23 = D3_D4
D24 = D3_D3
D25 = D3_C6
D26 = D0_C2
D27 = D0_B7
D44 = D0_B2
D45 = D0_B1
# I2C
SDA = D0_B6
SCL = D0_B5
# SPI
CE0 = D4_A6
SCLK = D4_B3
SCK = D4_B3
MOSI = D4_B2
MISO = D4_B0
# UART aliases
UART_TX = D0_D1
UART_RX = D0_D0
TXD = D0_D1
RXD = D0_D0
TX = D0_D1
RX = D0_D0 | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/board/radxa/radxacm3.py | radxacm3.py |
"""Pin definitions for the Beaglebone Black."""
from adafruit_blinka.microcontroller.am335x import pin
# initial pins, to mimic bonescript demo
# BeagleBone Black
# P8_1 = DGND # DGND
# P8_2 = DGND # DGND
P8_3 = pin.P8_3 # GPIO1_6 - GPIO_38
P8_4 = pin.P8_4 # GPIO1_7 - GPIO_39
P8_5 = pin.P8_5 # GPIO1_2 - GPIO_34
P8_6 = pin.P8_6 # GPIO1_3 - GPIO_35
P8_7 = pin.P8_7 # TIMER4 - GPIO_66
P8_8 = pin.P8_8 # TIMER7 - GPIO_67
P8_9 = pin.P8_9 # TIMER5 - GPIO_69
P8_10 = pin.P8_10 # TIMER6 - GPIO_68
P8_11 = pin.P8_11 # GPIO1_13 - GPIO_45
P8_12 = pin.P8_12 # GPIO1_12 - GPIO_44
P8_13 = pin.P8_13 # EHRPWM2B - GPIO_23
P8_14 = pin.P8_14 # GPIO0_26 - GPIO_26
P8_15 = pin.P8_15 # GPIO1_15 - GPIO_47
P8_16 = pin.P8_16 # GPIO1_14 - GPIO_46
P8_17 = pin.P8_17 # GPIO0_27 - GPIO_27
P8_18 = pin.P8_18 # GPIO2_1 - GPIO_65
P8_19 = pin.P8_19 # EHRPWM2A - GPIO_22
P8_20 = pin.P8_20 # GPIO1_31 - GPIO_63
P8_21 = pin.P8_21 # GPIO1_30 - GPIO_62
P8_22 = pin.P8_22 # GPIO1_5 - GPIO_37
P8_23 = pin.P8_23 # GPIO1_4 - GPIO_36
P8_24 = pin.P8_24 # GPIO1_1 - GPIO_33
P8_25 = pin.P8_25 # GPIO1_0 - GPIO_32
P8_26 = pin.P8_26 # GPIO1_29 - GPIO_61
P8_27 = pin.P8_27 # GPIO2_22 - GPIO_86
P8_28 = pin.P8_28 # GPIO2_24 - GPIO_88
P8_29 = pin.P8_29 # GPIO2_23 - GPIO_87
P8_30 = pin.P8_30 # GPIO2_25 - GPIO_89
P8_31 = pin.P8_31 # UART5_CTSN - GPIO_10
P8_32 = pin.P8_32 # UART5_RTSN - GPIO_11
P8_33 = pin.P8_33 # UART4_RTSN - GPIO_9
P8_34 = pin.P8_34 # UART3_RTSN - GPIO_81
P8_35 = pin.P8_35 # UART4_CTSN - GPIO_8
P8_36 = pin.P8_36 # UART3_CTSN - GPIO_80
P8_37 = pin.P8_37 # UART5_TXD - GPIO_78
P8_38 = pin.P8_38 # UART5_RXD - GPIO_79
P8_39 = pin.P8_39 # GPIO2_12 - GPIO_76
P8_40 = pin.P8_40 # GPIO2_13 - GPIO_77
P8_41 = pin.P8_41 # GPIO2_10 - GPIO_74
P8_42 = pin.P8_42 # GPIO2_11 - GPIO_75
P8_43 = pin.P8_43 # GPIO2_8 - GPIO_72
P8_44 = pin.P8_44 # GPIO2_9 - GPIO_73
P8_45 = pin.P8_45 # GPIO2_6 - GPIO_70
P8_46 = pin.P8_46 # GPIO2_7 - GPIO_71
# P9_1 = DGND # DGND
# P9_2 = DGND # DGND
# P9_3 = VDD_3V3 # VDD_3V3
# P9_4 = VDD_3V3 # VDD_3V3
# P9_5 = VDD_5V # VDD_5V
# P9_6 = VDD_5V # VDD_5V
# P9_7 = SYS_5V # SYS_5V
# P9_8 = SYS_5V # SYS_5V
# P9_9 = PWR_BUT # PWR_BUT
# P9_10 = SYS_RESETN # SYS_RESETn
P9_11 = pin.P9_11 # UART4_RXD - GPIO_30
P9_12 = pin.P9_12 # GPIO1_28 - GPIO_60
P9_13 = pin.P9_13 # UART4_TXD - GPIO_31
P9_14 = pin.P9_14 # EHRPWM1A - GPIO_50
P9_15 = pin.P9_15 # GPIO1_16 - GPIO_48
P9_16 = pin.P9_16 # EHRPWM1B - GPIO_51
P9_17 = pin.P9_17 # I2C1_SCL - GPIO_5
P9_18 = pin.P9_18 # I2C1_SDA - GPIO_4
P9_19 = pin.P9_19 # I2C2_SCL - GPIO_13
P9_20 = pin.P9_20 # I2C2_SDA - GPIO_12
P9_21 = pin.P9_21 # UART2_TXD - GPIO_3
P9_22 = pin.P9_22 # UART2_RXD - GPIO_2
P9_23 = pin.P9_23 # GPIO1_17 - GPIO_49
P9_24 = pin.P9_24 # UART1_TXD - GPIO_15
P9_25 = pin.P9_25 # GPIO3_21 - GPIO_117
P9_26 = pin.P9_26 # UART1_RXD - GPIO_14
P9_27 = pin.P9_27 # GPIO3_19 - GPIO_115
P9_28 = pin.P9_28 # SPI1_CS0 - GPIO_113
P9_29 = pin.P9_29 # SPI1_D0 - GPIO_111
P9_30 = pin.P9_30 # SPI1_D1 - GPIO_112
P9_31 = pin.P9_31 # SPI1_SCLK - GPIO_110
# P9_32 = VDD_ADC # VDD_ADC
# P9_33 = AIN4 # AIN4
# P9_34 = GNDA_ADC # GNDA_ADC
# P9_35 = AIN6 # AIN6
# P9_36 = AIN5 # AIN5
# P9_37 = AIN2 # AIN2
# P9_38 = AIN3 # AIN3
# P9_39 = AIN0 # AIN0
# P9_40 = AIN1 # AIN1
P9_41 = pin.P9_41 # CLKOUT2 - GPIO_20
P9_42 = pin.P9_42 # GPIO0_7 - GPIO_7
# P9_43 = DGND # DGND
# P9_44 = DGND # DGND
# P9_45 = DGND # DGND
# P9_46 = DGND # DGND
# common to all beagles
LED_USR0 = pin.USR0
LED_USR1 = pin.USR1
LED_USR2 = pin.USR2
LED_USR3 = pin.USR3
# I2C and SPI pins from:
# src/adafruit_blinka/board/raspi_40pin.py
# SDA = pin.SDA
# SCL = pin.SCL
# CE1 = pin.D7
# CE0 = pin.D8
# MISO = pin.D9
# MOSI = pin.D10
# SCLK = pin.D11
# SCK = pin.D11
# TXD = pin.D14
# RXD = pin.D15
# MISO_1 = pin.D19
# MOSI_1 = pin.D20
# SCLK_1 = pin.D21
# SCK_1 = pin.D21
SDA = pin.I2C2_SDA # P9_19
SCL = pin.I2C2_SCL # P9_20
# Refer to header default pin modes
# http://beagleboard.org/static/images/cape-headers.png
#
# P9_17 (SPI0_CSO => CE0) enables peripheral device
# P9_18 (SPI0_D1 => MOSI) outputs data to peripheral device
# P9_21 (SPIO_DO => MISO) receives data from peripheral device
# P9_22 (SPI0_SCLK => SCLK) outputs clock signal
#
# Use config-pin to set pin mode for SPI pins
# https://github.com/beagleboard/bb.org-overlays/tree/master/tools/beaglebone-universal-io
# config-pin p9.17 spi_cs
# config-pin p9.18 spi
# config-pin p9.21 spi
# config-pin p9.22 spi_sclk
#
CE0 = pin.SPI0_CS0 # P9_17
MOSI = pin.SPI0_D1 # P9_18
MISO = pin.SPI0_D0 # P9_21
SCLK = pin.SPI0_SCLK # P9_22
# CircuitPython naming convention for SPI Clock
SCK = SCLK
# Pins for SPI1
# refer to:
# http://beagleboard.org/static/images/cape-headers-spi.png
#
# CE1 P9.28 SPI1_CS0
# MISO_1 P9.29 SPI1_D0
# MOSI_1 P9.30 SPI1_D1
# SCLK_1 P9.31 SPI_SCLK
#
# SPI1 conflicts with HDMI Audio (McASP)
#
# Refer to:
# https://elinux.org/Beagleboard:BeagleBoneBlack_Debian#U-Boot_Overlays
#
# To Disable HDMI AUDIO, uncomment this line in /boot/uEnv.txt:
# disable_uboot_overlay_audio=1
#
# Set pin modes for SPI1 with:
#
# config-pin p9.28 spi1_cs
# config-pin p9.29 spi1
# config-pin p9.30 spi1
# config-pin p9.31 spi_sclk
CE1 = pin.SPI1_CS0 # P9_28
MOSI_1 = pin.SPI1_D0 # P9_29
MISO_1 = pin.SPI1_D1 # P9_30
SCLK_1 = pin.SPI1_SCLK # P9_31
# CircuitPython naming convention for SPI Clock
SCK_1 = SCLK_1 | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/board/beagleboard/beaglebone_black.py | beaglebone_black.py |
from adafruit_blinka.microcontroller.am335x import pin
# initial pins, to mimic bonescript demo
# PocketBeagle
# P1_1 = SYS VIN # VIN_AC
P1_2 = pin.P1_2 # GPIO2_23 - GPIO_87
P1_3 = pin.P1_3 # USB1_VBUS_OUT - (silkscreen: USB1 V_EN)
P1_4 = pin.P1_4 # GPIO2_25 - GPIO_89
# P1_5 = USB VBUS # USB1_VBUS_IN
P1_6 = pin.P1_6 # SPI0_CS0 - GPIO_5
# P1_7 = USB VIN # VIN-USB
P1_8 = pin.P1_8 # SPI0_SCLK - GPIO_2
# P1_9 = USB1 DN # USB1-DN
P1_10 = pin.P1_10 # SPI0_D0 - GPIO_3
# P1_11 = USB1 DP # USB1-DP
P1_12 = pin.P1_12 # SPI0_D1 - GPIO_4
# P1_13 = USB1 ID # USB1-ID
# P1_14 = SYS 3.3V # VOUT-3.3V
# P1_15 = SYS GND # GND
# P1_16 = SYS GND # GND
# P1_17 = AIN 1.8V REF- # VREFN
# P1_18 = AIN 1.8V REF+ # VREFP
P1_19 = pin.P1_19 # AIN0
P1_20 = pin.P1_20 # GPIO0_20 - GPIO_20
P1_21 = pin.P1_21 # AIN1
# P1_22 = SYS GND # GND
P1_23 = pin.P1_23 # AIN2
# P1_22 = SYS VOUT # VOUT-5V
P1_25 = pin.P1_25 # AIN3
P1_26 = pin.P1_26 # I2C2_SDA - GPIO_12
P1_27 = pin.P1_27 # AIN4
P1_28 = pin.P1_28 # I2C2_SCL - GPIO_13
P1_29 = pin.P1_29 # GPIO3_21 - GPIO_117
P1_30 = pin.P1_30 # UART0_TXD - GPIO_43
P1_31 = pin.P1_31 # GPIO3_18 - GPIO_114
P1_32 = pin.P1_32 # UART0_RXD - GPIO_42
P1_33 = pin.P1_33 # GPIO3_15 - GPIO_111 - EHRPWM0B (ehrpwm.0:1)
P1_34 = pin.P1_34 # GPIO0_26 - GPIO_26
P1_35 = pin.P1_35 # GPIO2_24 - GPIO_88
P1_36 = pin.P1_36 # EHRPWM0A - GPIO_110 - EHRPWM0A (ehrpwm.0:0)
P2_1 = pin.P2_1 # EHRPWM1A - GPIO_50
P2_2 = pin.P2_2 # GPIO1_27 - GPIO_59
P2_3 = pin.P2_3 # GPIO0_23 - GPIO_23
P2_4 = pin.P2_4 # GPIO1_26 - GPIO_58
P2_5 = pin.P2_5 # UART4_RXD - GPIO_30
P2_6 = pin.P2_6 # GPIO1_25 - GPIO_57
P2_7 = pin.P2_7 # UART4_TXD - GPIO_31
P2_8 = pin.P2_8 # GPIO1_28 - GPIO_60
P2_9 = pin.P2_9 # I2C1_SCL - GPIO_15
P2_10 = pin.P2_10 # GPIO1_20 - GPIO_52
P2_11 = pin.P2_11 # I2C1_SDA - GPIO_14
# P2_12 = SYS PWR BTN # POWER_BUTTON
# P2_13 = SYS VOUT # VOUT-5V
# P2_14 = BAT VIN # BAT-VIN
# P2_15 = SYS GND # GND
# P2_16 = BAT TEMP # BAT-TEMP
P2_17 = pin.P2_17 # GPIO2_1 - GPIO_65
P2_18 = pin.P2_18 # GPIO1_15 - GPIO_47
P2_19 = pin.P2_19 # GPIO0_27 - GPIO_27
P2_20 = pin.P2_20 # GPIO2_0 - GPIO_64
# P2_21 = SYS GND # GND
P2_22 = pin.P2_22 # GPIO1_14 - GPIO_46
# P2_23 = SYS 3.3V # VOUT-3.3V
P2_24 = pin.P2_24 # GPIO1_12 - GPIO_44
P2_25 = pin.P2_25 # SPI1_CS0 - GPIO_41
# P2_26 = SYS NRST # RESET#
P2_27 = pin.P2_27 # SPI1_D0 - GPIO_40
P2_28 = pin.P2_28 # GPIO3_20 - GPIO_116
P2_29 = pin.P2_29 # SPI1_SCLK - GPIO_7
P2_30 = pin.P2_30 # GPIO3_17 - GPIO_113
P2_31 = pin.P2_31 # SPI1_CS1 - GPIO_19
P2_32 = pin.P2_32 # GPIO3_16 - GPIO_112
P2_33 = pin.P2_33 # GPIO1_13 - GPIO_45
P2_34 = pin.P2_34 # GPIO3_19 - GPIO_115
P2_35 = pin.P2_35 # GPIO2_22 - GPIO_86
P2_36 = pin.P2_36 # AIN7
# common to all beagles
LED_USR0 = pin.USR0
LED_USR1 = pin.USR1
LED_USR2 = pin.USR2
LED_USR3 = pin.USR3
##########
# Refer to header default pin modes
# https://raw.githubusercontent.com/wiki/beagleboard/pocketbeagle/images/PocketBeagle_pinout.png
# I2C1 pins
SDA_1 = pin.I2C1_SDA # P2_11 data signal
SCL_1 = pin.I2C1_SCL # P2_9 clock signal
# for example compatibility we create a alias
SDA = SDA_1
SCL = SCL_1
# I2C2 pins
SDA_2 = pin.I2C2_SDA # P1_26 data signal
SCL_2 = pin.I2C2_SCL # P1_28 clock signal
# SPI0 pins
CE0 = pin.SPI0_CS0 # P1_6 - enables peripheral device
SCLK = pin.SPI0_SCLK # P1_12 - outputs data to peripheral device
MOSI = pin.SPI0_D1 # P1_10 - receives data from peripheral device
MISO = pin.SPI0_D0 # P1_8 - outputs clock signal
# CircuitPython naming convention for SPI Clock
SCK = SCLK
# SPI1 pins
CE0_1 = pin.SPI1_CS1 # P2_31 - enables peripheral device
SCLK_1 = pin.SPI1_SCLK # P2_25 - outputs data to peripheral device
MOSI_1 = pin.SPI1_D1 # P2_27 - receives data from peripheral device
MISO_1 = pin.SPI1_D0 # P2_29 - outputs clock signal
# CircuitPython naming convention for SPI Clock
SCK_1 = SCLK_1
# UART0
TX_0 = pin.UART0_TXD # P1_30
RX_0 = pin.UART0_RXD # P1_32
# create alias for most of the examples
TX = TX_0
RX = RX_0
# UART2
# pins already in use by SPI0
# TX_2 = pin.UART2_TXD # P1_8
# RX_2 = pin.UART2_RXD # P1_10
# UART4
TX_4 = pin.UART4_TXD # P2_7
RX_4 = pin.UART4_RXD # P2_5 | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/board/beagleboard/beaglebone_pocketbeagle.py | beaglebone_pocketbeagle.py |
"""Pin definitions for the Beaglebone Black."""
from adafruit_blinka.microcontroller.dra74x import pin
# initial pins, to mimic bonescript demo
# BeagleBone Black
# P8_1 = DGND # DGND
# P8_2 = DGND # DGND
P8_3 = pin.P8_3 # GPIO1_6 - GPIO_38
P8_4 = pin.P8_4 # GPIO1_7 - GPIO_39
P8_5 = pin.P8_5 # GPIO1_2 - GPIO_34
P8_6 = pin.P8_6 # GPIO1_3 - GPIO_35
P8_7 = pin.P8_7 # TIMER4 - GPIO_66
P8_8 = pin.P8_8 # TIMER7 - GPIO_67
P8_9 = pin.P8_9 # TIMER5 - GPIO_69
P8_10 = pin.P8_10 # TIMER6 - GPIO_68
P8_11 = pin.P8_11 # GPIO1_13 - GPIO_45
P8_12 = pin.P8_12 # GPIO1_12 - GPIO_44
P8_13 = pin.P8_13 # EHRPWM2B - GPIO_23
P8_14 = pin.P8_14 # GPIO0_26 - GPIO_26
P8_15 = pin.P8_15 # GPIO1_15 - GPIO_47
P8_16 = pin.P8_16 # GPIO1_14 - GPIO_46
P8_17 = pin.P8_17 # GPIO0_27 - GPIO_27
P8_18 = pin.P8_18 # GPIO2_1 - GPIO_65
P8_19 = pin.P8_19 # EHRPWM2A - GPIO_22
P8_20 = pin.P8_20 # GPIO1_31 - GPIO_63
P8_21 = pin.P8_21 # GPIO1_30 - GPIO_62
P8_22 = pin.P8_22 # GPIO1_5 - GPIO_37
P8_23 = pin.P8_23 # GPIO1_4 - GPIO_36
P8_24 = pin.P8_24 # GPIO1_1 - GPIO_33
P8_25 = pin.P8_25 # GPIO1_0 - GPIO_32
P8_26 = pin.P8_26 # GPIO1_29 - GPIO_61
P8_27 = pin.P8_27 # GPIO2_22 - GPIO_86
P8_28 = pin.P8_28 # GPIO2_24 - GPIO_88
P8_29 = pin.P8_29 # GPIO2_23 - GPIO_87
P8_30 = pin.P8_30 # GPIO2_25 - GPIO_89
P8_31 = pin.P8_31 # UART5_CTSN - GPIO_10
P8_32 = pin.P8_32 # UART5_RTSN - GPIO_11
P8_33 = pin.P8_33 # UART4_RTSN - GPIO_9
P8_34 = pin.P8_34 # UART3_RTSN - GPIO_81
P8_35 = pin.P8_35 # UART4_CTSN - GPIO_8
P8_36 = pin.P8_36 # UART3_CTSN - GPIO_80
P8_37 = pin.P8_37 # UART5_TXD - GPIO_78
P8_38 = pin.P8_38 # UART5_RXD - GPIO_79
P8_39 = pin.P8_39 # GPIO2_12 - GPIO_76
P8_40 = pin.P8_40 # GPIO2_13 - GPIO_77
P8_41 = pin.P8_41 # GPIO2_10 - GPIO_74
P8_42 = pin.P8_42 # GPIO2_11 - GPIO_75
P8_43 = pin.P8_43 # GPIO2_8 - GPIO_72
P8_44 = pin.P8_44 # GPIO2_9 - GPIO_73
P8_45 = pin.P8_45 # GPIO2_6 - GPIO_70
P8_46 = pin.P8_46 # GPIO2_7 - GPIO_71
# P9_1 = DGND # DGND
# P9_2 = DGND # DGND
# P9_3 = VDD_3V3 # VDD_3V3
# P9_4 = VDD_3V3 # VDD_3V3
# P9_5 = VDD_5V # VDD_5V
# P9_6 = VDD_5V # VDD_5V
# P9_7 = SYS_5V # SYS_5V
# P9_8 = SYS_5V # SYS_5V
# P9_9 = PWR_BUT # PWR_BUT
# P9_10 = SYS_RESETN # SYS_RESETn
P9_11 = pin.P9_11 # UART4_RXD - GPIO_30
P9_12 = pin.P9_12 # GPIO1_28 - GPIO_60
P9_13 = pin.P9_13 # UART4_TXD - GPIO_31
P9_14 = pin.P9_14 # EHRPWM1A - GPIO_50
P9_15 = pin.P9_15 # GPIO1_16 - GPIO_48
P9_16 = pin.P9_16 # EHRPWM1B - GPIO_51
P9_17 = pin.P9_17 # I2C1_SCL - GPIO_5
P9_18 = pin.P9_18 # I2C1_SDA - GPIO_4
P9_19 = pin.P9_19 # I2C2_SCL - GPIO_13
P9_20 = pin.P9_20 # I2C2_SDA - GPIO_12
P9_21 = pin.P9_21 # UART2_TXD - GPIO_3
P9_22 = pin.P9_22 # UART2_RXD - GPIO_2
P9_23 = pin.P9_23 # GPIO1_17 - GPIO_49
P9_24 = pin.P9_24 # UART1_TXD - GPIO_15
P9_25 = pin.P9_25 # GPIO3_21 - GPIO_117
P9_26 = pin.P9_26 # UART1_RXD - GPIO_14
P9_27 = pin.P9_27 # GPIO3_19 - GPIO_115
P9_28 = pin.P9_28 # SPI1_CS0 - GPIO_113
P9_29 = pin.P9_29 # SPI1_D0 - GPIO_111
P9_30 = pin.P9_30 # SPI1_D1 - GPIO_112
P9_31 = pin.P9_31 # SPI1_SCLK - GPIO_110
# P9_32 = VDD_ADC # VDD_ADC
# P9_33 = AIN4 # AIN4
# P9_34 = GNDA_ADC # GNDA_ADC
# P9_35 = AIN6 # AIN6
# P9_36 = AIN5 # AIN5
# P9_37 = AIN2 # AIN2
# P9_38 = AIN3 # AIN3
# P9_39 = AIN0 # AIN0
# P9_40 = AIN1 # AIN1
P9_41 = pin.P9_41 # CLKOUT2 - GPIO_20
P9_42 = pin.P9_42 # GPIO0_7 - GPIO_7
# P9_43 = DGND # DGND
# P9_44 = DGND # DGND
# P9_45 = DGND # DGND
# P9_46 = DGND # DGND
# common to all beagles
LED_USR0 = pin.USR0
LED_USR1 = pin.USR1
LED_USR2 = pin.USR2
LED_USR3 = pin.USR3
LED_USR4 = pin.USR4
# I2C and SPI pins from:
# src/adafruit_blinka/board/raspi_40pin.py
# SDA = pin.SDA
# SCL = pin.SCL
# CE1 = pin.D7
# CE0 = pin.D8
# MISO = pin.D9
# MOSI = pin.D10
# SCLK = pin.D11
# SCK = pin.D11
# TXD = pin.D14
# RXD = pin.D15
# MISO_1 = pin.D19
# MOSI_1 = pin.D20
# SCLK_1 = pin.D21
# SCK_1 = pin.D21
SDA = pin.I2C4_SDA # P9_19
SCL = pin.I2C4_SCL # P9_20
# Pins for SPI
#
# To enable SPI and an additional I2C port, add the following line to /boot/uEnv.txt:
# dtb=am5729-beagleboneai-roboticscape.dtb
#
# You can verify the dtb file exists by checking the /boot/dtbs/{kernel_version}/ folder
#
CE0 = pin.SPI1_CS0 # P9_28
CE1 = pin.SPI1_CS1 # P9_42
MOSI = pin.SPI1_D1 # P9_29
MISO = pin.SPI1_D0 # P9_30
SCLK = pin.SPI1_SCLK # P9_31
# CircuitPython naming convention for SPI Clock
SCK = SCLK | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/board/beagleboard/beaglebone_ai.py | beaglebone_ai.py |
"""Pin definitions for the Khadas VIM3."""
from adafruit_blinka.microcontroller.amlogic.a311d import pin
GPIOAO_0 = pin.GPIO496
GPIOAO_1 = pin.GPIO497
GPIOAO_2 = pin.GPIO498
GPIOAO_3 = pin.GPIO499
GPIOAO_4 = pin.GPIO500
GPIOAO_5 = pin.GPIO501
GPIOAO_6 = pin.GPIO502
GPIOAO_7 = pin.GPIO503
GPIOAO_8 = pin.GPIO504
GPIOAO_9 = pin.GPIO505
GPIOAO_10 = pin.GPIO506
GPIOAO_11 = pin.GPIO507
GPIOE_0 = pin.GPIO508
GPIOE_1 = pin.GPIO509
GPIOE_2 = pin.GPIO510
GPIOZ_0 = pin.GPIO427
GPIOZ_1 = pin.GPIO428
GPIOZ_2 = pin.GPIO429
GPIOZ_3 = pin.GPIO430
GPIOZ_4 = pin.GPIO431
GPIOZ_5 = pin.GPIO432
GPIOZ_6 = pin.GPIO433
GPIOZ_7 = pin.GPIO434
GPIOZ_8 = pin.GPIO435
GPIOZ_9 = pin.GPIO436
GPIOZ_10 = pin.GPIO437
GPIOZ_11 = pin.GPIO438
GPIOZ_12 = pin.GPIO439
GPIOZ_13 = pin.GPIO440
GPIOZ_14 = pin.GPIO441
GPIOZ_15 = pin.GPIO442
GPIOH_0 = pin.GPIO443
GPIOH_1 = pin.GPIO444
GPIOH_2 = pin.GPIO445
GPIOH_3 = pin.GPIO446
GPIOH_4 = pin.GPIO447
GPIOH_5 = pin.GPIO448
GPIOH_6 = pin.GPIO449
GPIOH_7 = pin.GPIO450
GPIOH_8 = pin.GPIO451
BOOT_0 = pin.GPIO452
BOOT_1 = pin.GPIO453
BOOT_2 = pin.GPIO454
BOOT_3 = pin.GPIO455
BOOT_4 = pin.GPIO456
BOOT_5 = pin.GPIO457
BOOT_6 = pin.GPIO458
BOOT_7 = pin.GPIO459
BOOT_8 = pin.GPIO460
BOOT_9 = pin.GPIO461
BOOT_10 = pin.GPIO462
BOOT_11 = pin.GPIO463
BOOT_12 = pin.GPIO464
BOOT_13 = pin.GPIO465
BOOT_14 = pin.GPIO466
BOOT_15 = pin.GPIO467
GPIOC_0 = pin.GPIO468
GPIOC_1 = pin.GPIO469
GPIOC_2 = pin.GPIO470
GPIOC_3 = pin.GPIO471
GPIOC_4 = pin.GPIO472
GPIOC_5 = pin.GPIO473
GPIOC_6 = pin.GPIO474
GPIOC_7 = pin.GPIO475
GPIOA_0 = pin.GPIO460
GPIOA_1 = pin.GPIO461
GPIOA_2 = pin.GPIO462
GPIOA_3 = pin.GPIO463
GPIOA_4 = pin.GPIO464
GPIOA_5 = pin.GPIO465
GPIOA_6 = pin.GPIO466
GPIOA_7 = pin.GPIO467
GPIOA_8 = pin.GPIO468
GPIOA_9 = pin.GPIO469
GPIOA_10 = pin.GPIO470
GPIOA_11 = pin.GPIO471
GPIOA_12 = pin.GPIO472
GPIOA_13 = pin.GPIO473
GPIOA_14 = pin.GPIO474
GPIOA_15 = pin.GPIO475
GPIOX_0 = pin.GPIO476
GPIOX_1 = pin.GPIO477
GPIOX_2 = pin.GPIO478
GPIOX_3 = pin.GPIO479
GPIOX_4 = pin.GPIO480
GPIOX_5 = pin.GPIO481
GPIOX_6 = pin.GPIO482
GPIOX_7 = pin.GPIO483
GPIOX_8 = pin.GPIO484
GPIOX_9 = pin.GPIO485
GPIOX_10 = pin.GPIO486
GPIOX_11 = pin.GPIO487
GPIOX_12 = pin.GPIO488
GPIOX_13 = pin.GPIO489
GPIOX_14 = pin.GPIO490
GPIOX_15 = pin.GPIO491
GPIOX_16 = pin.GPIO492
GPIOX_17 = pin.GPIO493
GPIOX_18 = pin.GPIO494
GPIOX_19 = pin.GPIO495
SCL = pin.GPIOX_18
SDA = pin.GPIOX_17
SCLK = pin.SPI0_SCLK
MCLK0 = pin.SPI0_MCLK0
MISO = pin.SPI0_SDO
MOSI = pin.SPI0_SDI
D0 = GPIOAO_10 # PIN_13
D1 = GPIOH_6 # PIN_15
D2 = GPIOH_7 # PIN_16
D3 = GPIOAO_1 # PIN_18
D4 = GPIOAO_2 # PIN_19
D5 = GPIOA_15 # PIN_22
D6 = GPIOA_14 # PIN_23
D7 = GPIOAO_2 # PIN_25
D8 = GPIOAO_3 # PIN_26
D9 = GPIOA_1 # PIN_29
D10 = GPIOA_0 # PIN_30
D11 = GPIOA_3 # PIN_31
D12 = GPIOA_2 # PIN_32
D13 = GPIOA_4 # PIN_33
D14 = GPIOH_5 # PIN_35
D15 = GPIOH_4 # PIN_37
D16 = GPIOZ_15 # PIN_39 | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/board/khadas/khadasvim3.py | khadasvim3.py |
"""Pin definitions for the Octavo OSD32MP1 BRK board."""
# See: https://octavosystems.com/octavosystems.com/wp-content/uploads/2020/05/Default-Pin-Mapping.pdf # pylint: disable=line-too-long
from adafruit_blinka.microcontroller.stm32.stm32mp157 import pin
# Board pin name = OSD32MP1 pin name = STM32MP1 pin name
# fmt: off
# --------------------------------
# Header Location A
# --------------------------------
# VIN - VIN A01
ADC_IN0 = ANA0 = pin.PAN0 # A02
TIM8_CH2 = PI6 = pin.PI6 # A03
GPIO_PI5 = PI5 = pin.PI5 # A04
SPI2_NSS = PI0 = pin.PI0 # A05
SPI2_SCK = PI1 = pin.PI1 # A06
FDCAN1_RX = PH14 = pin.PH14 # A07
FDCAN1_TX = PH13 = pin.PH13 # A08
I2C1_SCL = PH11 = pin.PH11 # A09
TIM12_CH2 = PH9 = pin.PH9 # A10
SPI4_MOSI = PE14 = pin.PE14 # A11
SPI4_NSS = PE11 = pin.PE11 # A12
GPIO_PH8 = PH8 = pin.PH8 # A13
GPIO_PD10 = PD10 = pin.PD10 # A14
GPIO_PH5 = PH5 = pin.PH5 # A15
USART2_RX = PF4 = pin.PF4 # A16
USART2_TX = PF5 = pin.PF5 # A17
I2C2_SCL = PF1 = pin.PF1 # A18
I2C2_SDA = PG15 = pin.PG15 # A19
GPIO_PD4 = PD4 = pin.PD4 # A20
GPIO_PD6 = PD6 = pin.PD6 # A21
I2C5_SDA = PD0 = pin.PD0 # A22
TIM4_CH2 = PB7 = pin.PB7 # A23
GPIO_PE3 = PE3 = pin.PE3 # A24
GPIO_PB15 = PB15 = pin.PB15 # A25
UART7_RX = PB3 = pin.PB3 # A26
GPIO_PE5 = PE5 = pin.PE5 # A27
GPIO_PB14 = PB14 = pin.PE14 # A28
# GND - VSS A29
# GND - VSS A30
# --------------------------------
# Header Location B
# --------------------------------
# VIN - VIN B01
ADC_IN1 = ANA1 = pin.PAN1 # B02
GPIO_PI7 = PI7 = pin.PI7 # B03
GPIO_PI4 = PI4 = pin.PI4 # B04
SPI2_MOSI = PI3 = pin.PI3 # B05
SPI2_MISO = PI2 = pin.PI2 # B06
GPIO_PH15 = PH15 = pin.PH15 # B07
I2C1_SDA = PH12 = pin.PH12 # B08
GPIO_PH10 = PH10 = pin.PH10 # B09
GPIO_PE15 = PE15 = pin.PE15 # B10
SPI4_SCK = PE12 = pin.PE12 # B11
GPIO_PH4 = PH4 = pin.PH4 # B12
SPI4_MISO = PE13 = pin.PE13 # B13
UART8_RX = PE0 = pin.PE0 # B14
UART8_TX = PE1 = pin.PE1 # B15
GPIO_PF0 = PF0 = pin.PF0 # B16
GPIO_PE6 = PE6 = pin.PE6 # B17
GPIO_PD7 = PD7 = pin.PD7 # B18
GPIO_PD5 = PD5 = pin.PD5 # B19
I2C5_SCL = PD1 = pin.PD1 # B20
GPIO_PD3 = PD3 = pin.PD3 # B21
TIM1_CH2 = PA9 = pin.PA9 # B22
GPIO_PB9 = PB9 = pin.PB9 # B23
GPIO_PB8 = PB8 = pin.PB8 # B24
GPIO_PB4 = PB4 = pin.PB4 # B25
GPIO_PG6 = PG6 = pin.PG6 # B26
UART7_TX = PA15 = pin.PA15 # B27
GPIO_PC7 = PC7 = pin.PC7 # B28
# USB1_DP - USB_DP1 B29
# USB1_DN - USB_DM1 B30
# --------------------------------
# Header Location C
# --------------------------------
# 3.3V - PMIC_V4OUT C01
GPIO_PD9 = PD9 = pin.PD9 # C02
GPIO_PD15 = PD15 = pin.PD15 # C03
GPIO_PD14 = PD14 = pin.PD14 # C04
GPIO_PF3 = PF3 = pin.PF3 # C05
GPIO_PC3 = PC3 = pin.PC3 # C06
GPIO_PG13 = PG13 = pin.PG13 # C07
GPIO_PG1 = PG1 = pin.PG1 # C08
GPIO_PG4 = PG4 = pin.PG4 # C09
GPIO_PF14 = PF14 = pin.PF14 # C10
GPIO_PB1 = PB1 = pin.PB1 # C11
SPI6_MISO = PZ1 = pin.PZ1 # C12
SPI6_NSS = PZ3 = pin.PZ3 # C13
# PONKEY - PWC_PONKEY C14
# VLD02 - PMIC_LD02 C15
# VBAT - VBAT C16
# VSW - PMC_SWOUT C17
# VBST - PMIC_BSTOUT C18
GPIO_PC5 = PC5 = pin.PC5 # C19
GPIO_PA1 = PA1 = pin.PA1 # C20
GPIO_PC4 = PC4 = pin.PC4 # C21
GPIO_PB10 = PB10 = pin.PB10 # C22
UART5_RX = PB12 = pin.PB12 # C23
GPIO_PC1 = PC1 = pin.PC1 # C24
GPIO_PA4 = PA4 = pin.PA4 # C25
GPIO_PA6 = PA6 = pin.PA6 # C26
GPIO_PD11 = PD11 = pin.PD11 # C27
GPIO_PF6 = PF6 = pin.PF6 # C28
GPIO_PD12 = PD12 = pin.PD12 # C29
GPIO_PB6 = PB6 = pin.PB6 # C30
# --------------------------------
# Header Location D
# --------------------------------
# 3.V - PMIC_V4OUT D01
# RESETN - NRST D02
GPIO_PD8 = PD8 = pin.PD8 # D03
GPIO_PA14 = PA14 = pin.PA14 # D04
GPIO_PG12 = PG12 = pin.PG12 # D05
GPIO_PA3 = PA3 = pin.PA3 # D06
GPIO_PE2 = PE2 = pin.PE2 # D07
GPIO_PG14 = PG14 = pin.PG14 # D08
GPIO_PG2 = PG2 = pin.PG2 # D09
GPIO_PB11 = PB11 = pin.PB11 # D10
GPIO_PF13 = PF13 = pin.PF13 # D11
SPI6_SCK = PZ0 = pin.PZ0 # D12
SPI6_MOSI = PZ2 = pin.PZ2 # D13
GPIO_PC2 = PC2 = pin.PC2 # D14
GPIO_PG0 = PG0 = pin.PG0 # D15
GPIO_PG3 = PG3 = pin.PG3 # D16
GPIO_PF15 = PF15 = pin.PF15 # D17
GPIO_PF12 = PF12 = pin.PF12 # D18
GPIO_PG5 = PG5 = pin.PG5 # D19
TIM3_CH2 = PB5 = pin.PB5 # D20
GPIO_PB0 = PB0 = pin.PB0 # D21
GPIO_PA7 = PA7 = pin.PA7 # D22
UART5_TX = PB13 = pin.PB13 # D23
GPIO_PA2 = PA2 = pin.PA2 # D24
GPIO_PA5 = PA5 = pin.PA5 # D25
GPIO_PC0 = PC0 = pin.PC0 # D26
GPIO_PF11 = PF11 = pin.PF11 # D27
GPIO_PD13 = PD13 = pin.PD13 # D28
# GND - VSS D29
# GND - VSS D30
# fmt: on
# I2C defaults
SDA1 = SDA = I2C1_SDA
SCL1 = SCL = I2C1_SCL
SDA2 = I2C2_SDA
SCL2 = I2C2_SCL
SDA5 = I2C5_SDA
SCL5 = I2C5_SCL
# SPI defaults
SCK = SPI2_SCK
MOSI = SPI2_MOSI
MISO = SPI2_MISO
CS = SPI2_NSS
# Board LED's
LED1_RED = pin.PZ6
LED1_GRN = pin.PZ7
LED2_RED = pin.PI8
LED2_GRN = pin.PI9
# Console UART
UART4_TX = pin.PG11
UART4_RX = pin.PB2 | Adafruit-Blinka | /Adafruit_Blinka-8.20.1-py3-none-any.whl/adafruit_blinka/board/stm32/osd32mp1_brk.py | osd32mp1_brk.py |
# Adafruit Python BluefruitLE
Python library to simplify access to Bluefruit LE (Bluetooth low energy) devices and services on Linux and Mac OSX. Hides all the platform-specific BLE code (using BlueZ on Linux and CoreBluetooth on Mac OSX) and provides a simpler syncronous BLE API which is great for scripts and other automated tasks using BLE. For example you can create a program to read and write data (like sensor readings) with a Bluefruit LE device in UART mode.
See more details from the guide here: https://learn.adafruit.com/bluefruit-le-python-library/overview
Note this library provides a Python wrapper for BLE **Central Mode**, meaning it can initiate connections and data exchanges with other BLE Peripherals. It does not allow you to emulate a BLE Peripheral via Python, or provide Python-based access to BLE peripherals connected to your system.
**Be aware that this library is early in development!** The examples show how to detect and interact with BLE UART devices which are the primary target of the library. More advanced features like getting advertisement data or interacting with other BLE services might not work or be currently supported. In particular BLE support for desktop operating systems is still somewhat buggy and spotty with support. The library has been developed and primarily tested on Python 2.7.x, but if there are issues with Python 3 please raise them so support can be added.
## Supported Platforms
The library supports the following platforms:
* Linux, using the latest BlueZ 5.33 release. The library is implemented using BlueZ's experimental DBus bindings for access from languages such as Python.
* Mac OSX, using Apple's CoreBluetooth library. The library depends on PyObjC which Apple includes with their Python version on OSX. Note that if you're using a different Python, like the one provided by Homebrew, be sure to [install PyObjC for that version of Python](http://pythonhosted.org/pyobjc/).
### What about Windows support?
The library currently does not support Windows since BLE support is limited on that platform. Windows 7 does not support BLE at all. Windows 8 does not have [BLE device search and pairing APIs](http://stackoverflow.com/questions/19959261/how-to-scan-for-bluetooth-low-energy-devices-in-windows-8-desktop).
Windows 10 appears to have a more capable BLE API but it has not yet been invesigated to see if it can be supported by this library yet.
## Linux & Raspberry Pi Requirements
On Linux (like with a Raspberry Pi) you'll need to compile and install the latest version of BlueZ, currently version 5.33,
to gain access to the Bluetooth LE API it exposes. It's important to use this more recent version of BlueZ as the BLE APIs are still in development and a bit experimental.
**Warning:** Be careful compiling and installing a later version of BlueZ on top of an existing version if you use
a Linux desktop OS like Ubuntu, Debian, etc. You might cause an issue with the new BlueZ version conflicting with
the distribution's older BlueZ installation and wreaking havoc with package dependencies. Ubuntu in particular
can get into a very bad state since core components depend on BlueZ. Look for a properly packaged BlueZ 5.33
release for your distribution, or install into a virtual machine that can protect your desktop machine from conflicts.
The steps below describe how to install BlueZ 5.33 on a Raspberry Pi running its Raspbian operating system. In a terminal on the Raspberry Pi run:
```
sudo apt-get update
sudo apt-get -y install libusb-dev libdbus-1-dev libglib2.0-dev libudev-dev libical-dev libreadline-dev
wget http://www.kernel.org/pub/linux/bluetooth/bluez-5.33.tar.gz
tar xvfz bluez-5.33.tar.gz
cd bluez-5.33
./configure --disable-systemd
make
sudo make install
sudo cp ./src/bluetoothd /usr/local/bin/
```
Finally you'll need to make sure the bluetoothd daemon runs at boot and is run with the `--experimental` flag to enable all the BLE APIs. To do this edit the `/etc/rc.local` file and add the following line before the `exit 0` at the end:
```
/usr/local/bin/bluetoothd --experimental &
```
Save the changed file and reboot the Pi. Then verify using the command `ps aux | grep bluetoothd` that the bluetoothd daemon is running.
## Mac OSX Requirements
On Mac OSX you do not need to install any dependencies to start using the library (the PyObjC library should be
installed already by Apple).
## Installation
Once the requirements above have been met the library can be installed by running the following command inside its root directory:
```
sudo python setup.py install
```
This will install the library so it can be used by any script on your system.
Alternatively you can run `sudo python setup.py develop` to have the library installed in develop mode where changes to the code (like doing a `git pull`) will immediately take effect without a reinstall.
After the library is installed examine the examples folder to see some examples of usage:
* **list_uarts.py** - This example will print out any BLE UART devices that can be found and is a simple example of searching for devices.
* **uart_service.py** - This example will connect to the first BLE UART device it finds, send the string 'Hello World!' and then wait 60 seconds to receive a reply back. The example uses a simple syncronous BLE UART service implementation to send and receive data with the UART device.
* **device_info.py** - This example will connect to the first BLE UART device it finds and print out details from its device info service. **Note this example only works on Mac OSX!** Unfortunately a bug / design issue in the current BlueZ API prevents access to the device information service.
* **low_level.py** - This is a lower-level example that interacts with the services and characteristics of a BLE device directly. Just like the uart_service.py example this will connect to the first found UART device, send a string, and then print out messages that are received for one minute.
To run an example be sure to run as the root user on Linux using sudo, for example to run the uart_service.py example:
```
sudo python uart_service.py
```
On Mac OSX the sudo prefix to run as root is not necessary.
| Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/README.md | README.md |
import abc
import time
from ..config import TIMEOUT_SEC
class Provider(object):
"""Base class for a BLE provider."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def initialize(self):
"""Initialize the BLE provider. Must be called once before any other
calls are made to the provider.
"""
raise NotImplementedError
@abc.abstractmethod
def run_mainloop_with(self, target):
"""Start the OS's main loop to process asyncronous BLE events and then
run the specified target function in a background thread. Target
function should be a function that takes no parameters and optionally
return an integer response code. When the target function stops
executing or returns with value then the main loop will be stopped and
the program will exit with the returned code.
Note that an OS main loop is required to process asyncronous BLE events
and this function is provided as a convenience for writing simple tools
and scripts that don't need to be full-blown GUI applications. If you
are writing a GUI application that has a main loop (a GTK glib main loop
on Linux, or a Cocoa main loop on OSX) then you don't need to call this
function.
"""
raise NotImplementedError
@abc.abstractmethod
def list_adapters(self):
"""Return a list of BLE adapter objects connected to the system."""
raise NotImplementedError
@abc.abstractmethod
def list_devices(self):
"""Return a list of BLE devices known to the system."""
raise NotImplementedError
@abc.abstractmethod
def clear_cached_data(self):
"""Clear any internally cached BLE device data. Necessary in some cases
to prevent issues with stale device data getting cached by the OS.
"""
raise NotImplementedError
@abc.abstractmethod
def disconnect_devices(self, service_uuids):
"""Disconnect any connected devices that have any of the specified
service UUIDs.
"""
raise NotImplementedError
def get_default_adapter(self):
"""Return the first BLE adapter found, or None if no adapters are
available.
"""
adapters = self.list_adapters()
if len(adapters) > 0:
return adapters[0]
else:
return None
def find_devices(self, service_uuids=[], name=None):
"""Return devices that advertise the specified service UUIDs and/or have
the specified name. Service_uuids should be a list of Python uuid.UUID
objects and is optional. Name is a string device name to look for and is
also optional. Will not block, instead it returns immediately with a
list of found devices (which might be empty).
"""
# Convert service UUID list to counter for quicker comparison.
expected = set(service_uuids)
# Grab all the devices.
devices = self.list_devices()
# Filter to just the devices that have the requested service UUID/name.
found = []
for device in devices:
if name is not None:
if device.name == name:
# Check if the name matches and add the device.
found.append(device)
else:
# Check if the advertised UUIDs have at least the expected UUIDs.
actual = set(device.advertised)
if actual >= expected:
found.append(device)
return found
def find_device(self, service_uuids=[], name=None, timeout_sec=TIMEOUT_SEC):
"""Return the first device that advertises the specified service UUIDs or
has the specified name. Will wait up to timeout_sec seconds for the device
to be found, and if the timeout is zero then it will not wait at all and
immediately return a result. When no device is found a value of None is
returned.
"""
start = time.time()
while True:
# Call find_devices and grab the first result if any are found.
found = self.find_devices(service_uuids, name)
if len(found) > 0:
return found[0]
# No device was found. Check if the timeout is exceeded and wait to
# try again.
if time.time()-start >= timeout_sec:
# Failed to find a device within the timeout.
return None
time.sleep(1) | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/interfaces/provider.py | provider.py |
import abc
class Device(object):
"""Base class for a BLE device."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def connect(self, timeout_sec):
"""Connect to the BLE device."""
raise NotImplementedError
@abc.abstractmethod
def disconnect(self, timeout_sec):
"""Disconnect from the BLE device."""
raise NotImplementedError
@abc.abstractmethod
def list_services(self):
"""Return a list of GattService objects that have been discovered for
this device.
"""
raise NotImplementedError
@abc.abstractproperty
def discover(self, service_uuids, char_uuids, timeout_sec=30):
"""Wait up to timeout_sec for the specified services and characteristics
to be discovered on the device. If the timeout is exceeded without
discovering the services and characteristics then an exception is thrown.
"""
raise NotImplementedError
@abc.abstractproperty
def advertised(self):
"""Return a list of UUIDs for services that are advertised by this
device.
"""
raise NotImplementedError
@abc.abstractproperty
def id(self):
"""Return a unique identifier for this device. On supported platforms
this will be the MAC address of the device, however on unsupported
platforms (Mac OSX) it will be a unique ID like a UUID.
"""
raise NotImplementedError
@abc.abstractproperty
def name(self):
"""Return the name of this device."""
raise NotImplementedError
@abc.abstractproperty
def is_connected(self):
"""Return True if the device is connected to the system, otherwise False.
"""
raise NotImplementedError
@abc.abstractproperty
def rssi(self):
"""Return the RSSI signal strength in decibels."""
raise NotImplementedError
def find_service(self, uuid):
"""Return the first child service found that has the specified
UUID. Will return None if no service that matches is found.
"""
for service in self.list_services():
if service.uuid == uuid:
return service
return None
def __eq__(self, other):
"""Test if this device is the same as the provided device."""
return self.id == other.id
def __ne__(self, other):
"""Test if this device is not the same as the provided device."""
return self.id != other.id
def __hash__(self):
"""Hash function implementation that allows device instances to be put
inside dictionaries and other containers.
"""
return hash(self.id) | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/interfaces/device.py | device.py |
import abc
class GattService(object):
"""Base class for a BLE GATT service."""
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def uuid(self):
"""Return the UUID of this GATT service."""
raise NotImplementedError
@abc.abstractmethod
def list_characteristics(self):
"""Return list of GATT characteristics that have been discovered for this
service.
"""
raise NotImplementedError
def find_characteristic(self, uuid):
"""Return the first child characteristic found that has the specified
UUID. Will return None if no characteristic that matches is found.
"""
for char in self.list_characteristics():
if char.uuid == uuid:
return char
return None
class GattCharacteristic(object):
"""Base class for a BLE GATT characteristic."""
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def uuid(self):
"""Return the UUID of this GATT characteristic."""
raise NotImplementedError
@abc.abstractmethod
def read_value(self):
"""Read the value of this characteristic."""
raise NotImplementedError
@abc.abstractmethod
def write_value(self, value):
"""Write the specified value to this characteristic."""
raise NotImplementedError
@abc.abstractmethod
def start_notify(self, on_change):
"""Enable notification of changes for this characteristic on the
specified on_change callback. on_change should be a function that takes
one parameter which is the value (as a string of bytes) of the changed
characteristic value.
"""
raise NotImplementedError
@abc.abstractmethod
def stop_notify(self):
"""Disable notification of changes for this characteristic."""
raise NotImplementedError
@abc.abstractmethod
def list_descriptors(self):
"""Return list of GATT descriptors that have been discovered for this
characteristic.
"""
raise NotImplementedError
def find_descriptor(self, uuid):
"""Return the first child descriptor found that has the specified
UUID. Will return None if no descriptor that matches is found.
"""
for desc in self.list_descriptors():
if desc.uuid == uuid:
return desc
return None
class GattDescriptor(object):
"""Base class for a BLE GATT descriptor."""
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def uuid(self):
"""Return the UUID of this GATT descriptor."""
raise NotImplementedError
@abc.abstractmethod
def read_value(self):
"""Read the value of this descriptor."""
raise NotImplementedError | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/interfaces/gatt.py | gatt.py |
from future.utils import raise_
import logging
import os
from past.builtins import map
import sys
import subprocess
import threading
import time
import objc
from PyObjCTools import AppHelper
from ..interfaces import Provider
from ..platform import get_provider
from .metadata import CoreBluetoothMetadata
from .objc_helpers import uuid_to_cbuuid
# Load CoreBluetooth bundle.
objc.loadBundle("CoreBluetooth", globals(),
bundle_path=objc.pathForFramework(u'/System/Library/Frameworks/IOBluetooth.framework/Versions/A/Frameworks/CoreBluetooth.framework'))
logger = logging.getLogger(__name__)
# Convenience functions to allow other classes to read global metadata lists
# associated with each CoreBluetooth type.
def device_list():
return get_provider()._devices
def service_list():
return get_provider()._services
def characteristic_list():
return get_provider()._characteristics
def descriptor_list():
return get_provider()._descriptors
class CentralDelegate(object):
"""Internal class to handle asyncronous BLE events from the operating system.
"""
# Note that this class will be used by multiple threads (the main loop
# thread that will receive async BLE events, and the secondary thread
# that will receive requests from user code) so access to internal state
def centralManagerDidUpdateState_(self, manager):
"""Called when the BLE adapter is powered on and ready to scan/connect
to devices.
"""
logger.debug('centralManagerDidUpdateState called')
# Notify adapter about changed central state.
get_provider()._adapter._state_changed(manager.state())
def centralManager_didDiscoverPeripheral_advertisementData_RSSI_(self, manager, peripheral, data, rssi):
"""Called when the BLE adapter found a device while scanning, or has
new advertisement data for a device.
"""
logger.debug('centralManager_didDiscoverPeripheral_advertisementData_RSSI called')
# Log name of device found while scanning.
#logger.debug('Saw device advertised with name: {0}'.format(peripheral.name()))
# Make sure the device is added to the list of devices and then update
# its advertisement state.
device = device_list().get(peripheral)
if device is None:
device = device_list().add(peripheral, CoreBluetoothDevice(peripheral))
device._update_advertised(data)
def centralManager_didConnectPeripheral_(self, manager, peripheral):
"""Called when a device is connected."""
logger.debug('centralManager_didConnectPeripheral called')
# Setup peripheral delegate and kick off service discovery. For now just
# assume all services need to be discovered.
peripheral.setDelegate_(self)
peripheral.discoverServices_(None)
# Fire connected event for device.
device = device_list().get(peripheral)
if device is not None:
device._set_connected()
def centralManager_didFailToConnectPeripheral_error_(self, manager, peripheral, error):
# Error connecting to devie. Ignored for now since connected event will
# never fire and a timeout will elapse.
logger.debug('centralManager_didFailToConnectPeripheral_error called')
def centralManager_didDisconnectPeripheral_error_(self, manager, peripheral, error):
"""Called when a device is disconnected."""
logger.debug('centralManager_didDisconnectPeripheral called')
# Get the device and remove it from the device list, then fire its
# disconnected event.
device = device_list().get(peripheral)
if device is not None:
# Fire disconnected event and remove device from device list.
device._set_disconnected()
device_list().remove(peripheral)
def peripheral_didDiscoverServices_(self, peripheral, services):
"""Called when services are discovered for a device."""
logger.debug('peripheral_didDiscoverServices called')
# Make sure the discovered services are added to the list of known
# services, and kick off characteristic discovery for each one.
# NOTE: For some reason the services parameter is never set to a good
# value, instead you must query peripheral.services() to enumerate the
# discovered services.
for service in peripheral.services():
if service_list().get(service) is None:
service_list().add(service, CoreBluetoothGattService(service))
# Kick off characteristic discovery for this service. Just discover
# all characteristics for now.
peripheral.discoverCharacteristics_forService_(None, service)
def peripheral_didDiscoverCharacteristicsForService_error_(self, peripheral, service, error):
"""Called when characteristics are discovered for a service."""
logger.debug('peripheral_didDiscoverCharacteristicsForService_error called')
# Stop if there was some kind of error.
if error is not None:
return
# Make sure the discovered characteristics are added to the list of known
# characteristics, and kick off descriptor discovery for each char.
for char in service.characteristics():
# Add to list of known characteristics.
if characteristic_list().get(char) is None:
characteristic_list().add(char, CoreBluetoothGattCharacteristic(char))
# Start descriptor discovery.
peripheral.discoverDescriptorsForCharacteristic_(char)
# Notify the device about the discovered characteristics.
device = device_list().get(peripheral)
if device is not None:
device._characteristics_discovered(service)
def peripheral_didDiscoverDescriptorsForCharacteristic_error_(self, peripheral, characteristic, error):
"""Called when characteristics are discovered for a service."""
logger.debug('peripheral_didDiscoverDescriptorsForCharacteristic_error called')
# Stop if there was some kind of error.
if error is not None:
return
# Make sure the discovered descriptors are added to the list of known
# descriptors.
for desc in characteristic.descriptors():
# Add to list of known descriptors.
if descriptor_list().get(desc) is None:
descriptor_list().add(desc, CoreBluetoothGattDescriptor(desc))
def peripheral_didWriteValueForCharacteristic_error_(self, peripheral, characteristic, error):
# Characteristic write succeeded. Ignored for now.
logger.debug('peripheral_didWriteValueForCharacteristic_error called')
def peripheral_didUpdateNotificationStateForCharacteristic_error_(self, peripheral, characteristic, error):
# Characteristic notification state updated. Ignored for now.
logger.debug('peripheral_didUpdateNotificationStateForCharacteristic_error called')
def peripheral_didUpdateValueForCharacteristic_error_(self, peripheral, characteristic, error):
"""Called when characteristic value was read or updated."""
logger.debug('peripheral_didUpdateValueForCharacteristic_error called')
# Stop if there was some kind of error.
if error is not None:
return
# Notify the device about the updated characteristic value.
device = device_list().get(peripheral)
if device is not None:
device._characteristic_changed(characteristic)
def peripheral_didUpdateValueForDescriptor_error_(self, peripheral, descriptor, error):
"""Called when descriptor value was read or updated."""
logger.debug('peripheral_didUpdateValueForDescriptor_error called')
# Stop if there was some kind of error.
if error is not None:
return
# Notify the device about the updated descriptor value.
device = device_list().get(peripheral)
if device is not None:
device._descriptor_changed(descriptor)
def peripheral_didReadRSSI_error_(self, peripheral, rssi, error):
"""Called when a new RSSI value for the peripheral is available."""
logger.debug('peripheral_didReadRSSI_error called')
# Note this appears to be completely undocumented at the time of this
# writing. Can see more details at:
# http://stackoverflow.com/questions/25952218/ios-8-corebluetooth-deprecated-rssi-methods
# Stop if there was some kind of error.
if error is not None:
return
# Notify the device about the updated RSSI value.
device = device_list().get(peripheral)
if device is not None:
device._rssi_changed(rssi)
class CoreBluetoothProvider(Provider):
"""BLE provider implementation using the CoreBluetooth framework."""
def __init__(self):
# Global state for BLE devices and other metadata.
self._central_delegate = CentralDelegate()
self._central_manager = None
self._user_thread = None
self._adapter = CoreBluetoothAdapter()
# Keep an internal cache of the devices, services, characteristics, and
# descriptors that are known to the system. Extra metadata can be stored
# with each item, like callbacks and events to fire when asyncronous BLE
# events occur.
self._devices = CoreBluetoothMetadata()
self._services = CoreBluetoothMetadata()
self._characteristics = CoreBluetoothMetadata()
self._descriptors = CoreBluetoothMetadata()
def initialize(self):
"""Initialize the BLE provider. Must be called once before any other
calls are made to the provider.
"""
# Setup the central manager and its delegate.
self._central_manager = CBCentralManager.alloc()
self._central_manager.initWithDelegate_queue_options_(self._central_delegate,
None, None)
# Add any connected devices to list of known devices.
def run_mainloop_with(self, target):
"""Start the OS's main loop to process asyncronous BLE events and then
run the specified target function in a background thread. Target
function should be a function that takes no parameters and optionally
return an integer response code. When the target function stops
executing or returns with value then the main loop will be stopped and
the program will exit with the returned code.
Note that an OS main loop is required to process asyncronous BLE events
and this function is provided as a convenience for writing simple tools
and scripts that don't need to be full-blown GUI applications. If you
are writing a GUI application that has a main loop (a GTK glib main loop
on Linux, or a Cocoa main loop on OSX) then you don't need to call this
function.
"""
# Create background thread to run user code.
self._user_thread = threading.Thread(target=self._user_thread_main,
args=(target,))
self._user_thread.daemon = True
self._user_thread.start()
# Run main loop. This call will never return!
try:
AppHelper.runConsoleEventLoop(installInterrupt=True)
except KeyboardInterrupt:
AppHelper.stopEventLoop()
sys.exit(0)
def _user_thread_main(self, target):
"""Main entry point for the thread that will run user's code."""
try:
# Run user's code.
return_code = target()
# Assume good result (0 return code) if none is returned.
if return_code is None:
return_code = 0
# Call exit on the main thread when user code has finished.
AppHelper.callAfter(lambda: sys.exit(return_code))
except Exception as ex:
# Something went wrong. Raise the exception on the main thread to exit.
AppHelper.callAfter(self._raise_error, sys.exc_info())
def _raise_error(self, exec_info):
"""Raise an exception from the provided exception info. Used to cause
the main thread to stop with an error.
"""
# Rethrow exception with its original stack trace following advice from:
# http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html
raise_(exec_info[1], None, exec_info[2])
def list_adapters(self):
"""Return a list of BLE adapter objects connected to the system."""
return [self._adapter]
def list_devices(self):
"""Return a list of BLE devices known to the system."""
return self._devices.list()
def clear_cached_data(self):
"""Clear the internal bluetooth device cache. This is useful if a device
changes its state like name and it can't be detected with the new state
anymore. WARNING: This will delete some files underneath the running user's
~/Library/Preferences/ folder!
See this Stackoverflow question for information on what the function does:
http://stackoverflow.com/questions/20553957/how-can-i-clear-the-corebluetooth-cache-on-macos
"""
# Turn off bluetooth.
if self._adapter.is_powered:
self._adapter.power_off()
# Delete cache files and suppress any stdout/err output.
with open(os.devnull, 'w') as devnull:
subprocess.call('rm ~/Library/Preferences/com.apple.Bluetooth.plist',
shell=True, stdout=devnull, stderr=subprocess.STDOUT)
subprocess.call('rm ~/Library/Preferences/ByHost/com.apple.Bluetooth.*.plist',
shell=True, stdout=devnull, stderr=subprocess.STDOUT)
def disconnect_devices(self, service_uuids):
"""Disconnect any connected devices that have any of the specified
service UUIDs.
"""
# Get list of connected devices with specified services.
cbuuids = map(uuid_to_cbuuid, service_uuids)
for device in self._central_manager.retrieveConnectedPeripheralsWithServices_(cbuuids):
self._central_manager.cancelPeripheralConnection_(device)
# Stop circular references by importing after classes that use these types.
from .adapter import CoreBluetoothAdapter
from .device import CoreBluetoothDevice
from .gatt import CoreBluetoothGattService, CoreBluetoothGattCharacteristic, CoreBluetoothGattDescriptor | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/corebluetooth/provider.py | provider.py |
import threading
class CoreBluetoothMetadata(object):
"""Class that encapsulates access to metadata associated with CoreBluetooth
objects like CBPeripherals (devices), CBCharacteristics, and CBDescriptors.
This is useful for associating extra state that isn't stored with Apple's
classes, like callbacks to call, etc. Think of this class as a dict that
uses a CBDevice, CBPeripheral, etc. as the key and stores any object with
that Objective-C type. Care is taken to make access to the items thread safe
so it can be accessed from multiple threads.
"""
def __init__(self):
# Initialize item dict and create a lock to synchronize access since it
# will be manipulated by the main thread and user thread.
self._metadata = {}
self._lock = threading.Lock()
def list(self):
"""Return list of all metadata objects."""
with self._lock:
return self._metadata.values()
def get(self, cbobject):
"""Retrieve the metadata associated with the specified CoreBluetooth
object.
"""
with self._lock:
return self._metadata.get(cbobject, None)
def get_all(self, cbobjects):
"""Retrieve a list of metadata objects associated with the specified
list of CoreBluetooth objects. If an object cannot be found then an
exception is thrown.
"""
try:
with self._lock:
return [self._metadata[x] for x in cbobjects]
except KeyError:
# Note that if this error gets thrown then the assumption that OSX
# will pass back to callbacks the exact CoreBluetooth objects that
# were used previously is broken! (i.e. the CoreBluetooth objects
# are not stateless)
raise RuntimeError('Failed to find expected metadata for CoreBluetooth object!')
def add(self, cbobject, metadata):
"""Add the specified CoreBluetooth item with the associated metadata if
it doesn't already exist. Returns the newly created or preexisting
metadata item.
"""
with self._lock:
if cbobject not in self._metadata:
self._metadata[cbobject] = metadata
return self._metadata[cbobject]
def remove(self, cbobject):
"""Remove any metadata associated with the provided CoreBluetooth object.
"""
with self._lock:
if cbobject in self._metadata:
del self._metadata[cbobject] | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/corebluetooth/metadata.py | metadata.py |
import logging
import threading
import time
import objc
from ..config import TIMEOUT_SEC
from ..interfaces import Adapter
from ..platform import get_provider
# Load IOBluetooth functions for controlling bluetooth power state.
objc.loadBundleFunctions(
objc.loadBundle("IOBluetooth", globals(), bundle_path=objc.pathForFramework(u'/System/Library/Frameworks/IOBluetooth.framework')),
globals(),
[('IOBluetoothPreferenceGetControllerPowerState', b'oI'),('IOBluetoothPreferenceSetControllerPowerState', b'vI')]
)
logger = logging.getLogger(__name__)
class CoreBluetoothAdapter(Adapter):
"""CoreBluetooth BLE network adapter. Note that CoreBluetooth has no
concept of individual BLE adapters so any instance of this class will just
interact with BLE globally.
"""
def __init__(self):
"""Create an instance of the bluetooth adapter from the provided bluez
DBus object.
"""
self._is_scanning = False
self._powered_on = threading.Event()
self._powered_off = threading.Event()
def _state_changed(self, state):
"""Called when the power state changes."""
logger.debug('Adapter state change: {0}'.format(state))
# Handle when powered on.
if state == 5:
self._powered_off.clear()
self._powered_on.set()
# Handle when powered off.
elif state == 4:
self._powered_on.clear()
self._powered_off.set()
@property
def name(self):
"""Return the name of this BLE network adapter."""
# Mac OSX has no oncept of BLE adapters so just return a fixed value.
return "Default Adapter"
def start_scan(self, timeout_sec=TIMEOUT_SEC):
"""Start scanning for BLE devices."""
get_provider()._central_manager.scanForPeripheralsWithServices_options_(None, None)
self._is_scanning = True
def stop_scan(self, timeout_sec=TIMEOUT_SEC):
"""Stop scanning for BLE devices."""
get_provider()._central_manager.stopScan()
self._is_scanning = False
@property
def is_scanning(self):
"""Return True if the BLE adapter is scanning for devices, otherwise
return False.
"""
return self._is_scanning
def power_on(self, timeout_sec=TIMEOUT_SEC):
"""Power on Bluetooth."""
# Turn on bluetooth and wait for powered on event to be set.
self._powered_on.clear()
IOBluetoothPreferenceSetControllerPowerState(1)
if not self._powered_on.wait(timeout_sec):
raise RuntimeError('Exceeded timeout waiting for adapter to power on!')
def power_off(self, timeout_sec=TIMEOUT_SEC):
"""Power off Bluetooth."""
# Turn off bluetooth.
self._powered_off.clear()
IOBluetoothPreferenceSetControllerPowerState(0)
if not self._powered_off.wait(timeout_sec):
raise RuntimeError('Exceeded timeout waiting for adapter to power off!')
@property
def is_powered(self):
"""Return True if the BLE adapter is powered up, otherwise return False.
"""
return IOBluetoothPreferenceGetControllerPowerState() == 1 | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/corebluetooth/adapter.py | adapter.py |
from past.builtins import map
import threading
from ..config import TIMEOUT_SEC
from ..interfaces import Device
from ..platform import get_provider
from .gatt import CoreBluetoothGattService
from .objc_helpers import cbuuid_to_uuid, nsuuid_to_uuid
from .provider import device_list, service_list, characteristic_list, descriptor_list
class CoreBluetoothDevice(Device):
"""CoreBluetooth BLE device."""
def __init__(self, peripheral):
"""Create an instance of the CoreBluetooth device from the provided
CBPeripheral instance.
"""
self._peripheral = peripheral
self._advertised = []
self._discovered_services = set()
self._char_on_changed = {}
self._rssi = None
# Events to signify when an asyncronous request has finished.
self._connected = threading.Event()
self._disconnected = threading.Event()
self._discovered = threading.Event()
self._rssi_read = threading.Event()
@property
def _central_manager(self):
# Lookup the CBCentralManager, reduces verbosity of calls.
return get_provider()._central_manager
def connect(self, timeout_sec=TIMEOUT_SEC):
"""Connect to the device. If not connected within the specified timeout
then an exception is thrown.
"""
self._central_manager.connectPeripheral_options_(self._peripheral, None)
if not self._connected.wait(timeout_sec):
raise RuntimeError('Failed to connect to device within timeout period!')
def disconnect(self, timeout_sec=TIMEOUT_SEC):
"""Disconnect from the device. If not disconnected within the specified
timeout then an exception is thrown.
"""
# Remove all the services, characteristics, and descriptors from the
# lists of those items. Do this before disconnecting because they wont't
# be accessible afterwards.
for service in self.list_services():
for char in service.list_characteristics():
for desc in char.list_descriptors():
descriptor_list().remove(desc)
characteristic_list().remove(char)
service_list().remove(service)
# Now disconnect.
self._central_manager.cancelPeripheralConnection_(self._peripheral)
if not self._disconnected.wait(timeout_sec):
raise RuntimeError('Failed to disconnect to device within timeout period!')
def _set_connected(self):
"""Set the connected event."""
self._disconnected.clear()
self._connected.set()
def _set_disconnected(self):
"""Set the connected event."""
self._connected.clear()
self._disconnected.set()
def _update_advertised(self, advertised):
"""Called when advertisement data is received."""
# Advertisement data was received, pull out advertised service UUIDs and
# name from advertisement data.
if 'kCBAdvDataServiceUUIDs' in advertised:
self._advertised = self._advertised + map(cbuuid_to_uuid, advertised['kCBAdvDataServiceUUIDs'])
def _characteristics_discovered(self, service):
"""Called when GATT characteristics have been discovered."""
# Characteristics for the specified service were discovered. Update
# set of discovered services and signal when all have been discovered.
self._discovered_services.add(service)
if self._discovered_services >= set(self._peripheral.services()):
# Found all the services characteristics, finally time to fire the
# service discovery complete event.
self._discovered.set()
def _notify_characteristic(self, characteristic, on_change):
"""Call the specified on_change callback when this characteristic
changes.
"""
# Associate the specified on_changed callback with any changes to this
# characteristic.
self._char_on_changed[characteristic] = on_change
def _characteristic_changed(self, characteristic):
"""Called when the specified characteristic has changed its value."""
# Called when a characteristic is changed. Get the on_changed handler
# for this characteristic (if it exists) and call it.
on_changed = self._char_on_changed.get(characteristic, None)
if on_changed is not None:
on_changed(characteristic.value().bytes().tobytes())
# Also tell the characteristic that it has a new value.
# First get the service that is associated with this characteristic.
char = characteristic_list().get(characteristic)
if char is not None:
char._value_read.set()
def _descriptor_changed(self, descriptor):
"""Called when the specified descriptor has changed its value."""
# Tell the descriptor it has a new value to read.
desc = descriptor_list().get(descriptor)
if desc is not None:
desc._value_read.set()
def _rssi_changed(self, rssi):
"""Called when the RSSI signal strength has been read."""
self._rssi = rssi
self._rssi_read.set()
def list_services(self):
"""Return a list of GattService objects that have been discovered for
this device.
"""
return service_list().get_all(self._peripheral.services())
def discover(self, service_uuids, char_uuids, timeout_sec=TIMEOUT_SEC):
"""Wait up to timeout_sec for the specified services and characteristics
to be discovered on the device. If the timeout is exceeded without
discovering the services and characteristics then an exception is thrown.
"""
# Since OSX tells us when all services and characteristics are discovered
# this function can just wait for that full service discovery.
if not self._discovered.wait(timeout_sec):
raise RuntimeError('Failed to discover device services within timeout period!')
@property
def advertised(self):
"""Return a list of UUIDs for services that are advertised by this
device.
"""
return self._advertised
@property
def id(self):
"""Return a unique identifier for this device. On supported platforms
this will be the MAC address of the device, however on unsupported
platforms (Mac OSX) it will be a unique ID like a UUID.
"""
return nsuuid_to_uuid(self._peripheral.identifier())
@property
def name(self):
"""Return the name of this device."""
return self._peripheral.name()
@property
def is_connected(self):
"""Return True if the device is connected to the system, otherwise False.
"""
return self._connected.is_set()
@property
def rssi(self, timeout_sec=TIMEOUT_SEC):
"""Return the RSSI signal strength in decibels."""
# Kick off query to get RSSI, then wait for it to return asyncronously
# when the _rssi_changed() function is called.
self._rssi_read.clear()
self._peripheral.readRSSI()
if not self._rssi_read.wait(timeout_sec):
raise RuntimeError('Exceeded timeout waiting for RSSI value!')
return self._rssi | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/corebluetooth/device.py | device.py |
import threading
import objc
from ..config import TIMEOUT_SEC
from ..interfaces import GattService, GattCharacteristic, GattDescriptor
from .objc_helpers import cbuuid_to_uuid
from .provider import device_list, characteristic_list, descriptor_list
# Load CoreBluetooth bundle.
objc.loadBundle("CoreBluetooth", globals(),
bundle_path=objc.pathForFramework(u'/System/Library/Frameworks/IOBluetooth.framework/Versions/A/Frameworks/CoreBluetooth.framework'))
class CoreBluetoothGattService(GattService):
"""CoreBluetooth GATT service object."""
def __init__(self, service):
"""Create an instance of the GATT service from the provided CoreBluetooth
CBService instance.
"""
self._service = service
@property
def uuid(self):
"""Return the UUID of this GATT service."""
return cbuuid_to_uuid(self._service.UUID())
def list_characteristics(self):
"""Return list of GATT characteristics that have been discovered for this
service.
"""
# Get the CoreBluetoothGattCharacteristic objects cached in the provider
# for this service's characteristics.
return characteristic_list().get_all(self._service.characteristics())
class CoreBluetoothGattCharacteristic(GattCharacteristic):
"""CoreBluetooth GATT characteristic object."""
def __init__(self, characteristic):
"""Create an instance of the GATT characteristic from the provided
CoreBluetooth CBCharacteristic instance.
"""
self._characteristic = characteristic
self._value_read = threading.Event()
@property
def _device(self):
"""Return the parent CoreBluetoothDevice object that owns this
characteristic.
"""
return device_list().get(self._characteristic.service().peripheral())
@property
def uuid(self):
"""Return the UUID of this GATT characteristic."""
return cbuuid_to_uuid(self._characteristic.UUID())
def read_value(self, timeout_sec=TIMEOUT_SEC):
"""Read the value of this characteristic."""
# Kick off a query to read the value of the characteristic, then wait
# for the result to return asyncronously.
self._value_read.clear()
self._device._peripheral.readValueForCharacteristic_(self._characteristic)
if not self._value_read.wait(timeout_sec):
raise RuntimeError('Exceeded timeout waiting to read characteristic value!')
return self._characteristic.value()
def write_value(self, value, write_type=0):
"""Write the specified value to this characteristic."""
data = NSData.dataWithBytes_length_(value, len(value))
self._device._peripheral.writeValue_forCharacteristic_type_(data,
self._characteristic,
write_type)
def start_notify(self, on_change):
"""Enable notification of changes for this characteristic on the
specified on_change callback. on_change should be a function that takes
one parameter which is the value (as a string of bytes) of the changed
characteristic value.
"""
# Tell the device what callback to use for changes to this characteristic.
self._device._notify_characteristic(self._characteristic, on_change)
# Turn on notifications of characteristic changes.
self._device._peripheral.setNotifyValue_forCharacteristic_(True,
self._characteristic)
def stop_notify(self):
"""Disable notification of changes for this characteristic."""
self._device._peripheral.setNotifyValue_forCharacteristic_(False,
self._characteristic)
def list_descriptors(self):
"""Return list of GATT descriptors that have been discovered for this
characteristic.
"""
# Get the CoreBluetoothGattDescriptor objects cached in the provider
# for this characteristics's descriptors.
return descriptor_list().get_all(self._characteristic.descriptors())
class CoreBluetoothGattDescriptor(GattDescriptor):
"""CoreBluetooth GATT descriptor object."""
def __init__(self, descriptor):
"""Create an instance of the GATT descriptor from the provided
CoreBluetooth CBDescriptor value.
"""
self._descriptor = descriptor
self._value_read = threading.Event()
@property
def _device(self):
"""Return the parent CoreBluetoothDevice object that owns this
characteristic.
"""
return device_list().get(self._descriptor.characteristic().service().peripheral())
@property
def uuid(self):
"""Return the UUID of this GATT descriptor."""
return cbuuid_to_uuid(self._descriptor.UUID())
def read_value(self):
"""Read the value of this descriptor."""
pass
# Kick off a query to read the value of the descriptor, then wait
# for the result to return asyncronously.
self._value_read.clear()
self._device._peripheral.readValueForDescriptor(self._descriptor)
if not self._value_read.wait(timeout_sec):
raise RuntimeError('Exceeded timeout waiting to read characteristic value!')
return self._value | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/corebluetooth/gatt.py | gatt.py |
from past.builtins import map
import sys
import threading
import time
import dbus
import dbus.mainloop.glib
from future.utils import raise_
from future.utils import iteritems
from gi.repository import GObject
from ..interfaces import Provider
from .adapter import BluezAdapter
from .adapter import _INTERFACE as _ADAPTER_INTERFACE
from .device import BluezDevice
class BluezProvider(Provider):
"""BLE provider implementation using the bluez DBus interface and GTK main
loop.
"""
def __init__(self):
# Initialize state for DBus bus, bluez root object, and main loop thread
# metadata.
self._bus = None
self._bluez = None
self._mainloop = None
self._gobject_mainloop = None
self._user_thread = None
self._return_code = 0
self._exception = None
def initialize(self):
"""Initialize bluez DBus communication. Must be called before any other
calls are made!
"""
# Ensure GLib's threading is initialized to support python threads, and
# make a default mainloop that all DBus objects will inherit. These
# commands MUST execute before any other DBus commands!
GObject.threads_init()
dbus.mainloop.glib.threads_init()
# Set the default main loop, this also MUST happen before other DBus calls.
self._mainloop = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
# Get the main DBus system bus and root bluez object.
self._bus = dbus.SystemBus()
self._bluez = dbus.Interface(self._bus.get_object('org.bluez', '/'),
'org.freedesktop.DBus.ObjectManager')
def run_mainloop_with(self, target):
"""Start the OS's main loop to process asyncronous BLE events and then
run the specified target function in a background thread. Target
function should be a function that takes no parameters and optionally
return an integer response code. When the target function stops
executing or returns with value then the main loop will be stopped and
the program will exit with the returned code.
Note that an OS main loop is required to process asyncronous BLE events
and this function is provided as a convenience for writing simple tools
and scripts that don't need to be full-blown GUI applications. If you
are writing a GUI application that has a main loop (a GTK glib main loop
on Linux, or a Cocoa main loop on OSX) then you don't need to call this
function.
"""
# Spin up a background thread to run the target code.
self._user_thread = threading.Thread(target=self._user_thread_main, args=(target,))
self._user_thread.daemon = True # Don't let the user thread block exit.
self._user_thread.start()
# Spin up a GLib main loop in the main thread to process async BLE events.
self._gobject_mainloop = GObject.MainLoop()
try:
self._gobject_mainloop.run() # Doesn't return until the mainloop ends.
except KeyboardInterrupt:
self._gobject_mainloop.quit()
sys.exit(0)
# Main loop finished. Check if an exception occured and throw it,
# otherwise return the status code from the user code.
if self._exception is not None:
# Rethrow exception with its original stack trace following advice from:
# http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html
raise_(self._exception[1], None, self._exception[2])
else:
sys.exit(self._return_code)
def _user_thread_main(self, target):
"""Main entry point for the thread that will run user's code."""
try:
# Wait for GLib main loop to start running before starting user code.
while True:
if self._gobject_mainloop is not None and self._gobject_mainloop.is_running():
# Main loop is running, we should be ready to make bluez DBus calls.
break
# Main loop isn't running yet, give time back to other threads.
time.sleep(0)
# Run user's code.
self._return_code = target()
# Assume good result (0 return code) if none is returned.
if self._return_code is None:
self._return_code = 0
# Signal the main loop to exit.
self._gobject_mainloop.quit()
except Exception as ex:
# Something went wrong. Raise the exception on the main thread to
# exit.
self._exception = sys.exc_info()
self._gobject_mainloop.quit()
def clear_cached_data(self):
"""Clear any internally cached BLE device data. Necessary in some cases
to prevent issues with stale device data getting cached by the OS.
"""
# Go through and remove any device that isn't currently connected.
for device in self.list_devices():
# Skip any connected device.
if device.is_connected:
continue
# Remove this device. First get the adapter associated with the device.
adapter = dbus.Interface(self._bus.get_object('org.bluez', device._adapter),
_ADAPTER_INTERFACE)
# Now call RemoveDevice on the adapter to remove the device from
# bluez's DBus hierarchy.
adapter.RemoveDevice(device._device.object_path)
def disconnect_devices(self, service_uuids=[]):
"""Disconnect any connected devices that have the specified list of
service UUIDs. The default is an empty list which means all devices
are disconnected.
"""
service_uuids = set(service_uuids)
for device in self.list_devices():
# Skip devices that aren't connected.
if not device.is_connected:
continue
device_uuids = set(map(lambda x: x.uuid, device.list_services()))
if device_uuids >= service_uuids:
# Found a device that has at least the requested services, now
# disconnect from it.
device.disconnect()
def list_adapters(self):
"""Return a list of BLE adapter objects connected to the system."""
return map(BluezAdapter, self._get_objects('org.bluez.Adapter1'))
def list_devices(self):
"""Return a list of BLE devices known to the system."""
return map(BluezDevice, self._get_objects('org.bluez.Device1'))
def _get_objects(self, interface, parent_path='/org/bluez'):
"""Return a list of all bluez DBus objects that implement the requested
interface name and are under the specified path. The default is to
search devices under the root of all bluez objects.
"""
# Iterate through all the objects in bluez's DBus hierarchy and return
# any that implement the requested interface under the specified path.
parent_path = parent_path.lower()
objects = []
for opath, interfaces in iteritems(self._bluez.GetManagedObjects()):
if interface in interfaces.keys() and opath.lower().startswith(parent_path):
objects.append(self._bus.get_object('org.bluez', opath))
return objects
def _get_objects_by_path(self, paths):
"""Return a list of all bluez DBus objects from the provided list of paths.
"""
return map(lambda x: self._bus.get_object('org.bluez', x), paths)
def _print_tree(self):
"""Print tree of all bluez objects, useful for debugging."""
# This is based on the bluez sample code get-managed-objects.py.
objects = self._bluez.GetManagedObjects()
for path in objects.keys():
print("[ %s ]" % (path))
interfaces = objects[path]
for interface in interfaces.keys():
if interface in ["org.freedesktop.DBus.Introspectable",
"org.freedesktop.DBus.Properties"]:
continue
print(" %s" % (interface))
properties = interfaces[interface]
for key in properties.keys():
print(" %s = %s" % (key, properties[key])) | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/bluez_dbus/provider.py | provider.py |
import threading
import dbus
from ..config import TIMEOUT_SEC
from ..interfaces import Adapter
_INTERFACE = 'org.bluez.Adapter1'
class BluezAdapter(Adapter):
"""Bluez BLE network adapter."""
def __init__(self, dbus_obj):
"""Create an instance of the bluetooth adapter from the provided bluez
DBus object.
"""
self._adapter = dbus.Interface(dbus_obj, _INTERFACE)
self._props = dbus.Interface(dbus_obj, 'org.freedesktop.DBus.Properties')
self._scan_started = threading.Event()
self._scan_stopped = threading.Event()
self._props.connect_to_signal('PropertiesChanged', self._prop_changed)
def _prop_changed(self, iface, changed_props, invalidated_props):
# Handle property changes for the adapter. Note this call happens in
# a separate thread so be careful to make thread safe changes to state!
# Skip any change events not for this adapter interface.
if iface != _INTERFACE:
return
# If scanning starts then fire the scan started event.
if 'Discovering' in changed_props and changed_props['Discovering'] == 1:
self._scan_started.set()
# If scanning stops then fire the scan stopped event.
if 'Discovering' in changed_props and changed_props['Discovering'] == 0:
self._scan_stopped.set()
@property
def name(self):
"""Return the name of this BLE network adapter."""
return self._props.Get(_INTERFACE, 'Name')
def start_scan(self, timeout_sec=TIMEOUT_SEC):
"""Start scanning for BLE devices with this adapter."""
self._scan_started.clear()
self._adapter.StartDiscovery()
if not self._scan_started.wait(timeout_sec):
raise RuntimeError('Exceeded timeout waiting for adapter to start scanning!')
def stop_scan(self, timeout_sec=TIMEOUT_SEC):
"""Stop scanning for BLE devices with this adapter."""
self._scan_stopped.clear()
self._adapter.StopDiscovery()
if not self._scan_stopped.wait(timeout_sec):
raise RuntimeError('Exceeded timeout waiting for adapter to stop scanning!')
@property
def is_scanning(self):
"""Return True if the BLE adapter is scanning for devices, otherwise
return False.
"""
return self._props.Get(_INTERFACE, 'Discovering')
def power_on(self):
"""Power on this BLE adapter."""
return self._props.Set(_INTERFACE, 'Powered', True)
def power_off(self):
"""Power off this BLE adapter."""
return self._props.Set(_INTERFACE, 'Powered', False)
@property
def is_powered(self):
"""Return True if the BLE adapter is powered up, otherwise return False.
"""
return self._props.Get(_INTERFACE, 'Powered') | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/bluez_dbus/adapter.py | adapter.py |
from past.builtins import map
import threading
import time
import uuid
import dbus
from ..config import TIMEOUT_SEC
from ..interfaces import Device
from ..platform import get_provider
from .adapter import _INTERFACE as _ADAPTER_INTERFACE
from .gatt import BluezGattService, BluezGattCharacteristic, _SERVICE_INTERFACE, _CHARACTERISTIC_INTERFACE
_INTERFACE = 'org.bluez.Device1'
class BluezDevice(Device):
"""Bluez BLE device."""
def __init__(self, dbus_obj):
"""Create an instance of the bluetooth device from the provided bluez
DBus object.
"""
self._device = dbus.Interface(dbus_obj, _INTERFACE)
self._props = dbus.Interface(dbus_obj, 'org.freedesktop.DBus.Properties')
self._connected = threading.Event()
self._disconnected = threading.Event()
self._props.connect_to_signal('PropertiesChanged', self._prop_changed)
def _prop_changed(self, iface, changed_props, invalidated_props):
# Handle property changes for the device. Note this call happens in
# a separate thread so be careful to make thread safe changes to state!
# Skip any change events not for this adapter interface.
if iface != _INTERFACE:
return
# If connected then fire the connected event.
if 'Connected' in changed_props and changed_props['Connected'] == 1:
self._connected.set()
# If disconnected then fire the disconnected event.
if 'Connected' in changed_props and changed_props['Connected'] == 0:
self._disconnected.set()
def connect(self, timeout_sec=TIMEOUT_SEC):
"""Connect to the device. If not connected within the specified timeout
then an exception is thrown.
"""
self._connected.clear()
self._device.Connect()
if not self._connected.wait(timeout_sec):
raise RuntimeError('Exceeded timeout waiting to connect to device!')
def disconnect(self, timeout_sec=TIMEOUT_SEC):
"""Disconnect from the device. If not disconnected within the specified
timeout then an exception is thrown.
"""
self._disconnected.clear()
self._device.Disconnect()
if not self._disconnected.wait(timeout_sec):
raise RuntimeError('Exceeded timeout waiting to disconnect from device!')
def list_services(self):
"""Return a list of GattService objects that have been discovered for
this device.
"""
return map(BluezGattService,
get_provider()._get_objects(_SERVICE_INTERFACE,
self._device.object_path))
def discover(self, service_uuids, char_uuids, timeout_sec=TIMEOUT_SEC):
"""Wait up to timeout_sec for the specified services and characteristics
to be discovered on the device. If the timeout is exceeded without
discovering the services and characteristics then an exception is thrown.
"""
# Turn expected values into a counter of each UUID for fast comparison.
expected_services = set(service_uuids)
expected_chars = set(char_uuids)
# Loop trying to find the expected services for the device.
start = time.time()
while True:
# Find actual services discovered for the device.
actual_services = set(self.advertised)
# Find actual characteristics discovered for the device.
chars = map(BluezGattCharacteristic,
get_provider()._get_objects(_CHARACTERISTIC_INTERFACE,
self._device.object_path))
actual_chars = set(map(lambda x: x.uuid, chars))
# Compare actual discovered UUIDs with expected and return true if at
# least the expected UUIDs are available.
if actual_services >= expected_services and actual_chars >= expected_chars:
# Found at least the expected services!
return True
# Couldn't find the devices so check if timeout has expired and try again.
if time.time()-start >= timeout_sec:
return False
time.sleep(1)
@property
def advertised(self):
"""Return a list of UUIDs for services that are advertised by this
device.
"""
uuids = []
# Get UUIDs property but wrap it in a try/except to catch if the property
# doesn't exist as it is optional.
try:
uuids = self._props.Get(_INTERFACE, 'UUIDs')
except dbus.exceptions.DBusException as ex:
# Ignore error if device has no UUIDs property (i.e. might not be
# a BLE device).
if ex.get_dbus_name() != 'org.freedesktop.DBus.Error.InvalidArgs':
raise ex
return [uuid.UUID(str(x)) for x in uuids]
@property
def id(self):
"""Return a unique identifier for this device. On supported platforms
this will be the MAC address of the device, however on unsupported
platforms (Mac OSX) it will be a unique ID like a UUID.
"""
return self._props.Get(_INTERFACE, 'Address')
@property
def name(self):
"""Return the name of this device."""
return self._props.Get(_INTERFACE, 'Name')
@property
def is_connected(self):
"""Return True if the device is connected to the system, otherwise False.
"""
return self._props.Get(_INTERFACE, 'Connected')
@property
def rssi(self):
"""Return the RSSI signal strength in decibels."""
return self._props.Get(_INTERFACE, 'RSSI')
@property
def _adapter(self):
"""Return the DBus path to the adapter that owns this device."""
return self._props.Get(_INTERFACE, 'Adapter') | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/bluez_dbus/device.py | device.py |
from past.builtins import map
import uuid
import dbus
from ..interfaces import GattService, GattCharacteristic, GattDescriptor
from ..platform import get_provider
_SERVICE_INTERFACE = 'org.bluez.GattService1'
_CHARACTERISTIC_INTERFACE = 'org.bluez.GattCharacteristic1'
_DESCRIPTOR_INTERFACE = 'org.bluez.GattDescriptor1'
class BluezGattService(GattService):
"""Bluez GATT service object."""
def __init__(self, dbus_obj):
"""Create an instance of the GATT service from the provided bluez
DBus object.
"""
self._props = dbus.Interface(dbus_obj, 'org.freedesktop.DBus.Properties')
@property
def uuid(self):
"""Return the UUID of this GATT service."""
return uuid.UUID(str(self._props.Get(_SERVICE_INTERFACE, 'UUID')))
def list_characteristics(self):
"""Return list of GATT characteristics that have been discovered for this
service.
"""
paths = self._props.Get(_SERVICE_INTERFACE, 'Characteristics')
return map(BluezGattCharacteristic,
get_provider()._get_objects_by_path(paths))
class BluezGattCharacteristic(GattCharacteristic):
"""Bluez GATT characteristic object."""
def __init__(self, dbus_obj):
"""Create an instance of the GATT characteristic from the provided bluez
DBus object.
"""
self._characteristic = dbus.Interface(dbus_obj, _CHARACTERISTIC_INTERFACE)
self._props = dbus.Interface(dbus_obj, 'org.freedesktop.DBus.Properties')
@property
def uuid(self):
"""Return the UUID of this GATT characteristic."""
return uuid.UUID(str(self._props.Get(_CHARACTERISTIC_INTERFACE, 'UUID')))
def read_value(self):
"""Read the value of this characteristic."""
return self._characteristic.ReadValue()
def write_value(self, value):
"""Write the specified value to this characteristic."""
self._characteristic.WriteValue(value)
def start_notify(self, on_change):
"""Enable notification of changes for this characteristic on the
specified on_change callback. on_change should be a function that takes
one parameter which is the value (as a string of bytes) of the changed
characteristic value.
"""
# Setup a closure to be the first step in handling the on change callback.
# This closure will verify the characteristic is changed and pull out the
# new value to pass to the user's on change callback.
def characteristic_changed(iface, changed_props, invalidated_props):
# Check that this change is for a GATT characteristic and it has a
# new value.
if iface != _CHARACTERISTIC_INTERFACE:
return
if 'Value' not in changed_props:
return
# Send the new value to the on_change callback.
on_change(''.join(map(chr, changed_props['Value'])))
# Hook up the property changed signal to call the closure above.
self._props.connect_to_signal('PropertiesChanged', characteristic_changed)
# Enable notifications for changes on the characteristic.
self._characteristic.StartNotify()
def stop_notify(self):
"""Disable notification of changes for this characteristic."""
self._characteristic.StopNotify()
def list_descriptors(self):
"""Return list of GATT descriptors that have been discovered for this
characteristic.
"""
paths = self._props.Get(_CHARACTERISTIC_INTERFACE, 'Descriptors')
return map(BluezGattDescriptor,
get_provider()._get_objects_by_path(paths))
class BluezGattDescriptor(GattDescriptor):
"""Bluez GATT descriptor object."""
def __init__(self, dbus_obj):
"""Create an instance of the GATT descriptor from the provided bluez
DBus object.
"""
self._descriptor = dbus.Interface(dbus_obj, _DESCRIPTOR_INTERFACE)
self._props = dbus.Interface(dbus_obj, 'org.freedesktop.DBus.Properties')
@property
def uuid(self):
"""Return the UUID of this GATT descriptor."""
return uuid.UUID(str(self._props.Get(_DESCRIPTOR_INTERFACE, 'UUID')))
def read_value(self):
"""Read the value of this descriptor."""
return self._descriptor.ReadValue() | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/bluez_dbus/gatt.py | gatt.py |
import uuid
from .servicebase import ServiceBase
# Define service and characteristic UUIDs. These UUIDs are taken from the spec:
# https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.device_information.xml
DIS_SERVICE_UUID = uuid.UUID('0000180A-0000-1000-8000-00805F9B34FB')
MANUFACTURER_CHAR_UUID = uuid.UUID('00002A29-0000-1000-8000-00805F9B34FB')
MODEL_CHAR_UUID = uuid.UUID('00002A24-0000-1000-8000-00805F9B34FB')
SERIAL_CHAR_UUID = uuid.UUID('00002A25-0000-1000-8000-00805F9B34FB')
HW_REVISION_CHAR_UUID = uuid.UUID('00002A27-0000-1000-8000-00805F9B34FB')
FW_REVISION_CHAR_UUID = uuid.UUID('00002A26-0000-1000-8000-00805F9B34FB')
SW_REVISION_CHAR_UUID = uuid.UUID('00002A28-0000-1000-8000-00805F9B34FB')
SYS_ID_CHAR_UUID = uuid.UUID('00002A23-0000-1000-8000-00805F9B34FB')
REG_CERT_CHAR_UUID = uuid.UUID('00002A2A-0000-1000-8000-00805F9B34FB')
PNP_ID_CHAR_UUID = uuid.UUID('00002A50-0000-1000-8000-00805F9B34FB')
class DeviceInformation(ServiceBase):
"""Bluetooth LE device information service object."""
# Configure expected services and characteristics for the DIS service.
# Since characteristics are optional don't list any as explicit requirements.
# Also most devices don't advertise the DIS service so don't list it as
# required in advertisements.
ADVERTISED = []
SERVICES = [DIS_SERVICE_UUID]
CHARACTERISTICS = []
def __init__(self, device):
"""Initialize device information from provided bluez device."""
# Find the DIS service and characteristics associated with the device.
self._dis = device.find_service(DIS_SERVICE_UUID)
self._manufacturer = self._dis.find_characteristic(MANUFACTURER_CHAR_UUID)
self._model = self._dis.find_characteristic(MODEL_CHAR_UUID)
self._serial = self._dis.find_characteristic(SERIAL_CHAR_UUID)
self._hw_revision = self._dis.find_characteristic(HW_REVISION_CHAR_UUID)
self._sw_revision = self._dis.find_characteristic(SW_REVISION_CHAR_UUID)
self._fw_revision = self._dis.find_characteristic(FW_REVISION_CHAR_UUID)
self._sys_id = self._dis.find_characteristic(SYS_ID_CHAR_UUID)
self._reg_cert = self._dis.find_characteristic(REG_CERT_CHAR_UUID)
self._pnp_id = self._dis.find_characteristic(PNP_ID_CHAR_UUID)
# Expose all the DIS properties as easy to read python object properties.
@property
def manufacturer(self):
if self._manufacturer is not None:
return self._manufacturer.read_value()
return None
@property
def model(self):
if self._model is not None:
return self._model.read_value()
return None
@property
def serial(self):
if self._serial is not None:
return self._serial.read_value()
return None
@property
def hw_revision(self):
if self._hw_revision is not None:
return self._hw_revision.read_value()
return None
@property
def sw_revision(self):
if self._sw_revision is not None:
return self._sw_revision.read_value()
return None
@property
def fw_revision(self):
if self._fw_revision is not None:
return self._fw_revision.read_value()
return None
@property
def system_id(self):
if self._sys_id is not None:
return self._sys_id.read_value()
return None
@property
def regulatory_cert(self):
if self._reg_cert is not None:
return self._reg_cert.read_value()
return None
@property
def pnp_id(self):
if self._pnp_id is not None:
return self._pnp_id.read_value()
return None | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/services/device_information.py | device_information.py |
import queue
import uuid
from .servicebase import ServiceBase
# Define service and characteristic UUIDs.
UART_SERVICE_UUID = uuid.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')
TX_CHAR_UUID = uuid.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E')
RX_CHAR_UUID = uuid.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E')
class UART(ServiceBase):
"""Bluetooth LE UART service object."""
# Configure expected services and characteristics for the UART service.
ADVERTISED = [UART_SERVICE_UUID]
SERVICES = [UART_SERVICE_UUID]
CHARACTERISTICS = [TX_CHAR_UUID, RX_CHAR_UUID]
def __init__(self, device):
"""Initialize UART from provided bluez device."""
# Find the UART service and characteristics associated with the device.
self._uart = device.find_service(UART_SERVICE_UUID)
if self._uart is None:
raise RuntimeError('Failed to find expected UART service!')
self._tx = self._uart.find_characteristic(TX_CHAR_UUID)
self._rx = self._uart.find_characteristic(RX_CHAR_UUID)
if self._tx is None or self._rx is None:
raise RuntimeError('Failed to find expected UART RX and TX characteristics!')
# Use a queue to pass data received from the RX property change back to
# the main thread in a thread-safe way.
self._queue = queue.Queue()
# Subscribe to RX characteristic changes to receive data.
self._rx.start_notify(self._rx_received)
def _rx_received(self, data):
# Callback that's called when data is received on the RX characteristic.
# Just throw the new data in the queue so the read function can access
# it on the main thread.
self._queue.put(data)
def write(self, data):
"""Write a string of data to the UART device."""
self._tx.write_value(data)
def read(self, timeout_sec=None):
"""Block until data is available to read from the UART. Will return a
string of data that has been received. Timeout_sec specifies how many
seconds to wait for data to be available and will block forever if None
(the default). If the timeout is exceeded and no data is found then
None is returned.
"""
try:
return self._queue.get(timeout=timeout_sec)
except queue.Empty:
# Timeout exceeded, return None to signify no data received.
return None | Adafruit-BluefruitLE | /Adafruit_BluefruitLE-0.9.10.tar.gz/Adafruit_BluefruitLE-0.9.10/Adafruit_BluefruitLE/services/uart.py | uart.py |
import time
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.I2C as I2C
import Adafruit_GPIO.MCP230xx as MCP
import Adafruit_GPIO.PWM as PWM
# Commands
LCD_CLEARDISPLAY = 0x01
LCD_RETURNHOME = 0x02
LCD_ENTRYMODESET = 0x04
LCD_DISPLAYCONTROL = 0x08
LCD_CURSORSHIFT = 0x10
LCD_FUNCTIONSET = 0x20
LCD_SETCGRAMADDR = 0x40
LCD_SETDDRAMADDR = 0x80
# Entry flags
LCD_ENTRYRIGHT = 0x00
LCD_ENTRYLEFT = 0x02
LCD_ENTRYSHIFTINCREMENT = 0x01
LCD_ENTRYSHIFTDECREMENT = 0x00
# Control flags
LCD_DISPLAYON = 0x04
LCD_DISPLAYOFF = 0x00
LCD_CURSORON = 0x02
LCD_CURSOROFF = 0x00
LCD_BLINKON = 0x01
LCD_BLINKOFF = 0x00
# Move flags
LCD_DISPLAYMOVE = 0x08
LCD_CURSORMOVE = 0x00
LCD_MOVERIGHT = 0x04
LCD_MOVELEFT = 0x00
# Function set flags
LCD_8BITMODE = 0x10
LCD_4BITMODE = 0x00
LCD_2LINE = 0x08
LCD_1LINE = 0x00
LCD_5x10DOTS = 0x04
LCD_5x8DOTS = 0x00
# Offset for up to 4 rows.
LCD_ROW_OFFSETS = (0x00, 0x40, 0x14, 0x54)
# Char LCD plate GPIO numbers.
LCD_PLATE_RS = 15
LCD_PLATE_RW = 14
LCD_PLATE_EN = 13
LCD_PLATE_D4 = 12
LCD_PLATE_D5 = 11
LCD_PLATE_D6 = 10
LCD_PLATE_D7 = 9
LCD_PLATE_RED = 6
LCD_PLATE_GREEN = 7
LCD_PLATE_BLUE = 8
# Char LCD plate button names.
SELECT = 0
RIGHT = 1
DOWN = 2
UP = 3
LEFT = 4
class Adafruit_CharLCD(object):
"""Class to represent and interact with an HD44780 character LCD display."""
def __init__(self, rs, en, d4, d5, d6, d7, cols, lines, backlight=None,
invert_polarity=True,
enable_pwm=False,
gpio=GPIO.get_platform_gpio(),
pwm=PWM.get_platform_pwm(),
initial_backlight=1.0):
"""Initialize the LCD. RS, EN, and D4...D7 parameters should be the pins
connected to the LCD RS, clock enable, and data line 4 through 7 connections.
The LCD will be used in its 4-bit mode so these 6 lines are the only ones
required to use the LCD. You must also pass in the number of columns and
lines on the LCD.
If you would like to control the backlight, pass in the pin connected to
the backlight with the backlight parameter. The invert_polarity boolean
controls if the backlight is one with a LOW signal or HIGH signal. The
default invert_polarity value is True, i.e. the backlight is on with a
LOW signal.
You can enable PWM of the backlight pin to have finer control on the
brightness. To enable PWM make sure your hardware supports PWM on the
provided backlight pin and set enable_pwm to True (the default is False).
The appropriate PWM library will be used depending on the platform, but
you can provide an explicit one with the pwm parameter.
The initial state of the backlight is ON, but you can set it to an
explicit initial state with the initial_backlight parameter (0 is off,
1 is on/full bright).
You can optionally pass in an explicit GPIO class,
for example if you want to use an MCP230xx GPIO extender. If you don't
pass in an GPIO instance, the default GPIO for the running platform will
be used.
"""
# Save column and line state.
self._cols = cols
self._lines = lines
# Save GPIO state and pin numbers.
self._gpio = gpio
self._rs = rs
self._en = en
self._d4 = d4
self._d5 = d5
self._d6 = d6
self._d7 = d7
# Save backlight state.
self._backlight = backlight
self._pwm_enabled = enable_pwm
self._pwm = pwm
self._blpol = not invert_polarity
# Setup all pins as outputs.
for pin in (rs, en, d4, d5, d6, d7):
gpio.setup(pin, GPIO.OUT)
# Setup backlight.
if backlight is not None:
if enable_pwm:
pwm.start(backlight, self._pwm_duty_cycle(initial_backlight))
else:
gpio.setup(backlight, GPIO.OUT)
gpio.output(backlight, self._blpol if initial_backlight else not self._blpol)
# Initialize the display.
self.write8(0x33)
self.write8(0x32)
# Initialize display control, function, and mode registers.
self.displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF
self.displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_2LINE | LCD_5x8DOTS
self.displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT
# Write registers.
self.write8(LCD_DISPLAYCONTROL | self.displaycontrol)
self.write8(LCD_FUNCTIONSET | self.displayfunction)
self.write8(LCD_ENTRYMODESET | self.displaymode) # set the entry mode
self.clear()
def home(self):
"""Move the cursor back to its home (first line and first column)."""
self.write8(LCD_RETURNHOME) # set cursor position to zero
self._delay_microseconds(3000) # this command takes a long time!
def clear(self):
"""Clear the LCD."""
self.write8(LCD_CLEARDISPLAY) # command to clear display
self._delay_microseconds(3000) # 3000 microsecond sleep, clearing the display takes a long time
def set_cursor(self, col, row):
"""Move the cursor to an explicit column and row position."""
# Clamp row to the last row of the display.
if row > self._lines:
row = self._lines - 1
# Set location.
self.write8(LCD_SETDDRAMADDR | (col + LCD_ROW_OFFSETS[row]))
def enable_display(self, enable):
"""Enable or disable the display. Set enable to True to enable."""
if enable:
self.displaycontrol |= LCD_DISPLAYON
else:
self.displaycontrol &= ~LCD_DISPLAYON
self.write8(LCD_DISPLAYCONTROL | self.displaycontrol)
def show_cursor(self, show):
"""Show or hide the cursor. Cursor is shown if show is True."""
if show:
self.displaycontrol |= LCD_CURSORON
else:
self.displaycontrol &= ~LCD_CURSORON
self.write8(LCD_DISPLAYCONTROL | self.displaycontrol)
def blink(self, blink):
"""Turn on or off cursor blinking. Set blink to True to enable blinking."""
if blink:
self.displaycontrol |= LCD_BLINKON
else:
self.displaycontrol &= ~LCD_BLINKON
self.write8(LCD_DISPLAYCONTROL | self.displaycontrol)
def move_left(self):
"""Move display left one position."""
self.write8(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT)
def move_right(self):
"""Move display right one position."""
self.write8(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT)
def set_left_to_right(self):
"""Set text direction left to right."""
self.displaymode |= LCD_ENTRYLEFT
self.write8(LCD_ENTRYMODESET | self.displaymode)
def set_right_to_left(self):
"""Set text direction right to left."""
self.displaymode &= ~LCD_ENTRYLEFT
self.write8(LCD_ENTRYMODESET | self.displaymode)
def autoscroll(self, autoscroll):
"""Autoscroll will 'right justify' text from the cursor if set True,
otherwise it will 'left justify' the text.
"""
if autoscroll:
self.displaymode |= LCD_ENTRYSHIFTINCREMENT
else:
self.displaymode &= ~LCD_ENTRYSHIFTINCREMENT
self.write8(LCD_ENTRYMODESET | self.displaymode)
def message(self, text):
"""Write text to display. Note that text can include newlines."""
line = 0
# Iterate through each character.
for char in text:
# Advance to next line if character is a new line.
if char == '\n':
line += 1
# Move to left or right side depending on text direction.
col = 0 if self.displaymode & LCD_ENTRYLEFT > 0 else self._cols-1
self.set_cursor(col, line)
# Write the character to the display.
else:
self.write8(ord(char), True)
def set_backlight(self, backlight):
"""Enable or disable the backlight. If PWM is not enabled (default), a
non-zero backlight value will turn on the backlight and a zero value will
turn it off. If PWM is enabled, backlight can be any value from 0.0 to
1.0, with 1.0 being full intensity backlight.
"""
if self._backlight is not None:
if self._pwm_enabled:
self._pwm.set_duty_cycle(self._backlight, self._pwm_duty_cycle(backlight))
else:
self._gpio.output(self._backlight, self._blpol if backlight else not self._blpol)
def write8(self, value, char_mode=False):
"""Write 8-bit value in character or data mode. Value should be an int
value from 0-255, and char_mode is True if character data or False if
non-character data (default).
"""
# One millisecond delay to prevent writing too quickly.
self._delay_microseconds(1000)
# Set character / data bit.
self._gpio.output(self._rs, char_mode)
# Write upper 4 bits.
self._gpio.output_pins({ self._d4: ((value >> 4) & 1) > 0,
self._d5: ((value >> 5) & 1) > 0,
self._d6: ((value >> 6) & 1) > 0,
self._d7: ((value >> 7) & 1) > 0 })
self._pulse_enable()
# Write lower 4 bits.
self._gpio.output_pins({ self._d4: (value & 1) > 0,
self._d5: ((value >> 1) & 1) > 0,
self._d6: ((value >> 2) & 1) > 0,
self._d7: ((value >> 3) & 1) > 0 })
self._pulse_enable()
def create_char(self, location, pattern):
"""Fill one of the first 8 CGRAM locations with custom characters.
The location parameter should be between 0 and 7 and pattern should
provide an array of 8 bytes containing the pattern. E.g. you can easyly
design your custom character at http://www.quinapalus.com/hd44780udg.html
To show your custom character use eg. lcd.message('\x01')
"""
# only position 0..7 are allowed
location &= 0x7
self.write8(LCD_SETCGRAMADDR | (location << 3))
for i in range(8):
self.write8(pattern[i], char_mode=True)
def _delay_microseconds(self, microseconds):
# Busy wait in loop because delays are generally very short (few microseconds).
end = time.time() + (microseconds/1000000.0)
while time.time() < end:
pass
def _pulse_enable(self):
# Pulse the clock enable line off, on, off to send command.
self._gpio.output(self._en, False)
self._delay_microseconds(1) # 1 microsecond pause - enable pulse must be > 450ns
self._gpio.output(self._en, True)
self._delay_microseconds(1) # 1 microsecond pause - enable pulse must be > 450ns
self._gpio.output(self._en, False)
self._delay_microseconds(1) # commands need > 37us to settle
def _pwm_duty_cycle(self, intensity):
# Convert intensity value of 0.0 to 1.0 to a duty cycle of 0.0 to 100.0
intensity = 100.0*intensity
# Invert polarity if required.
if not self._blpol:
intensity = 100.0-intensity
return intensity
class Adafruit_RGBCharLCD(Adafruit_CharLCD):
"""Class to represent and interact with an HD44780 character LCD display with
an RGB backlight."""
def __init__(self, rs, en, d4, d5, d6, d7, cols, lines, red, green, blue,
gpio=GPIO.get_platform_gpio(),
invert_polarity=True,
enable_pwm=False,
pwm=PWM.get_platform_pwm(),
initial_color=(1.0, 1.0, 1.0)):
"""Initialize the LCD with RGB backlight. RS, EN, and D4...D7 parameters
should be the pins connected to the LCD RS, clock enable, and data line
4 through 7 connections. The LCD will be used in its 4-bit mode so these
6 lines are the only ones required to use the LCD. You must also pass in
the number of columns and lines on the LCD.
The red, green, and blue parameters define the pins which are connected
to the appropriate backlight LEDs. The invert_polarity parameter is a
boolean that controls if the LEDs are on with a LOW or HIGH signal. By
default invert_polarity is True, i.e. the backlight LEDs are on with a
low signal. If you want to enable PWM on the backlight LEDs (for finer
control of colors) and the hardware supports PWM on the provided pins,
set enable_pwm to True. Finally you can set an explicit initial backlight
color with the initial_color parameter. The default initial color is
white (all LEDs lit).
You can optionally pass in an explicit GPIO class,
for example if you want to use an MCP230xx GPIO extender. If you don't
pass in an GPIO instance, the default GPIO for the running platform will
be used.
"""
super(Adafruit_RGBCharLCD, self).__init__(rs, en, d4, d5, d6, d7,
cols,
lines,
enable_pwm=enable_pwm,
backlight=None,
invert_polarity=invert_polarity,
gpio=gpio,
pwm=pwm)
self._red = red
self._green = green
self._blue = blue
# Setup backlight pins.
if enable_pwm:
# Determine initial backlight duty cycles.
rdc, gdc, bdc = self._rgb_to_duty_cycle(initial_color)
pwm.start(red, rdc)
pwm.start(green, gdc)
pwm.start(blue, bdc)
else:
gpio.setup(red, GPIO.OUT)
gpio.setup(green, GPIO.OUT)
gpio.setup(blue, GPIO.OUT)
self._gpio.output_pins(self._rgb_to_pins(initial_color))
def _rgb_to_duty_cycle(self, rgb):
# Convert tuple of RGB 0-1 values to tuple of duty cycles (0-100).
red, green, blue = rgb
# Clamp colors between 0.0 and 1.0
red = max(0.0, min(1.0, red))
green = max(0.0, min(1.0, green))
blue = max(0.0, min(1.0, blue))
return (self._pwm_duty_cycle(red),
self._pwm_duty_cycle(green),
self._pwm_duty_cycle(blue))
def _rgb_to_pins(self, rgb):
# Convert tuple of RGB 0-1 values to dict of pin values.
red, green, blue = rgb
return { self._red: self._blpol if red else not self._blpol,
self._green: self._blpol if green else not self._blpol,
self._blue: self._blpol if blue else not self._blpol }
def set_color(self, red, green, blue):
"""Set backlight color to provided red, green, and blue values. If PWM
is enabled then color components can be values from 0.0 to 1.0, otherwise
components should be zero for off and non-zero for on.
"""
if self._pwm_enabled:
# Set duty cycle of PWM pins.
rdc, gdc, bdc = self._rgb_to_duty_cycle((red, green, blue))
self._pwm.set_duty_cycle(self._red, rdc)
self._pwm.set_duty_cycle(self._green, gdc)
self._pwm.set_duty_cycle(self._blue, bdc)
else:
# Set appropriate backlight pins based on polarity and enabled colors.
self._gpio.output_pins({self._red: self._blpol if red else not self._blpol,
self._green: self._blpol if green else not self._blpol,
self._blue: self._blpol if blue else not self._blpol })
def set_backlight(self, backlight):
"""Enable or disable the backlight. If PWM is not enabled (default), a
non-zero backlight value will turn on the backlight and a zero value will
turn it off. If PWM is enabled, backlight can be any value from 0.0 to
1.0, with 1.0 being full intensity backlight. On an RGB display this
function will set the backlight to all white.
"""
self.set_color(backlight, backlight, backlight)
class Adafruit_CharLCDPlate(Adafruit_RGBCharLCD):
"""Class to represent and interact with an Adafruit Raspberry Pi character
LCD plate."""
def __init__(self, address=0x20, busnum=I2C.get_default_bus(), cols=16, lines=2):
"""Initialize the character LCD plate. Can optionally specify a separate
I2C address or bus number, but the defaults should suffice for most needs.
Can also optionally specify the number of columns and lines on the LCD
(default is 16x2).
"""
# Configure MCP23017 device.
self._mcp = MCP.MCP23017(address=address, busnum=busnum)
# Set LCD R/W pin to low for writing only.
self._mcp.setup(LCD_PLATE_RW, GPIO.OUT)
self._mcp.output(LCD_PLATE_RW, GPIO.LOW)
# Set buttons as inputs with pull-ups enabled.
for button in (SELECT, RIGHT, DOWN, UP, LEFT):
self._mcp.setup(button, GPIO.IN)
self._mcp.pullup(button, True)
# Initialize LCD (with no PWM support).
super(Adafruit_CharLCDPlate, self).__init__(LCD_PLATE_RS, LCD_PLATE_EN,
LCD_PLATE_D4, LCD_PLATE_D5, LCD_PLATE_D6, LCD_PLATE_D7, cols, lines,
LCD_PLATE_RED, LCD_PLATE_GREEN, LCD_PLATE_BLUE, enable_pwm=False,
gpio=self._mcp)
def is_pressed(self, button):
"""Return True if the provided button is pressed, False otherwise."""
if button not in set((SELECT, RIGHT, DOWN, UP, LEFT)):
raise ValueError('Unknown button, must be SELECT, RIGHT, DOWN, UP, or LEFT.')
return self._mcp.input(button) == GPIO.LOW | Adafruit-CharLCD | /Adafruit_CharLCD-1.1.1.tar.gz/Adafruit_CharLCD-1.1.1/Adafruit_CharLCD/Adafruit_CharLCD.py | Adafruit_CharLCD.py |
*DEPRECATED LIBRARY* Adafruit Python DHT Sensor Library
=======================
his library has been deprecated! We are leaving this up for historical and research purposes but archiving the repository.
We are now only supporting the use of our CircuitPython libraries for use with Python.
Check out this guide for info on using DHT sensors with the CircuitPython library: https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/python-setup
---------------------------------------
Python library to read the DHT series of humidity and temperature sensors on a
Raspberry Pi or Beaglebone Black.
Designed specifically to work with the Adafruit DHT series sensors ---->
https://www.adafruit.com/products/385
Currently the library is tested with Python 2.6, 2.7, 3.3 and 3.4. It should
work with Python greater than 3.4, too.
Installing
----------
### Dependencies
For all platforms (Raspberry Pi and Beaglebone Black) make sure your system is
able to compile and download Python extensions with **pip**:
On Raspbian or Beaglebone Black's Debian/Ubuntu image you can ensure your
system is ready by running one or two of the following sets of commands:
Python 2:
````sh
sudo apt-get update
sudo apt-get install python-pip
sudo python -m pip install --upgrade pip setuptools wheel
````
Python 3:
````sh
sudo apt-get update
sudo apt-get install python3-pip
sudo python3 -m pip install --upgrade pip setuptools wheel
````
### Install with pip
Use `pip` to install from PyPI.
Python 2:
```sh
sudo pip install Adafruit_DHT
```
Python 3:
```sh
sudo pip3 install Adafruit_DHT
```
### Compile and install from the repository
First download the library source code from the [GitHub releases
page](https://github.com/adafruit/Adafruit_Python_DHT/releases), unzipping the
archive, and execute:
Python 2:
```sh
cd Adafruit_Python_DHT
sudo python setup.py install
```
Python 3:
```sh
cd Adafruit_Python_DHT
sudo python3 setup.py install
```
You may also git clone the repository if you want to test an unreleased
version:
```sh
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
```
Usage
-----
See example of usage in the examples folder.
Author
------
Adafruit invests time and resources providing this open source code, please
support Adafruit and open-source hardware by purchasing products from Adafruit!
Written by Tony DiCola for Adafruit Industries.
MIT license, all text above must be included in any redistribution
| Adafruit-DHT-Fixed | /Adafruit_DHT_Fixed-1.4.2.tar.gz/Adafruit_DHT_Fixed-1.4.2/README.md | README.md |
# 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.
import time
from . import platform_detect
# Define error constants.
DHT_SUCCESS = 0
DHT_ERROR_TIMEOUT = -1
DHT_ERROR_CHECKSUM = -2
DHT_ERROR_ARGUMENT = -3
DHT_ERROR_GPIO = -4
TRANSIENT_ERRORS = [DHT_ERROR_CHECKSUM, DHT_ERROR_TIMEOUT]
# Define sensor type constants.
DHT11 = 11
DHT22 = 22
AM2302 = 22
SENSORS = [DHT11, DHT22, AM2302]
def get_platform():
"""Return a DHT platform interface for the currently detected platform."""
plat = platform_detect.platform_detect()
if plat == platform_detect.RASPBERRY_PI:
# Check for version 1 or 2 of the pi.
version = platform_detect.pi_version()
if version == 1:
from . import Raspberry_Pi
return Raspberry_Pi
elif version == 2:
from . import Raspberry_Pi_2
return Raspberry_Pi_2
elif version == 3:
"""Use Pi 2 driver even though running on Pi 3"""
from . import Raspberry_Pi_2
return Raspberry_Pi_2
else:
raise RuntimeError('No driver for detected Raspberry Pi version available!')
elif plat == platform_detect.BEAGLEBONE_BLACK:
from . import Beaglebone_Black
return Beaglebone_Black
else:
raise RuntimeError('Unknown platform.')
def read(sensor, pin, platform=None):
"""Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius). Note that
because the sensor requires strict timing to read and Linux is not a real
time OS, a result is not guaranteed to be returned! In some cases this will
return the tuple (None, None) which indicates the function should be retried.
Also note the DHT sensor cannot be read faster than about once every 2 seconds.
Platform is an optional parameter which allows you to override the detected
platform interface--ignore this parameter unless you receive unknown platform
errors and want to override the detection.
"""
if sensor not in SENSORS:
raise ValueError('Expected DHT11, DHT22, or AM2302 sensor value.')
if platform is None:
platform = get_platform()
return platform.read(sensor, pin)
def read_retry(sensor, pin, retries=15, delay_seconds=2, platform=None):
"""Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius).
Unlike the read function, this read_retry function will attempt to read
multiple times (up to the specified max retries) until a good reading can be
found. If a good reading cannot be found after the amount of retries, a tuple
of (None, None) is returned. The delay between retries is by default 2
seconds, but can be overridden.
"""
for i in range(retries):
humidity, temperature = read(sensor, pin, platform)
if humidity is not None and temperature is not None:
return (humidity, temperature)
time.sleep(delay_seconds)
return (None, None) | Adafruit-DHT-Fixed | /Adafruit_DHT_Fixed-1.4.2.tar.gz/Adafruit_DHT_Fixed-1.4.2/Adafruit_DHT/common.py | common.py |
# 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.
import re
from . import common
from . import Beaglebone_Black_Driver as driver
# Define mapping of pin names to GPIO base and number.
# Adapted from Adafruit_BBIO code Beaglebone Black system reference.
pin_to_gpio = {
"P9_11": (0,30),
"P9_12": (1,28),
"P9_13": (0,31),
"P9_14": (1,18),
"P9_15": (1,16),
"P9_16": (1,19),
"P9_17": (0,5),
"P9_18": (0,4),
"P9_19": (0,13),
"P9_20": (0,12),
"P9_21": (0,3),
"P9_22": (0,2),
"P9_23": (1,17),
"P9_24": (0,15),
"P9_25": (3,21),
"P9_26": (0,14),
"P9_27": (3,19),
"P9_28": (3,17),
"P9_29": (3,15),
"P9_30": (3,16),
"P9_31": (3,14),
"P9_41": (0,20),
"P9_42": (0,7),
"UART4_RXD": (0,30),
"UART4_TXD": (0,31),
"EHRPWM1A": (1,18),
"EHRPWM1B": (1,19),
"I2C1_SCL": (0,5),
"I2C1_SDA": (0,4),
"I2C2_SCL": (0,13),
"I2C2_SDA": (0,12),
"UART2_TXD": (0,3),
"UART2_RXD": (0,2),
"UART1_TXD": (0,15),
"UART1_RXD": (0,14),
"SPI1_CS0": (3,17),
"SPI1_D0": (3,15),
"SPI1_D1": (3,16),
"SPI1_SCLK": (3,14),
"CLKOUT2": (0,20),
"30": (0,30),
"60": (1,28),
"31": (0,31),
"50": (1,18),
"48": (1,16),
"51": (1,19),
"5": (0,5),
"4": (0,4),
"13": (0,13),
"12": (0,12),
"3": (0,3),
"2": (0,2),
"49": (1,17),
"15": (0,15),
"117": (3,21),
"14": (0,14),
"115": (3,19),
"113": (3,17),
"111": (3,15),
"112": (3,16),
"110": (3,14),
"20": (0,20),
"7": (0,7),
"P8_3": (1,6),
"P8_4": (1,7),
"P8_5": (1,2),
"P8_6": (1,3),
"P8_7": (2,2),
"P8_8": (2,3),
"P8_9": (2,5),
"P8_10": (2,4),
"P8_11": (1,13),
"P8_12": (1,12),
"P8_13": (0,23),
"P8_14": (0,26),
"P8_15": (1,15),
"P8_16": (1,14),
"P8_17": (0,27),
"P8_18": (2,1),
"P8_19": (0,22),
"P8_20": (1,31),
"P8_21": (1,30),
"P8_22": (1,5),
"P8_23": (1,4),
"P8_24": (1,1),
"P8_25": (1,0),
"P8_26": (1,29),
"P8_27": (2,22),
"P8_28": (2,24),
"P8_29": (2,23),
"P8_30": (2,25),
"P8_31": (0,10),
"P8_32": (0,11),
"P8_33": (0,9),
"P8_34": (2,17),
"P8_35": (0,8),
"P8_36": (2,16),
"P8_37": (2,14),
"P8_38": (2,15),
"P8_39": (2,12),
"P8_40": (2,13),
"P8_41": (2,10),
"P8_42": (2,11),
"P8_43": (2,8),
"P8_44": (2,9),
"P8_45": (2,6),
"P8_46": (2,7),
"TIMER4": (2,2),
"TIMER7": (2,3),
"TIMER5": (2,5),
"TIMER6": (2,4),
"EHRPWM2B": (0,23),
"EHRPWM2A": (0,22),
"UART5_CTSN": (0,10),
"UART5_RTSN": (0,11),
"UART4_RTSN": (0,9),
"UART3_RTSN": (2,17),
"UART4_CTSN": (0,8),
"UART3_CTSN": (2,16),
"UART5_TXD": (2,14),
"UART5_RXD": (2,15),
"38": (1,6),
"39": (1,7),
"34": (1,2),
"35": (1,3),
"66": (2,2),
"67": (2,3),
"69": (2,5),
"68": (2,4),
"45": (1,13),
"44": (1,12),
"23": (0,23),
"26": (0,26),
"47": (1,15),
"46": (1,14),
"27": (0,27),
"65": (2,1),
"22": (0,22),
"63": (1,31),
"62": (1,30),
"37": (1,5),
"36": (1,4),
"33": (1,1),
"32": (1,0),
"61": (1,29),
"86": (2,22),
"88": (2,24),
"87": (2,23),
"89": (2,25),
"10": (0,10),
"11": (0,11),
"9": (0,9),
"81": (2,17),
"8": (0,8),
"80": (2,16),
"78": (2,14),
"79": (2,15),
"76": (2,12),
"77": (2,13),
"74": (2,10),
"75": (2,11),
"72": (2,8),
"73": (2,9),
"70": (2,6),
"71": (2,7)
}
def read(sensor, pin):
# Validate GPIO and map it to GPIO base and number.
gpio = pin_to_gpio.get(str(pin).upper(), None)
if gpio is None:
# Couldn't find in mapping, check if pin looks like GPIO<base>_<number>
match = re.match('GPIO([0123])_(\d+)', pin, re.IGNORECASE)
if match is not None:
gpio = (int(match.group(1)), int(match.group(2)))
if gpio is None or gpio[0] < 0 or gpio[0] > 3 or gpio[1] < 0 or gpio[1] > 31:
raise ValueError('Pin must be a valid GPIO identifier like P9_12 or GPIO1_28.')
# Get a reading from C driver code.
result, humidity, temp = driver.read(sensor, gpio[0], gpio[1])
if result in common.TRANSIENT_ERRORS:
# Signal no result could be obtained, but the caller can retry.
return (None, None)
elif result == common.DHT_ERROR_GPIO:
raise RuntimeError('Error accessing GPIO. Make sure program is run as root with sudo!')
elif result != common.DHT_SUCCESS:
# Some kind of error occured.
raise RuntimeError('Error calling DHT test driver read: {0}'.format(result))
return (humidity, temp) | Adafruit-DHT-Fixed | /Adafruit_DHT_Fixed-1.4.2.tar.gz/Adafruit_DHT_Fixed-1.4.2/Adafruit_DHT/Beaglebone_Black.py | Beaglebone_Black.py |
# 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.
# This is a direct copy of what's in the Adafruit Python GPIO library:
# https://raw.githubusercontent.com/adafruit/Adafruit_Python_GPIO/master/Adafruit_GPIO/Platform.py
# TODO: Add dependency on Adafruit Python GPIO and use its platform detect
# functions.
import platform
import re
# Platform identification constants.
UNKNOWN = 0
RASPBERRY_PI = 1
BEAGLEBONE_BLACK = 2
def platform_detect():
"""Detect if running on the Raspberry Pi or Beaglebone Black and return the
platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN."""
# Handle Raspberry Pi
pi = pi_version()
if pi is not None:
return RASPBERRY_PI
# Handle Beaglebone Black
# TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading
# the platform.
plat = platform.platform()
if plat.lower().find('armv7l-with-debian') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-ubuntu') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-glibc2.4') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-arch') > -1:
return BEAGLEBONE_BLACK
# Couldn't figure out the platform, just return unknown.
return UNKNOWN
def pi_revision():
"""Detect the revision number of a Raspberry Pi, useful for changing
functionality like default I2C bus based on revision."""
# Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History
with open('/proc/cpuinfo', 'r') as infile:
for line in infile:
# Match a line of the form "Revision : 0002" while ignoring extra
# info in front of the revsion (like 1000 when the Pi was over-volted).
match = re.match('Revision\s+:\s+.*(\w{4})$', line, flags=re.IGNORECASE)
if match and match.group(1) in ['0000', '0002', '0003']:
# Return revision 1 if revision ends with 0000, 0002 or 0003.
return 1
elif match:
# Assume revision 2 if revision ends with any other 4 chars.
return 2
# Couldn't find the revision, throw an exception.
raise RuntimeError('Could not determine Raspberry Pi revision.')
def pi_version():
"""Detect the version of the Raspberry Pi. Returns either 1, 2, 3 or
None depending on if it's a Raspberry Pi 1 (model A, B, A+, B+),
Raspberry Pi 2 (model B+), Raspberry Pi 3,Raspberry Pi 3 (model B+), Raspberry Pi 4
or not a Raspberry Pi.
"""
# Check /proc/cpuinfo for the Hardware field value.
# 2708 is pi 1
# 2709 is pi 2
# 2835 is pi 3 or pi 4
# 2837 is pi 3b+
# Anything else is not a pi.
with open('/proc/cpuinfo', 'r') as infile:
cpuinfo = infile.read()
# Match a line like 'Hardware : BCM2709'
match = re.search('^Hardware\s+:\s+(\w+)$', cpuinfo,
flags=re.MULTILINE | re.IGNORECASE)
if not match:
# Couldn't find the hardware, assume it isn't a pi.
return None
if match.group(1) == 'BCM2708':
# Pi 1
return 1
elif match.group(1) == 'BCM2709':
# Pi 2
return 2
elif match.group(1) == 'BCM2835':
# Pi 3 or Pi 4
return 3
elif match.group(1) == 'BCM2837':
# Pi 3b+
return 3
else:
# Something else, not a pi.
return None | Adafruit-DHT-Fixed | /Adafruit_DHT_Fixed-1.4.2.tar.gz/Adafruit_DHT_Fixed-1.4.2/Adafruit_DHT/platform_detect.py | platform_detect.py |
Adafruit Python DHT Sensor Library
==================================
Python library to read the DHT series of humidity and temperature sensors on a Raspberry Pi or Beaglebone Black.
Designed specifically to work with the Adafruit DHT series sensors ----> https://www.adafruit.com/products/385
Currently the library is tested with Python 2.6, 2.7, 3.3 and 3.4. It should work with Python greater than 3.4, too.
For all platforms (Raspberry Pi and Beaglebone Black) make sure your system is able to compile Python extensions. On Raspbian or Beaglebone Black's Debian/Ubuntu image you can ensure your system is ready by executing:
````
sudo apt-get update
sudo apt-get install build-essential python-dev
````
Install the library by downloading with the download link on the right, unzipping the archive, and executing:
````
sudo python setup.py install
````
You can ommit the sudo if you use raspberry pi.
See example of usage in the examples folder.
Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit!
Written by Tony DiCola for Adafruit Industries.
MIT license, all text above must be included in any redistribution
| Adafruit-DHT-test | /Adafruit_DHT_test-1.3.2.tar.gz/Adafruit_DHT_test-1.3.2/README.md | README.md |
# 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.
import time
from . import platform_detect
# Define error constants.
DHT_SUCCESS = 0
DHT_ERROR_TIMEOUT = -1
DHT_ERROR_CHECKSUM = -2
DHT_ERROR_ARGUMENT = -3
DHT_ERROR_GPIO = -4
TRANSIENT_ERRORS = [DHT_ERROR_CHECKSUM, DHT_ERROR_TIMEOUT]
# Define sensor type constants.
DHT11 = 11
DHT22 = 22
AM2302 = 22
SENSORS = [DHT11, DHT22, AM2302]
def get_platform():
"""Return a DHT platform interface for the currently detected platform."""
plat = platform_detect.platform_detect()
if plat == platform_detect.RASPBERRY_PI:
# Check for version 1 or 2 of the pi.
version = platform_detect.pi_version()
if version == 1:
from . import Raspberry_Pi
return Raspberry_Pi
elif version == 2:
from . import Raspberry_Pi_2
return Raspberry_Pi_2
elif version == 3:
"""Use Pi 2 driver even though running on Pi 3"""
from . import Raspberry_Pi_2
return Raspberry_Pi_2
else:
raise RuntimeError('No driver for detected Raspberry Pi version available!')
elif plat == platform_detect.BEAGLEBONE_BLACK:
from . import Beaglebone_Black
return Beaglebone_Black
else:
raise RuntimeError('Unknown platform.')
def read(sensor, pin, platform=None):
"""Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius). Note that
because the sensor requires strict timing to read and Linux is not a real
time OS, a result is not guaranteed to be returned! In some cases this will
return the tuple (None, None) which indicates the function should be retried.
Also note the DHT sensor cannot be read faster than about once every 2 seconds.
Platform is an optional parameter which allows you to override the detected
platform interface--ignore this parameter unless you receive unknown platform
errors and want to override the detection.
"""
if sensor not in SENSORS:
raise ValueError('Expected DHT11, DHT22, or AM2302 sensor value.')
if platform is None:
platform = get_platform()
return platform.read(sensor, pin)
def read_retry(sensor, pin, retries=15, delay_seconds=2, platform=None):
"""Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius).
Unlike the read function, this read_retry function will attempt to read
multiple times (up to the specified max retries) until a good reading can be
found. If a good reading cannot be found after the amount of retries, a tuple
of (None, None) is returned. The delay between retries is by default 2
seconds, but can be overridden.
"""
for i in range(retries):
humidity, temperature = read(sensor, pin, platform)
if humidity is not None and temperature is not None:
return (humidity, temperature)
time.sleep(delay_seconds)
return (None, None) | Adafruit-DHT-test | /Adafruit_DHT_test-1.3.2.tar.gz/Adafruit_DHT_test-1.3.2/Adafruit_DHT/common.py | common.py |
# 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.
import re
from . import common
from . import Beaglebone_Black_Driver as driver
# Define mapping of pin names to GPIO base and number.
# Adapted from Adafruit_BBIO code Beaglebone Black system reference.
pin_to_gpio = {
"P9_11": (0,30),
"P9_12": (1,28),
"P9_13": (0,31),
"P9_14": (1,18),
"P9_15": (1,16),
"P9_16": (1,19),
"P9_17": (0,5),
"P9_18": (0,4),
"P9_19": (0,13),
"P9_20": (0,12),
"P9_21": (0,3),
"P9_22": (0,2),
"P9_23": (1,17),
"P9_24": (0,15),
"P9_25": (3,21),
"P9_26": (0,14),
"P9_27": (3,19),
"P9_28": (3,17),
"P9_29": (3,15),
"P9_30": (3,16),
"P9_31": (3,14),
"P9_41": (0,20),
"P9_42": (0,7),
"UART4_RXD": (0,30),
"UART4_TXD": (0,31),
"EHRPWM1A": (1,18),
"EHRPWM1B": (1,19),
"I2C1_SCL": (0,5),
"I2C1_SDA": (0,4),
"I2C2_SCL": (0,13),
"I2C2_SDA": (0,12),
"UART2_TXD": (0,3),
"UART2_RXD": (0,2),
"UART1_TXD": (0,15),
"UART1_RXD": (0,14),
"SPI1_CS0": (3,17),
"SPI1_D0": (3,15),
"SPI1_D1": (3,16),
"SPI1_SCLK": (3,14),
"CLKOUT2": (0,20),
"30": (0,30),
"60": (1,28),
"31": (0,31),
"50": (1,18),
"48": (1,16),
"51": (1,19),
"5": (0,5),
"4": (0,4),
"13": (0,13),
"12": (0,12),
"3": (0,3),
"2": (0,2),
"49": (1,17),
"15": (0,15),
"117": (3,21),
"14": (0,14),
"115": (3,19),
"113": (3,17),
"111": (3,15),
"112": (3,16),
"110": (3,14),
"20": (0,20),
"7": (0,7),
"P8_3": (1,6),
"P8_4": (1,7),
"P8_5": (1,2),
"P8_6": (1,3),
"P8_7": (2,2),
"P8_8": (2,3),
"P8_9": (2,5),
"P8_10": (2,4),
"P8_11": (1,13),
"P8_12": (1,12),
"P8_13": (0,23),
"P8_14": (0,26),
"P8_15": (1,15),
"P8_16": (1,14),
"P8_17": (0,27),
"P8_18": (2,1),
"P8_19": (0,22),
"P8_20": (1,31),
"P8_21": (1,30),
"P8_22": (1,5),
"P8_23": (1,4),
"P8_24": (1,1),
"P8_25": (1,0),
"P8_26": (1,29),
"P8_27": (2,22),
"P8_28": (2,24),
"P8_29": (2,23),
"P8_30": (2,25),
"P8_31": (0,10),
"P8_32": (0,11),
"P8_33": (0,9),
"P8_34": (2,17),
"P8_35": (0,8),
"P8_36": (2,16),
"P8_37": (2,14),
"P8_38": (2,15),
"P8_39": (2,12),
"P8_40": (2,13),
"P8_41": (2,10),
"P8_42": (2,11),
"P8_43": (2,8),
"P8_44": (2,9),
"P8_45": (2,6),
"P8_46": (2,7),
"TIMER4": (2,2),
"TIMER7": (2,3),
"TIMER5": (2,5),
"TIMER6": (2,4),
"EHRPWM2B": (0,23),
"EHRPWM2A": (0,22),
"UART5_CTSN": (0,10),
"UART5_RTSN": (0,11),
"UART4_RTSN": (0,9),
"UART3_RTSN": (2,17),
"UART4_CTSN": (0,8),
"UART3_CTSN": (2,16),
"UART5_TXD": (2,14),
"UART5_RXD": (2,15),
"38": (1,6),
"39": (1,7),
"34": (1,2),
"35": (1,3),
"66": (2,2),
"67": (2,3),
"69": (2,5),
"68": (2,4),
"45": (1,13),
"44": (1,12),
"23": (0,23),
"26": (0,26),
"47": (1,15),
"46": (1,14),
"27": (0,27),
"65": (2,1),
"22": (0,22),
"63": (1,31),
"62": (1,30),
"37": (1,5),
"36": (1,4),
"33": (1,1),
"32": (1,0),
"61": (1,29),
"86": (2,22),
"88": (2,24),
"87": (2,23),
"89": (2,25),
"10": (0,10),
"11": (0,11),
"9": (0,9),
"81": (2,17),
"8": (0,8),
"80": (2,16),
"78": (2,14),
"79": (2,15),
"76": (2,12),
"77": (2,13),
"74": (2,10),
"75": (2,11),
"72": (2,8),
"73": (2,9),
"70": (2,6),
"71": (2,7)
}
def read(sensor, pin):
# Validate GPIO and map it to GPIO base and number.
gpio = pin_to_gpio.get(str(pin).upper(), None)
if gpio is None:
# Couldn't find in mapping, check if pin looks like GPIO<base>_<number>
match = re.match('GPIO([0123])_(\d+)', pin, re.IGNORECASE)
if match is not None:
gpio = (int(match.group(1)), int(match.group(2)))
if gpio is None or gpio[0] < 0 or gpio[0] > 3 or gpio[1] < 0 or gpio[1] > 31:
raise ValueError('Pin must be a valid GPIO identifier like P9_12 or GPIO1_28.')
# Get a reading from C driver code.
result, humidity, temp = driver.read(sensor, gpio[0], gpio[1])
if result in common.TRANSIENT_ERRORS:
# Signal no result could be obtained, but the caller can retry.
return (None, None)
elif result == common.DHT_ERROR_GPIO:
raise RuntimeError('Error accessing GPIO. Make sure program is run as root with sudo!')
elif result != common.DHT_SUCCESS:
# Some kind of error occured.
raise RuntimeError('Error calling DHT test driver read: {0}'.format(result))
return (humidity, temp) | Adafruit-DHT-test | /Adafruit_DHT_test-1.3.2.tar.gz/Adafruit_DHT_test-1.3.2/Adafruit_DHT/Beaglebone_Black.py | Beaglebone_Black.py |
# 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.
# This is a direct copy of what's in the Adafruit Python GPIO library:
# https://raw.githubusercontent.com/adafruit/Adafruit_Python_GPIO/master/Adafruit_GPIO/Platform.py
# TODO: Add dependency on Adafruit Python GPIO and use its platform detect
# functions.
import platform
import re
# Platform identification constants.
UNKNOWN = 0
RASPBERRY_PI = 1
BEAGLEBONE_BLACK = 2
def platform_detect():
"""Detect if running on the Raspberry Pi or Beaglebone Black and return the
platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN."""
# Handle Raspberry Pi
pi = pi_version()
if pi is not None:
return RASPBERRY_PI
# Handle Beaglebone Black
# TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading
# the platform.
plat = platform.platform()
if plat.lower().find('armv7l-with-debian') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-ubuntu') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-glibc2.4') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-arch') > -1:
return BEAGLEBONE_BLACK
# Couldn't figure out the platform, just return unknown.
return UNKNOWN
def pi_revision():
"""Detect the revision number of a Raspberry Pi, useful for changing
functionality like default I2C bus based on revision."""
# Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History
with open('/proc/cpuinfo', 'r') as infile:
for line in infile:
# Match a line of the form "Revision : 0002" while ignoring extra
# info in front of the revsion (like 1000 when the Pi was over-volted).
match = re.match('Revision\s+:\s+.*(\w{4})$', line, flags=re.IGNORECASE)
if match and match.group(1) in ['0000', '0002', '0003']:
# Return revision 1 if revision ends with 0000, 0002 or 0003.
return 1
elif match:
# Assume revision 2 if revision ends with any other 4 chars.
return 2
# Couldn't find the revision, throw an exception.
raise RuntimeError('Could not determine Raspberry Pi revision.')
def pi_version():
"""Detect the version of the Raspberry Pi. Returns either 1, 2, 3 or
None depending on if it's a Raspberry Pi 1 (model A, B, A+, B+),
Raspberry Pi 2 (model B+), Raspberry Pi 3 or not a Raspberry Pi.
"""
# Check /proc/cpuinfo for the Hardware field value.
# 2708 is pi 1
# 2709 is pi 2
# 2835 is pi 3
# Anything else is not a pi.
with open('/proc/cpuinfo', 'r') as infile:
cpuinfo = infile.read()
# Match a line like 'Hardware : BCM2709'
match = re.search('^Hardware\s+:\s+(\w+)$', cpuinfo,
flags=re.MULTILINE | re.IGNORECASE)
if not match:
# Couldn't find the hardware, assume it isn't a pi.
return None
if match.group(1) == 'BCM2708':
# Pi 1
return 1
elif match.group(1) == 'BCM2709':
# Pi 2
return 2
elif match.group(1) == 'BCM2835':
# Pi 3
return 3
else:
# Something else, not a pi.
return None | Adafruit-DHT-test | /Adafruit_DHT_test-1.3.2.tar.gz/Adafruit_DHT_test-1.3.2/Adafruit_DHT/platform_detect.py | platform_detect.py |
Adafruit Python DHT Sensor Library
==================================
Python library to read the DHT series of humidity and temperature sensors on a
Raspberry Pi or Beaglebone Black.
Designed specifically to work with the Adafruit DHT series sensors ---->
https://www.adafruit.com/products/385
Currently the library is tested with Python 2.6, 2.7, 3.3 and 3.4. It should
work with Python greater than 3.4, too.
Installing
----------
### Dependencies
For all platforms (Raspberry Pi and Beaglebone Black) make sure your system is
able to compile and download Python extensions with **pip**:
On Raspbian or Beaglebone Black's Debian/Ubuntu image you can ensure your
system is ready by running one or two of the following sets of commands:
Python 2:
````sh
sudo apt-get update
sudo apt-get install python-pip
sudo python -m pip install --upgrade pip setuptools wheel
````
Python 3:
````sh
sudo apt-get update
sudo apt-get install python3-pip
sudo python3 -m pip install --upgrade pip setuptools wheel
````
### Install with pip
Use `pip` to install from PyPI.
Python 2:
```sh
sudo pip install Adafruit_DHT
```
Python 3:
```sh
sudo pip3 install Adafruit_DHT
```
### Compile and install from the repository
First download the library source code from the [GitHub releases
page](https://github.com/adafruit/Adafruit_Python_DHT/releases), unzipping the
archive, and execute:
Python 2:
```sh
cd Adafruit_Python_DHT
sudo python setup.py install
```
Python 3:
```sh
cd Adafruit_Python_DHT
sudo python3 setup.py install
```
You may also git clone the repository if you want to test an unreleased
version:
```sh
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
```
Usage
-----
See example of usage in the examples folder.
Author
------
Adafruit invests time and resources providing this open source code, please
support Adafruit and open-source hardware by purchasing products from Adafruit!
Written by Tony DiCola for Adafruit Industries.
MIT license, all text above must be included in any redistribution
| Adafruit-DHT | /Adafruit_DHT-1.4.0.tar.gz/Adafruit_DHT-1.4.0/README.md | README.md |
# 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.
import time
from . import platform_detect
# Define error constants.
DHT_SUCCESS = 0
DHT_ERROR_TIMEOUT = -1
DHT_ERROR_CHECKSUM = -2
DHT_ERROR_ARGUMENT = -3
DHT_ERROR_GPIO = -4
TRANSIENT_ERRORS = [DHT_ERROR_CHECKSUM, DHT_ERROR_TIMEOUT]
# Define sensor type constants.
DHT11 = 11
DHT22 = 22
AM2302 = 22
SENSORS = [DHT11, DHT22, AM2302]
def get_platform():
"""Return a DHT platform interface for the currently detected platform."""
plat = platform_detect.platform_detect()
if plat == platform_detect.RASPBERRY_PI:
# Check for version 1 or 2 of the pi.
version = platform_detect.pi_version()
if version == 1:
from . import Raspberry_Pi
return Raspberry_Pi
elif version == 2:
from . import Raspberry_Pi_2
return Raspberry_Pi_2
elif version == 3:
"""Use Pi 2 driver even though running on Pi 3"""
from . import Raspberry_Pi_2
return Raspberry_Pi_2
else:
raise RuntimeError('No driver for detected Raspberry Pi version available!')
elif plat == platform_detect.BEAGLEBONE_BLACK:
from . import Beaglebone_Black
return Beaglebone_Black
else:
raise RuntimeError('Unknown platform.')
def read(sensor, pin, platform=None):
"""Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius). Note that
because the sensor requires strict timing to read and Linux is not a real
time OS, a result is not guaranteed to be returned! In some cases this will
return the tuple (None, None) which indicates the function should be retried.
Also note the DHT sensor cannot be read faster than about once every 2 seconds.
Platform is an optional parameter which allows you to override the detected
platform interface--ignore this parameter unless you receive unknown platform
errors and want to override the detection.
"""
if sensor not in SENSORS:
raise ValueError('Expected DHT11, DHT22, or AM2302 sensor value.')
if platform is None:
platform = get_platform()
return platform.read(sensor, pin)
def read_retry(sensor, pin, retries=15, delay_seconds=2, platform=None):
"""Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on
specified pin and return a tuple of humidity (as a floating point value
in percent) and temperature (as a floating point value in Celsius).
Unlike the read function, this read_retry function will attempt to read
multiple times (up to the specified max retries) until a good reading can be
found. If a good reading cannot be found after the amount of retries, a tuple
of (None, None) is returned. The delay between retries is by default 2
seconds, but can be overridden.
"""
for i in range(retries):
humidity, temperature = read(sensor, pin, platform)
if humidity is not None and temperature is not None:
return (humidity, temperature)
time.sleep(delay_seconds)
return (None, None) | Adafruit-DHT | /Adafruit_DHT-1.4.0.tar.gz/Adafruit_DHT-1.4.0/Adafruit_DHT/common.py | common.py |
# 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.
import re
from . import common
from . import Beaglebone_Black_Driver as driver
# Define mapping of pin names to GPIO base and number.
# Adapted from Adafruit_BBIO code Beaglebone Black system reference.
pin_to_gpio = {
"P9_11": (0,30),
"P9_12": (1,28),
"P9_13": (0,31),
"P9_14": (1,18),
"P9_15": (1,16),
"P9_16": (1,19),
"P9_17": (0,5),
"P9_18": (0,4),
"P9_19": (0,13),
"P9_20": (0,12),
"P9_21": (0,3),
"P9_22": (0,2),
"P9_23": (1,17),
"P9_24": (0,15),
"P9_25": (3,21),
"P9_26": (0,14),
"P9_27": (3,19),
"P9_28": (3,17),
"P9_29": (3,15),
"P9_30": (3,16),
"P9_31": (3,14),
"P9_41": (0,20),
"P9_42": (0,7),
"UART4_RXD": (0,30),
"UART4_TXD": (0,31),
"EHRPWM1A": (1,18),
"EHRPWM1B": (1,19),
"I2C1_SCL": (0,5),
"I2C1_SDA": (0,4),
"I2C2_SCL": (0,13),
"I2C2_SDA": (0,12),
"UART2_TXD": (0,3),
"UART2_RXD": (0,2),
"UART1_TXD": (0,15),
"UART1_RXD": (0,14),
"SPI1_CS0": (3,17),
"SPI1_D0": (3,15),
"SPI1_D1": (3,16),
"SPI1_SCLK": (3,14),
"CLKOUT2": (0,20),
"30": (0,30),
"60": (1,28),
"31": (0,31),
"50": (1,18),
"48": (1,16),
"51": (1,19),
"5": (0,5),
"4": (0,4),
"13": (0,13),
"12": (0,12),
"3": (0,3),
"2": (0,2),
"49": (1,17),
"15": (0,15),
"117": (3,21),
"14": (0,14),
"115": (3,19),
"113": (3,17),
"111": (3,15),
"112": (3,16),
"110": (3,14),
"20": (0,20),
"7": (0,7),
"P8_3": (1,6),
"P8_4": (1,7),
"P8_5": (1,2),
"P8_6": (1,3),
"P8_7": (2,2),
"P8_8": (2,3),
"P8_9": (2,5),
"P8_10": (2,4),
"P8_11": (1,13),
"P8_12": (1,12),
"P8_13": (0,23),
"P8_14": (0,26),
"P8_15": (1,15),
"P8_16": (1,14),
"P8_17": (0,27),
"P8_18": (2,1),
"P8_19": (0,22),
"P8_20": (1,31),
"P8_21": (1,30),
"P8_22": (1,5),
"P8_23": (1,4),
"P8_24": (1,1),
"P8_25": (1,0),
"P8_26": (1,29),
"P8_27": (2,22),
"P8_28": (2,24),
"P8_29": (2,23),
"P8_30": (2,25),
"P8_31": (0,10),
"P8_32": (0,11),
"P8_33": (0,9),
"P8_34": (2,17),
"P8_35": (0,8),
"P8_36": (2,16),
"P8_37": (2,14),
"P8_38": (2,15),
"P8_39": (2,12),
"P8_40": (2,13),
"P8_41": (2,10),
"P8_42": (2,11),
"P8_43": (2,8),
"P8_44": (2,9),
"P8_45": (2,6),
"P8_46": (2,7),
"TIMER4": (2,2),
"TIMER7": (2,3),
"TIMER5": (2,5),
"TIMER6": (2,4),
"EHRPWM2B": (0,23),
"EHRPWM2A": (0,22),
"UART5_CTSN": (0,10),
"UART5_RTSN": (0,11),
"UART4_RTSN": (0,9),
"UART3_RTSN": (2,17),
"UART4_CTSN": (0,8),
"UART3_CTSN": (2,16),
"UART5_TXD": (2,14),
"UART5_RXD": (2,15),
"38": (1,6),
"39": (1,7),
"34": (1,2),
"35": (1,3),
"66": (2,2),
"67": (2,3),
"69": (2,5),
"68": (2,4),
"45": (1,13),
"44": (1,12),
"23": (0,23),
"26": (0,26),
"47": (1,15),
"46": (1,14),
"27": (0,27),
"65": (2,1),
"22": (0,22),
"63": (1,31),
"62": (1,30),
"37": (1,5),
"36": (1,4),
"33": (1,1),
"32": (1,0),
"61": (1,29),
"86": (2,22),
"88": (2,24),
"87": (2,23),
"89": (2,25),
"10": (0,10),
"11": (0,11),
"9": (0,9),
"81": (2,17),
"8": (0,8),
"80": (2,16),
"78": (2,14),
"79": (2,15),
"76": (2,12),
"77": (2,13),
"74": (2,10),
"75": (2,11),
"72": (2,8),
"73": (2,9),
"70": (2,6),
"71": (2,7)
}
def read(sensor, pin):
# Validate GPIO and map it to GPIO base and number.
gpio = pin_to_gpio.get(str(pin).upper(), None)
if gpio is None:
# Couldn't find in mapping, check if pin looks like GPIO<base>_<number>
match = re.match('GPIO([0123])_(\d+)', pin, re.IGNORECASE)
if match is not None:
gpio = (int(match.group(1)), int(match.group(2)))
if gpio is None or gpio[0] < 0 or gpio[0] > 3 or gpio[1] < 0 or gpio[1] > 31:
raise ValueError('Pin must be a valid GPIO identifier like P9_12 or GPIO1_28.')
# Get a reading from C driver code.
result, humidity, temp = driver.read(sensor, gpio[0], gpio[1])
if result in common.TRANSIENT_ERRORS:
# Signal no result could be obtained, but the caller can retry.
return (None, None)
elif result == common.DHT_ERROR_GPIO:
raise RuntimeError('Error accessing GPIO. Make sure program is run as root with sudo!')
elif result != common.DHT_SUCCESS:
# Some kind of error occured.
raise RuntimeError('Error calling DHT test driver read: {0}'.format(result))
return (humidity, temp) | Adafruit-DHT | /Adafruit_DHT-1.4.0.tar.gz/Adafruit_DHT-1.4.0/Adafruit_DHT/Beaglebone_Black.py | Beaglebone_Black.py |
# 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.
# This is a direct copy of what's in the Adafruit Python GPIO library:
# https://raw.githubusercontent.com/adafruit/Adafruit_Python_GPIO/master/Adafruit_GPIO/Platform.py
# TODO: Add dependency on Adafruit Python GPIO and use its platform detect
# functions.
import platform
import re
# Platform identification constants.
UNKNOWN = 0
RASPBERRY_PI = 1
BEAGLEBONE_BLACK = 2
def platform_detect():
"""Detect if running on the Raspberry Pi or Beaglebone Black and return the
platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN."""
# Handle Raspberry Pi
pi = pi_version()
if pi is not None:
return RASPBERRY_PI
# Handle Beaglebone Black
# TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading
# the platform.
plat = platform.platform()
if plat.lower().find('armv7l-with-debian') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-ubuntu') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-glibc2.4') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-arch') > -1:
return BEAGLEBONE_BLACK
# Couldn't figure out the platform, just return unknown.
return UNKNOWN
def pi_revision():
"""Detect the revision number of a Raspberry Pi, useful for changing
functionality like default I2C bus based on revision."""
# Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History
with open('/proc/cpuinfo', 'r') as infile:
for line in infile:
# Match a line of the form "Revision : 0002" while ignoring extra
# info in front of the revsion (like 1000 when the Pi was over-volted).
match = re.match('Revision\s+:\s+.*(\w{4})$', line, flags=re.IGNORECASE)
if match and match.group(1) in ['0000', '0002', '0003']:
# Return revision 1 if revision ends with 0000, 0002 or 0003.
return 1
elif match:
# Assume revision 2 if revision ends with any other 4 chars.
return 2
# Couldn't find the revision, throw an exception.
raise RuntimeError('Could not determine Raspberry Pi revision.')
def pi_version():
"""Detect the version of the Raspberry Pi. Returns either 1, 2, 3 or
None depending on if it's a Raspberry Pi 1 (model A, B, A+, B+),
Raspberry Pi 2 (model B+), Raspberry Pi 3,Raspberry Pi 3 (model B+) or not a Raspberry Pi.
"""
# Check /proc/cpuinfo for the Hardware field value.
# 2708 is pi 1
# 2709 is pi 2
# 2835 is pi 3
# 2837 is pi 3b+
# Anything else is not a pi.
with open('/proc/cpuinfo', 'r') as infile:
cpuinfo = infile.read()
# Match a line like 'Hardware : BCM2709'
match = re.search('^Hardware\s+:\s+(\w+)$', cpuinfo,
flags=re.MULTILINE | re.IGNORECASE)
if not match:
# Couldn't find the hardware, assume it isn't a pi.
return None
if match.group(1) == 'BCM2708':
# Pi 1
return 1
elif match.group(1) == 'BCM2709':
# Pi 2
return 2
elif match.group(1) == 'BCM2835':
# Pi 3
return 3
elif match.group(1) == 'BCM2837':
# Pi 3b+
return 3
else:
# Something else, not a pi.
return None | Adafruit-DHT | /Adafruit_DHT-1.4.0.tar.gz/Adafruit_DHT-1.4.0/Adafruit_DHT/platform_detect.py | platform_detect.py |
import math
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.I2C as I2C
class MCP230xxBase(GPIO.BaseGPIO):
"""Base class to represent an MCP230xx series GPIO extender. Is compatible
with the Adafruit_GPIO BaseGPIO class so it can be used as a custom GPIO
class for interacting with device.
"""
def __init__(self, address, i2c=None, **kwargs):
"""Initialize MCP230xx at specified I2C address and bus number. If bus
is not specified it will default to the appropriate platform detected bus.
"""
# Create I2C device.
if i2c is None:
import Adafruit_GPIO.I2C as I2C
i2c = I2C
self._device = i2c.get_i2c_device(address, **kwargs)
# Assume starting in ICON.BANK = 0 mode (sequential access).
# Compute how many bytes are needed to store count of GPIO.
self.gpio_bytes = int(math.ceil(self.NUM_GPIO/8.0))
# Buffer register values so they can be changed without reading.
self.iodir = [0x00]*self.gpio_bytes # Default direction to all inputs.
self.gppu = [0x00]*self.gpio_bytes # Default to pullups disabled.
self.gpio = [0x00]*self.gpio_bytes
# Write current direction and pullup buffer state.
self.write_iodir()
self.write_gppu()
def setup(self, pin, value):
"""Set the input or output mode for a specified pin. Mode should be
either GPIO.OUT or GPIO.IN.
"""
self._validate_pin(pin)
# Set bit to 1 for input or 0 for output.
if value == GPIO.IN:
self.iodir[int(pin/8)] |= 1 << (int(pin%8))
elif value == GPIO.OUT:
self.iodir[int(pin/8)] &= ~(1 << (int(pin%8)))
else:
raise ValueError('Unexpected value. Must be GPIO.IN or GPIO.OUT.')
self.write_iodir()
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either GPIO.HIGH/GPIO.LOW or a boolean (True = HIGH).
"""
self.output_pins({pin: value})
def output_pins(self, pins):
"""Set multiple pins high or low at once. Pins should be a dict of pin
name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins
will be set to the given values.
"""
[self._validate_pin(pin) for pin in pins.keys()]
# Set each changed pin's bit.
for pin, value in iter(pins.items()):
if value:
self.gpio[int(pin/8)] |= 1 << (int(pin%8))
else:
self.gpio[int(pin/8)] &= ~(1 << (int(pin%8)))
# Write GPIO state.
self.write_gpio()
def input(self, pin):
"""Read the specified pin and return GPIO.HIGH/True if the pin is pulled
high, or GPIO.LOW/False if pulled low.
"""
return self.input_pins([pin])[0]
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
"""
[self._validate_pin(pin) for pin in pins]
# Get GPIO state.
gpio = self._device.readList(self.GPIO, self.gpio_bytes)
# Return True if pin's bit is set.
return [(gpio[int(pin/8)] & 1 << (int(pin%8))) > 0 for pin in pins]
def pullup(self, pin, enabled):
"""Turn on the pull-up resistor for the specified pin if enabled is True,
otherwise turn off the pull-up resistor.
"""
self._validate_pin(pin)
if enabled:
self.gppu[int(pin/8)] |= 1 << (int(pin%8))
else:
self.gppu[int(pin/8)] &= ~(1 << (int(pin%8)))
self.write_gppu()
def write_gpio(self, gpio=None):
"""Write the specified byte value to the GPIO registor. If no value
specified the current buffered value will be written.
"""
if gpio is not None:
self.gpio = gpio
self._device.writeList(self.GPIO, self.gpio)
def write_iodir(self, iodir=None):
"""Write the specified byte value to the IODIR registor. If no value
specified the current buffered value will be written.
"""
if iodir is not None:
self.iodir = iodir
self._device.writeList(self.IODIR, self.iodir)
def write_gppu(self, gppu=None):
"""Write the specified byte value to the GPPU registor. If no value
specified the current buffered value will be written.
"""
if gppu is not None:
self.gppu = gppu
self._device.writeList(self.GPPU, self.gppu)
class MCP23017(MCP230xxBase):
"""MCP23017-based GPIO class with 16 GPIO pins."""
# Define number of pins and registor addresses.
NUM_GPIO = 16
IODIR = 0x00
GPIO = 0x12
GPPU = 0x0C
def __init__(self, address=0x20, **kwargs):
super(MCP23017, self).__init__(address, **kwargs)
class MCP23008(MCP230xxBase):
"""MCP23008-based GPIO class with 8 GPIO pins."""
# Define number of pins and registor addresses.
NUM_GPIO = 8
IODIR = 0x00
GPIO = 0x09
GPPU = 0x06
def __init__(self, address=0x20, **kwargs):
super(MCP23008, self).__init__(address, **kwargs) | Adafruit-GPIO | /Adafruit_GPIO-1.0.3.tar.gz/Adafruit_GPIO-1.0.3/Adafruit_GPIO/MCP230xx.py | MCP230xx.py |
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.I2C as I2C
IN = GPIO.IN
OUT = GPIO.OUT
HIGH = GPIO.HIGH
LOW = GPIO.LOW
class PCF8574(GPIO.BaseGPIO):
"""Class to represent a PCF8574 or PCF8574A GPIO extender. Compatible
with the Adafruit_GPIO BaseGPIO class so it can be used as a custom GPIO
class for interacting with device.
"""
NUM_GPIO = 8
def __init__(self, address=0x27, busnum=None, i2c=None, **kwargs):
address = int(address)
self.__name__ = \
"PCF8574" if address in range(0x20, 0x28) else \
"PCF8574A" if address in range(0x38, 0x40) else \
"Bad address for PCF8574(A): 0x%02X not in range [0x20..0x27, 0x38..0x3F]" % address
if self.__name__[0] != 'P':
raise ValueError(self.__name__)
# Create I2C device.
i2c = i2c or I2C
busnum = busnum or i2c.get_default_bus()
self._device = i2c.get_i2c_device(address, busnum, **kwargs)
# Buffer register values so they can be changed without reading.
self.iodir = 0xFF # Default direction to all inputs is in
self.gpio = 0x00
self._write_pins()
def _write_pins(self):
self._device.writeRaw8(self.gpio | self.iodir)
def _read_pins(self):
return self._device.readRaw8() & self.iodir
def setup(self, pin, mode):
self.setup_pins({pin: mode})
def setup_pins(self, pins):
if False in [y for x,y in [(self._validate_pin(pin),mode in (IN,OUT)) for pin,mode in pins.iteritems()]]:
raise ValueError('Invalid MODE, IN or OUT')
for pin,mode in pins.iteritems():
self.iodir = self._bit2(self.iodir, pin, mode)
self._write_pins()
def output(self, pin, value):
self.output_pins({pin: value})
def output_pins(self, pins):
[self._validate_pin(pin) for pin in pins.keys()]
for pin,value in pins.iteritems():
self.gpio = self._bit2(self.gpio, pin, bool(value))
self._write_pins()
def input(self, pin):
return self.input_pins([pin])[0]
def input_pins(self, pins):
[self._validate_pin(pin) for pin in pins]
inp = self._read_pins()
return [bool(inp & (1<<pin)) for pin in pins] | Adafruit-GPIO | /Adafruit_GPIO-1.0.3.tar.gz/Adafruit_GPIO-1.0.3/Adafruit_GPIO/PCF8574.py | PCF8574.py |
import logging
import subprocess
import Adafruit_GPIO.Platform as Platform
def reverseByteOrder(data):
"""Reverses the byte order of an int (16-bit) or long (32-bit) value."""
# Courtesy Vishal Sapre
byteCount = len(hex(data)[2:].replace('L','')[::2])
val = 0
for i in range(byteCount):
val = (val << 8) | (data & 0xff)
data >>= 8
return val
def get_default_bus():
"""Return the default bus number based on the device platform. For a
Raspberry Pi either bus 0 or 1 (based on the Pi revision) will be returned.
For a Beaglebone Black the first user accessible bus, 1, will be returned.
"""
plat = Platform.platform_detect()
if plat == Platform.RASPBERRY_PI:
if Platform.pi_revision() == 1:
# Revision 1 Pi uses I2C bus 0.
return 0
else:
# Revision 2 Pi uses I2C bus 1.
return 1
elif plat == Platform.BEAGLEBONE_BLACK:
# Beaglebone Black has multiple I2C buses, default to 1 (P9_19 and P9_20).
return 1
else:
raise RuntimeError('Could not determine default I2C bus for platform.')
def get_i2c_device(address, busnum=None, i2c_interface=None, **kwargs):
"""Return an I2C device for the specified address and on the specified bus.
If busnum isn't specified, the default I2C bus for the platform will attempt
to be detected.
"""
if busnum is None:
busnum = get_default_bus()
return Device(address, busnum, i2c_interface, **kwargs)
def require_repeated_start():
"""Enable repeated start conditions for I2C register reads. This is the
normal behavior for I2C, however on some platforms like the Raspberry Pi
there are bugs which disable repeated starts unless explicitly enabled with
this function. See this thread for more details:
http://www.raspberrypi.org/forums/viewtopic.php?f=44&t=15840
"""
plat = Platform.platform_detect()
if plat == Platform.RASPBERRY_PI:
# On the Raspberry Pi there is a bug where register reads don't send a
# repeated start condition like the kernel smbus I2C driver functions
# define. As a workaround this bit in the BCM2708 driver sysfs tree can
# be changed to enable I2C repeated starts.
subprocess.check_call('chmod 666 /sys/module/i2c_bcm2708/parameters/combined', shell=True)
subprocess.check_call('echo -n 1 > /sys/module/i2c_bcm2708/parameters/combined', shell=True)
# Other platforms are a no-op because they (presumably) have the correct
# behavior and send repeated starts.
class Device(object):
"""Class for communicating with an I2C device using the adafruit-pureio pure
python smbus library, or other smbus compatible I2C interface. Allows reading
and writing 8-bit, 16-bit, and byte array values to registers
on the device."""
def __init__(self, address, busnum, i2c_interface=None):
"""Create an instance of the I2C device at the specified address on the
specified I2C bus number."""
self._address = address
if i2c_interface is None:
# Use pure python I2C interface if none is specified.
import Adafruit_PureIO.smbus
self._bus = Adafruit_PureIO.smbus.SMBus(busnum)
else:
# Otherwise use the provided class to create an smbus interface.
self._bus = i2c_interface(busnum)
self._logger = logging.getLogger('Adafruit_I2C.Device.Bus.{0}.Address.{1:#0X}' \
.format(busnum, address))
def writeRaw8(self, value):
"""Write an 8-bit value on the bus (without register)."""
value = value & 0xFF
self._bus.write_byte(self._address, value)
self._logger.debug("Wrote 0x%02X",
value)
def write8(self, register, value):
"""Write an 8-bit value to the specified register."""
value = value & 0xFF
self._bus.write_byte_data(self._address, register, value)
self._logger.debug("Wrote 0x%02X to register 0x%02X",
value, register)
def write16(self, register, value):
"""Write a 16-bit value to the specified register."""
value = value & 0xFFFF
self._bus.write_word_data(self._address, register, value)
self._logger.debug("Wrote 0x%04X to register pair 0x%02X, 0x%02X",
value, register, register+1)
def writeList(self, register, data):
"""Write bytes to the specified register."""
self._bus.write_i2c_block_data(self._address, register, data)
self._logger.debug("Wrote to register 0x%02X: %s",
register, data)
def readList(self, register, length):
"""Read a length number of bytes from the specified register. Results
will be returned as a bytearray."""
results = self._bus.read_i2c_block_data(self._address, register, length)
self._logger.debug("Read the following from register 0x%02X: %s",
register, results)
return results
def readRaw8(self):
"""Read an 8-bit value on the bus (without register)."""
result = self._bus.read_byte(self._address) & 0xFF
self._logger.debug("Read 0x%02X",
result)
return result
def readU8(self, register):
"""Read an unsigned byte from the specified register."""
result = self._bus.read_byte_data(self._address, register) & 0xFF
self._logger.debug("Read 0x%02X from register 0x%02X",
result, register)
return result
def readS8(self, register):
"""Read a signed byte from the specified register."""
result = self.readU8(register)
if result > 127:
result -= 256
return result
def readU16(self, register, little_endian=True):
"""Read an unsigned 16-bit value from the specified register, with the
specified endianness (default little endian, or least significant byte
first)."""
result = self._bus.read_word_data(self._address,register) & 0xFFFF
self._logger.debug("Read 0x%04X from register pair 0x%02X, 0x%02X",
result, register, register+1)
# Swap bytes if using big endian because read_word_data assumes little
# endian on ARM (little endian) systems.
if not little_endian:
result = ((result << 8) & 0xFF00) + (result >> 8)
return result
def readS16(self, register, little_endian=True):
"""Read a signed 16-bit value from the specified register, with the
specified endianness (default little endian, or least significant byte
first)."""
result = self.readU16(register, little_endian)
if result > 32767:
result -= 65536
return result
def readU16LE(self, register):
"""Read an unsigned 16-bit value from the specified register, in little
endian byte order."""
return self.readU16(register, little_endian=True)
def readU16BE(self, register):
"""Read an unsigned 16-bit value from the specified register, in big
endian byte order."""
return self.readU16(register, little_endian=False)
def readS16LE(self, register):
"""Read a signed 16-bit value from the specified register, in little
endian byte order."""
return self.readS16(register, little_endian=True)
def readS16BE(self, register):
"""Read a signed 16-bit value from the specified register, in big
endian byte order."""
return self.readS16(register, little_endian=False) | Adafruit-GPIO | /Adafruit_GPIO-1.0.3.tar.gz/Adafruit_GPIO-1.0.3/Adafruit_GPIO/I2C.py | I2C.py |
import atexit
import logging
import math
import os
import subprocess
import sys
import time
import ftdi1 as ftdi
import Adafruit_GPIO.GPIO as GPIO
logger = logging.getLogger(__name__)
FT232H_VID = 0x0403 # Default FTDI FT232H vendor ID
FT232H_PID = 0x6014 # Default FTDI FT232H product ID
MSBFIRST = 0
LSBFIRST = 1
_REPEAT_DELAY = 4
def _check_running_as_root():
# NOTE: Checking for root with user ID 0 isn't very portable, perhaps
# there's a better alternative?
if os.geteuid() != 0:
raise RuntimeError('Expected to be run by root user! Try running with sudo.')
def disable_FTDI_driver():
"""Disable the FTDI drivers for the current platform. This is necessary
because they will conflict with libftdi and accessing the FT232H. Note you
can enable the FTDI drivers again by calling enable_FTDI_driver.
"""
logger.debug('Disabling FTDI driver.')
if sys.platform == 'darwin':
logger.debug('Detected Mac OSX')
# Mac OS commands to disable FTDI driver.
_check_running_as_root()
subprocess.call('kextunload -b com.apple.driver.AppleUSBFTDI', shell=True)
subprocess.call('kextunload /System/Library/Extensions/FTDIUSBSerialDriver.kext', shell=True)
elif sys.platform.startswith('linux'):
logger.debug('Detected Linux')
# Linux commands to disable FTDI driver.
_check_running_as_root()
subprocess.call('modprobe -r -q ftdi_sio', shell=True)
subprocess.call('modprobe -r -q usbserial', shell=True)
# Note there is no need to disable FTDI drivers on Windows!
def enable_FTDI_driver():
"""Re-enable the FTDI drivers for the current platform."""
logger.debug('Enabling FTDI driver.')
if sys.platform == 'darwin':
logger.debug('Detected Mac OSX')
# Mac OS commands to enable FTDI driver.
_check_running_as_root()
subprocess.check_call('kextload -b com.apple.driver.AppleUSBFTDI', shell=True)
subprocess.check_call('kextload /System/Library/Extensions/FTDIUSBSerialDriver.kext', shell=True)
elif sys.platform.startswith('linux'):
logger.debug('Detected Linux')
# Linux commands to enable FTDI driver.
_check_running_as_root()
subprocess.check_call('modprobe -q ftdi_sio', shell=True)
subprocess.check_call('modprobe -q usbserial', shell=True)
def use_FT232H():
"""Disable any built in FTDI drivers which will conflict and cause problems
with libftdi (which is used to communicate with the FT232H). Will register
an exit function so the drivers are re-enabled on program exit.
"""
disable_FTDI_driver()
atexit.register(enable_FTDI_driver)
def enumerate_device_serials(vid=FT232H_VID, pid=FT232H_PID):
"""Return a list of all FT232H device serial numbers connected to the
machine. You can use these serial numbers to open a specific FT232H device
by passing it to the FT232H initializer's serial parameter.
"""
try:
# Create a libftdi context.
ctx = None
ctx = ftdi.new()
# Enumerate FTDI devices.
device_list = None
count, device_list = ftdi.usb_find_all(ctx, vid, pid)
if count < 0:
raise RuntimeError('ftdi_usb_find_all returned error {0}: {1}'.format(count, ftdi.get_error_string(self._ctx)))
# Walk through list of devices and assemble list of serial numbers.
devices = []
while device_list is not None:
# Get USB device strings and add serial to list of devices.
ret, manufacturer, description, serial = ftdi.usb_get_strings(ctx, device_list.dev, 256, 256, 256)
if serial is not None:
devices.append(serial)
device_list = device_list.next
return devices
finally:
# Make sure to clean up list and context when done.
if device_list is not None:
ftdi.list_free(device_list)
if ctx is not None:
ftdi.free(ctx)
class FT232H(GPIO.BaseGPIO):
# Make GPIO constants that match main GPIO class for compatibility.
HIGH = GPIO.HIGH
LOW = GPIO.LOW
IN = GPIO.IN
OUT = GPIO.OUT
def __init__(self, vid=FT232H_VID, pid=FT232H_PID, serial=None):
"""Create a FT232H object. Will search for the first available FT232H
device with the specified USB vendor ID and product ID (defaults to
FT232H default VID & PID). Can also specify an optional serial number
string to open an explicit FT232H device given its serial number. See
the FT232H.enumerate_device_serials() function to see how to list all
connected device serial numbers.
"""
# Initialize FTDI device connection.
self._ctx = ftdi.new()
if self._ctx == 0:
raise RuntimeError('ftdi_new failed! Is libftdi1 installed?')
# Register handler to close and cleanup FTDI context on program exit.
atexit.register(self.close)
if serial is None:
# Open USB connection for specified VID and PID if no serial is specified.
self._check(ftdi.usb_open, vid, pid)
else:
# Open USB connection for VID, PID, serial.
self._check(ftdi.usb_open_string, 's:{0}:{1}:{2}'.format(vid, pid, serial))
# Reset device.
self._check(ftdi.usb_reset)
# Disable flow control. Commented out because it is unclear if this is necessary.
#self._check(ftdi.setflowctrl, ftdi.SIO_DISABLE_FLOW_CTRL)
# Change read & write buffers to maximum size, 65535 bytes.
self._check(ftdi.read_data_set_chunksize, 65535)
self._check(ftdi.write_data_set_chunksize, 65535)
# Clear pending read data & write buffers.
self._check(ftdi.usb_purge_buffers)
# Enable MPSSE and syncronize communication with device.
self._mpsse_enable()
self._mpsse_sync()
# Initialize all GPIO as inputs.
self._write('\x80\x00\x00\x82\x00\x00')
self._direction = 0x0000
self._level = 0x0000
def close(self):
"""Close the FTDI device. Will be automatically called when the program ends."""
if self._ctx is not None:
ftdi.free(self._ctx)
self._ctx = None
def _write(self, string):
"""Helper function to call write_data on the provided FTDI device and
verify it succeeds.
"""
# Get modem status. Useful to enable for debugging.
#ret, status = ftdi.poll_modem_status(self._ctx)
#if ret == 0:
# logger.debug('Modem status {0:02X}'.format(status))
#else:
# logger.debug('Modem status error {0}'.format(ret))
length = len(string)
ret = ftdi.write_data(self._ctx, string, length)
# Log the string that was written in a python hex string format using a very
# ugly one-liner list comprehension for brevity.
#logger.debug('Wrote {0}'.format(''.join(['\\x{0:02X}'.format(ord(x)) for x in string])))
if ret < 0:
raise RuntimeError('ftdi_write_data failed with error {0}: {1}'.format(ret, ftdi.get_error_string(self._ctx)))
if ret != length:
raise RuntimeError('ftdi_write_data expected to write {0} bytes but actually wrote {1}!'.format(length, ret))
def _check(self, command, *args):
"""Helper function to call the provided command on the FTDI device and
verify the response matches the expected value.
"""
ret = command(self._ctx, *args)
logger.debug('Called ftdi_{0} and got response {1}.'.format(command.__name__, ret))
if ret != 0:
raise RuntimeError('ftdi_{0} failed with error {1}: {2}'.format(command.__name__, ret, ftdi.get_error_string(self._ctx)))
def _poll_read(self, expected, timeout_s=5.0):
"""Helper function to continuously poll reads on the FTDI device until an
expected number of bytes are returned. Will throw a timeout error if no
data is received within the specified number of timeout seconds. Returns
the read data as a string if successful, otherwise raises an execption.
"""
start = time.time()
# Start with an empty response buffer.
response = bytearray(expected)
index = 0
# Loop calling read until the response buffer is full or a timeout occurs.
while time.time() - start <= timeout_s:
ret, data = ftdi.read_data(self._ctx, expected - index)
# Fail if there was an error reading data.
if ret < 0:
raise RuntimeError('ftdi_read_data failed with error code {0}.'.format(ret))
# Add returned data to the buffer.
response[index:index+ret] = data[:ret]
index += ret
# Buffer is full, return the result data.
if index >= expected:
return str(response)
time.sleep(0.01)
raise RuntimeError('Timeout while polling ftdi_read_data for {0} bytes!'.format(expected))
def _mpsse_enable(self):
"""Enable MPSSE mode on the FTDI device."""
# Reset MPSSE by sending mask = 0 and mode = 0
self._check(ftdi.set_bitmode, 0, 0)
# Enable MPSSE by sending mask = 0 and mode = 2
self._check(ftdi.set_bitmode, 0, 2)
def _mpsse_sync(self, max_retries=10):
"""Synchronize buffers with MPSSE by sending bad opcode and reading expected
error response. Should be called once after enabling MPSSE."""
# Send a bad/unknown command (0xAB), then read buffer until bad command
# response is found.
self._write('\xAB')
# Keep reading until bad command response (0xFA 0xAB) is returned.
# Fail if too many read attempts are made to prevent sticking in a loop.
tries = 0
sync = False
while not sync:
data = self._poll_read(2)
if data == '\xFA\xAB':
sync = True
tries += 1
if tries >= max_retries:
raise RuntimeError('Could not synchronize with FT232H!')
def mpsse_set_clock(self, clock_hz, adaptive=False, three_phase=False):
"""Set the clock speed of the MPSSE engine. Can be any value from 450hz
to 30mhz and will pick that speed or the closest speed below it.
"""
# Disable clock divisor by 5 to enable faster speeds on FT232H.
self._write('\x8A')
# Turn on/off adaptive clocking.
if adaptive:
self._write('\x96')
else:
self._write('\x97')
# Turn on/off three phase clock (needed for I2C).
# Also adjust the frequency for three-phase clocking as specified in section 2.2.4
# of this document:
# http://www.ftdichip.com/Support/Documents/AppNotes/AN_255_USB%20to%20I2C%20Example%20using%20the%20FT232H%20and%20FT201X%20devices.pdf
if three_phase:
self._write('\x8C')
else:
self._write('\x8D')
# Compute divisor for requested clock.
# Use equation from section 3.8.1 of:
# http://www.ftdichip.com/Support/Documents/AppNotes/AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf
# Note equation is using 60mhz master clock instead of 12mhz.
divisor = int(math.ceil((30000000.0-float(clock_hz))/float(clock_hz))) & 0xFFFF
if three_phase:
divisor = int(divisor*(2.0/3.0))
logger.debug('Setting clockspeed with divisor value {0}'.format(divisor))
# Send command to set divisor from low and high byte values.
self._write(str(bytearray((0x86, divisor & 0xFF, (divisor >> 8) & 0xFF))))
def mpsse_read_gpio(self):
"""Read both GPIO bus states and return a 16 bit value with their state.
D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits.
"""
# Send command to read low byte and high byte.
self._write('\x81\x83')
# Wait for 2 byte response.
data = self._poll_read(2)
# Assemble response into 16 bit value.
low_byte = ord(data[0])
high_byte = ord(data[1])
logger.debug('Read MPSSE GPIO low byte = {0:02X} and high byte = {1:02X}'.format(low_byte, high_byte))
return (high_byte << 8) | low_byte
def mpsse_gpio(self):
"""Return command to update the MPSSE GPIO state to the current direction
and level.
"""
level_low = chr(self._level & 0xFF)
level_high = chr((self._level >> 8) & 0xFF)
dir_low = chr(self._direction & 0xFF)
dir_high = chr((self._direction >> 8) & 0xFF)
return str(bytearray((0x80, level_low, dir_low, 0x82, level_high, dir_high)))
def mpsse_write_gpio(self):
"""Write the current MPSSE GPIO state to the FT232H chip."""
self._write(self.mpsse_gpio())
def get_i2c_device(self, address, **kwargs):
"""Return an I2CDevice instance using this FT232H object and the provided
I2C address. Meant to be passed as the i2c_provider parameter to objects
which use the Adafruit_Python_GPIO library for I2C.
"""
return I2CDevice(self, address, **kwargs)
# GPIO functions below:
def _setup_pin(self, pin, mode):
if pin < 0 or pin > 15:
raise ValueError('Pin must be between 0 and 15 (inclusive).')
if mode not in (GPIO.IN, GPIO.OUT):
raise ValueError('Mode must be GPIO.IN or GPIO.OUT.')
if mode == GPIO.IN:
# Set the direction and level of the pin to 0.
self._direction &= ~(1 << pin) & 0xFFFF
self._level &= ~(1 << pin) & 0xFFFF
else:
# Set the direction of the pin to 1.
self._direction |= (1 << pin) & 0xFFFF
def setup(self, pin, mode):
"""Set the input or output mode for a specified pin. Mode should be
either OUT or IN."""
self._setup_pin(pin, mode)
self.mpsse_write_gpio()
def setup_pins(self, pins, values={}, write=True):
"""Setup multiple pins as inputs or outputs at once. Pins should be a
dict of pin name to pin mode (IN or OUT). Optional starting values of
pins can be provided in the values dict (with pin name to pin value).
"""
# General implementation that can be improved by subclasses.
for pin, mode in iter(pins.items()):
self._setup_pin(pin, mode)
for pin, value in iter(values.items()):
self._output_pin(pin, value)
if write:
self.mpsse_write_gpio()
def _output_pin(self, pin, value):
if value:
self._level |= (1 << pin) & 0xFFFF
else:
self._level &= ~(1 << pin) & 0xFFFF
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high)."""
if pin < 0 or pin > 15:
raise ValueError('Pin must be between 0 and 15 (inclusive).')
self._output_pin(pin, value)
self.mpsse_write_gpio()
def output_pins(self, pins, write=True):
"""Set multiple pins high or low at once. Pins should be a dict of pin
name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins
will be set to the given values.
"""
for pin, value in iter(pins.items()):
self._output_pin(pin, value)
if write:
self.mpsse_write_gpio()
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low."""
return self.input_pins([pin])[0]
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low."""
if [pin for pin in pins if pin < 0 or pin > 15]:
raise ValueError('Pin must be between 0 and 15 (inclusive).')
_pins = self.mpsse_read_gpio()
return [((_pins >> pin) & 0x0001) == 1 for pin in pins]
class SPI(object):
def __init__(self, ft232h, cs=None, max_speed_hz=1000000, mode=0, bitorder=MSBFIRST):
self._ft232h = ft232h
# Initialize chip select pin if provided to output high.
if cs is not None:
ft232h.setup(cs, GPIO.OUT)
ft232h.set_high(cs)
self._cs = cs
# Initialize clock, mode, and bit order.
self.set_clock_hz(max_speed_hz)
self.set_mode(mode)
self.set_bit_order(bitorder)
def _assert_cs(self):
if self._cs is not None:
self._ft232h.set_low(self._cs)
def _deassert_cs(self):
if self._cs is not None:
self._ft232h.set_high(self._cs)
def set_clock_hz(self, hz):
"""Set the speed of the SPI clock in hertz. Note that not all speeds
are supported and a lower speed might be chosen by the hardware.
"""
self._ft232h.mpsse_set_clock(hz)
def set_mode(self, mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise ValueError('Mode must be a value 0, 1, 2, or 3.')
if mode == 0:
# Mode 0 captures on rising clock, propagates on falling clock
self.write_clock_ve = 1
self.read_clock_ve = 0
# Clock base is low.
clock_base = GPIO.LOW
elif mode == 1:
# Mode 1 capture of falling edge, propagate on rising clock
self.write_clock_ve = 0
self.read_clock_ve = 1
# Clock base is low.
clock_base = GPIO.LOW
elif mode == 2:
# Mode 2 capture on rising clock, propagate on falling clock
self.write_clock_ve = 1
self.read_clock_ve = 0
# Clock base is high.
clock_base = GPIO.HIGH
elif mode == 3:
# Mode 3 capture on falling edge, propagage on rising clock
self.write_clock_ve = 0
self.read_clock_ve = 1
# Clock base is high.
clock_base = GPIO.HIGH
# Set clock and DO as output, DI as input. Also start clock at its base value.
self._ft232h.setup_pins({0: GPIO.OUT, 1: GPIO.OUT, 2: GPIO.IN}, {0: clock_base})
def set_bit_order(self, order):
"""Set order of bits to be read/written over serial lines. Should be
either MSBFIRST for most-significant first, or LSBFIRST for
least-signifcant first.
"""
if order == MSBFIRST:
self.lsbfirst = 0
elif order == LSBFIRST:
self.lsbfirst = 1
else:
raise ValueError('Order must be MSBFIRST or LSBFIRST.')
def write(self, data):
"""Half-duplex SPI write. The specified array of bytes will be clocked
out the MOSI line.
"""
# Build command to write SPI data.
command = 0x10 | (self.lsbfirst << 3) | self.write_clock_ve
logger.debug('SPI write with command {0:2X}.'.format(command))
# Compute length low and high bytes.
# NOTE: Must actually send length minus one because the MPSSE engine
# considers 0 a length of 1 and FFFF a length of 65536
length = len(data)-1
len_low = length & 0xFF
len_high = (length >> 8) & 0xFF
self._assert_cs()
# Send command and length.
self._ft232h._write(str(bytearray((command, len_low, len_high))))
# Send data.
self._ft232h._write(str(bytearray(data)))
self._deassert_cs()
def read(self, length):
"""Half-duplex SPI read. The specified length of bytes will be clocked
in the MISO line and returned as a bytearray object.
"""
# Build command to read SPI data.
command = 0x20 | (self.lsbfirst << 3) | (self.read_clock_ve << 2)
logger.debug('SPI read with command {0:2X}.'.format(command))
# Compute length low and high bytes.
# NOTE: Must actually send length minus one because the MPSSE engine
# considers 0 a length of 1 and FFFF a length of 65536
len_low = (length-1) & 0xFF
len_high = ((length-1) >> 8) & 0xFF
self._assert_cs()
# Send command and length.
self._ft232h._write(str(bytearray((command, len_low, len_high, 0x87))))
self._deassert_cs()
# Read response bytes.
return bytearray(self._ft232h._poll_read(length))
def transfer(self, data):
"""Full-duplex SPI read and write. The specified array of bytes will be
clocked out the MOSI line, while simultaneously bytes will be read from
the MISO line. Read bytes will be returned as a bytearray object.
"""
# Build command to read and write SPI data.
command = 0x30 | (self.lsbfirst << 3) | (self.read_clock_ve << 2) | self.write_clock_ve
logger.debug('SPI transfer with command {0:2X}.'.format(command))
# Compute length low and high bytes.
# NOTE: Must actually send length minus one because the MPSSE engine
# considers 0 a length of 1 and FFFF a length of 65536
length = len(data)
len_low = (length-1) & 0xFF
len_high = ((length-1) >> 8) & 0xFF
# Send command and length.
self._assert_cs()
self._ft232h._write(str(bytearray((command, len_low, len_high))))
self._ft232h._write(str(bytearray(data)))
self._ft232h._write('\x87')
self._deassert_cs()
# Read response bytes.
return bytearray(self._ft232h._poll_read(length))
class I2CDevice(object):
"""Class for communicating with an I2C device using the smbus library.
Allows reading and writing 8-bit, 16-bit, and byte array values to registers
on the device."""
# Note that most of the functions in this code are adapted from this app note:
# http://www.ftdichip.com/Support/Documents/AppNotes/AN_255_USB%20to%20I2C%20Example%20using%20the%20FT232H%20and%20FT201X%20devices.pdf
def __init__(self, ft232h, address, clock_hz=100000):
"""Create an instance of the I2C device at the specified address on the
specified I2C bus number."""
self._address = address
self._ft232h = ft232h
# Enable clock with three phases for I2C.
self._ft232h.mpsse_set_clock(clock_hz, three_phase=True)
# Enable drive-zero mode to drive outputs low on 0 and tri-state on 1.
# This matches the protocol for I2C communication so multiple devices can
# share the I2C bus.
self._ft232h._write('\x9E\x07\x00')
self._idle()
def _idle(self):
"""Put I2C lines into idle state."""
# Put the I2C lines into an idle state with SCL and SDA high.
self._ft232h.setup_pins({0: GPIO.OUT, 1: GPIO.OUT, 2: GPIO.IN},
{0: GPIO.HIGH, 1: GPIO.HIGH})
def _transaction_start(self):
"""Start I2C transaction."""
# Clear command buffer and expected response bytes.
self._command = []
self._expected = 0
def _transaction_end(self):
"""End I2C transaction and get response bytes, including ACKs."""
# Ask to return response bytes immediately.
self._command.append('\x87')
# Send the entire command to the MPSSE.
self._ft232h._write(''.join(self._command))
# Read response bytes and return them.
return bytearray(self._ft232h._poll_read(self._expected))
def _i2c_start(self):
"""Send I2C start signal. Must be called within a transaction start/end.
"""
# Set SCL high and SDA low, repeat 4 times to stay in this state for a
# short period of time.
self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.LOW}, write=False)
self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
# Now drop SCL to low (again repeat 4 times for short delay).
self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.LOW}, write=False)
self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
def _i2c_idle(self):
"""Set I2C signals to idle state with SCL and SDA at a high value. Must
be called within a transaction start/end.
"""
self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.HIGH}, write=False)
self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
def _i2c_stop(self):
"""Send I2C stop signal. Must be called within a transaction start/end.
"""
# Set SCL low and SDA low for a short period.
self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.LOW}, write=False)
self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
# Set SCL high and SDA low for a short period.
self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.LOW}, write=False)
self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
# Finally set SCL high and SDA high for a short period.
self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.HIGH}, write=False)
self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
def _i2c_read_bytes(self, length=1):
"""Read the specified number of bytes from the I2C bus. Length is the
number of bytes to read (must be 1 or more).
"""
for i in range(length-1):
# Read a byte and send ACK.
self._command.append('\x20\x00\x00\x13\x00\x00')
# Make sure pins are back in idle state with clock low and data high.
self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)
self._command.append(self._ft232h.mpsse_gpio())
# Read last byte and send NAK.
self._command.append('\x20\x00\x00\x13\x00\xFF')
# Make sure pins are back in idle state with clock low and data high.
self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)
self._command.append(self._ft232h.mpsse_gpio())
# Increase expected number of bytes.
self._expected += length
def _i2c_write_bytes(self, data):
"""Write the specified number of bytes to the chip."""
for byte in data:
# Write byte.
self._command.append(str(bytearray((0x11, 0x00, 0x00, byte))))
# Make sure pins are back in idle state with clock low and data high.
self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)
self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
# Read bit for ACK/NAK.
self._command.append('\x22\x00')
# Increase expected response bytes.
self._expected += len(data)
def _address_byte(self, read=True):
"""Return the address byte with the specified R/W bit set. If read is
True the R/W bit will be 1, otherwise the R/W bit will be 0.
"""
if read:
return (self._address << 1) | 0x01
else:
return self._address << 1
def _verify_acks(self, response):
"""Check all the specified bytes have the ACK bit set. Throws a
RuntimeError exception if not all the ACKs are set.
"""
for byte in response:
if byte & 0x01 != 0x00:
raise RuntimeError('Failed to find expected I2C ACK!')
def ping(self):
"""Attempt to detect if a device at this address is present on the I2C
bus. Will send out the device's address for writing and verify an ACK
is received. Returns true if the ACK is received, and false if not.
"""
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(False)])
self._i2c_stop()
response = self._transaction_end()
if len(response) != 1:
raise RuntimeError('Expected 1 response byte but received {0} byte(s).'.format(len(response)))
return ((response[0] & 0x01) == 0x00)
def writeRaw8(self, value):
"""Write an 8-bit value on the bus (without register)."""
value = value & 0xFF
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(False), value])
self._i2c_stop()
response = self._transaction_end()
self._verify_acks(response)
def write8(self, register, value):
"""Write an 8-bit value to the specified register."""
value = value & 0xFF
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(False), register, value])
self._i2c_stop()
response = self._transaction_end()
self._verify_acks(response)
def write16(self, register, value, little_endian=True):
"""Write a 16-bit value to the specified register."""
value = value & 0xFFFF
value_low = value & 0xFF
value_high = (value >> 8) & 0xFF
if not little_endian:
value_low, value_high = value_high, value_low
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(False), register, value_low,
value_high])
self._i2c_stop()
response = self._transaction_end()
self._verify_acks(response)
def writeList(self, register, data):
"""Write bytes to the specified register."""
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(False), register] + data)
self._i2c_stop()
response = self._transaction_end()
self._verify_acks(response)
def readList(self, register, length):
"""Read a length number of bytes from the specified register. Results
will be returned as a bytearray."""
if length <= 0:
raise ValueError("Length must be at least 1 byte.")
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(True), register])
self._i2c_stop()
self._i2c_idle()
self._i2c_start()
self._i2c_read_bytes(length)
self._i2c_stop()
response = self._transaction_end()
self._verify_acks(response[:-length])
return response[-length:]
def readRaw8(self):
"""Read an 8-bit value on the bus (without register)."""
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(False)])
self._i2c_stop()
self._i2c_idle()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(True)])
self._i2c_read_bytes(1)
self._i2c_stop()
response = self._transaction_end()
self._verify_acks(response[:-1])
return response[-1]
def readU8(self, register):
"""Read an unsigned byte from the specified register."""
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(False), register])
self._i2c_stop()
self._i2c_idle()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(True)])
self._i2c_read_bytes(1)
self._i2c_stop()
response = self._transaction_end()
self._verify_acks(response[:-1])
return response[-1]
def readS8(self, register):
"""Read a signed byte from the specified register."""
result = self.readU8(register)
if result > 127:
result -= 256
return result
def readU16(self, register, little_endian=True):
"""Read an unsigned 16-bit value from the specified register, with the
specified endianness (default little endian, or least significant byte
first)."""
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(False), register])
self._i2c_stop()
self._i2c_idle()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(True)])
self._i2c_read_bytes(2)
self._i2c_stop()
response = self._transaction_end()
self._verify_acks(response[:-2])
if little_endian:
return (response[-1] << 8) | response[-2]
else:
return (response[-2] << 8) | response[-1]
def readS16(self, register, little_endian=True):
"""Read a signed 16-bit value from the specified register, with the
specified endianness (default little endian, or least significant byte
first)."""
result = self.readU16(register, little_endian)
if result > 32767:
result -= 65536
return result
def readU16LE(self, register):
"""Read an unsigned 16-bit value from the specified register, in little
endian byte order."""
return self.readU16(register, little_endian=True)
def readU16BE(self, register):
"""Read an unsigned 16-bit value from the specified register, in big
endian byte order."""
return self.readU16(register, little_endian=False)
def readS16LE(self, register):
"""Read a signed 16-bit value from the specified register, in little
endian byte order."""
return self.readS16(register, little_endian=True)
def readS16BE(self, register):
"""Read a signed 16-bit value from the specified register, in big
endian byte order."""
return self.readS16(register, little_endian=False) | Adafruit-GPIO | /Adafruit_GPIO-1.0.3.tar.gz/Adafruit_GPIO-1.0.3/Adafruit_GPIO/FT232H.py | FT232H.py |
# 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.
import platform
import re
# Platform identification constants.
UNKNOWN = 0
RASPBERRY_PI = 1
BEAGLEBONE_BLACK = 2
MINNOWBOARD = 3
def platform_detect():
"""Detect if running on the Raspberry Pi or Beaglebone Black and return the
platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN."""
# Handle Raspberry Pi
pi = pi_version()
if pi is not None:
return RASPBERRY_PI
# Handle Beaglebone Black
# TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading
# the platform.
plat = platform.platform()
if plat.lower().find('armv7l-with-debian') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-ubuntu') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-glibc2.4') > -1:
return BEAGLEBONE_BLACK
# Handle Minnowboard
# Assumption is that mraa is installed
try:
import mraa
if mraa.getPlatformName()=='MinnowBoard MAX':
return MINNOWBOARD
except ImportError:
pass
# Couldn't figure out the platform, just return unknown.
return UNKNOWN
def pi_revision():
"""Detect the revision number of a Raspberry Pi, useful for changing
functionality like default I2C bus based on revision."""
# Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History
with open('/proc/cpuinfo', 'r') as infile:
for line in infile:
# Match a line of the form "Revision : 0002" while ignoring extra
# info in front of the revsion (like 1000 when the Pi was over-volted).
match = re.match('Revision\s+:\s+.*(\w{4})$', line, flags=re.IGNORECASE)
if match and match.group(1) in ['0000', '0002', '0003']:
# Return revision 1 if revision ends with 0000, 0002 or 0003.
return 1
elif match:
# Assume revision 2 if revision ends with any other 4 chars.
return 2
# Couldn't find the revision, throw an exception.
raise RuntimeError('Could not determine Raspberry Pi revision.')
def pi_version():
"""Detect the version of the Raspberry Pi. Returns either 1, 2 or
None depending on if it's a Raspberry Pi 1 (model A, B, A+, B+),
Raspberry Pi 2 (model B+), or not a Raspberry Pi.
"""
# Check /proc/cpuinfo for the Hardware field value.
# 2708 is pi 1
# 2709 is pi 2
# 2835 is pi 3 on 4.9.x kernel
# Anything else is not a pi.
with open('/proc/cpuinfo', 'r') as infile:
cpuinfo = infile.read()
# Match a line like 'Hardware : BCM2709'
match = re.search('^Hardware\s+:\s+(\w+)$', cpuinfo,
flags=re.MULTILINE | re.IGNORECASE)
if not match:
# Couldn't find the hardware, assume it isn't a pi.
return None
if match.group(1) == 'BCM2708':
# Pi 1
return 1
elif match.group(1) == 'BCM2709':
# Pi 2
return 2
elif match.group(1) == 'BCM2835':
# Pi 3 / Pi on 4.9.x kernel
return 3
else:
# Something else, not a pi.
return None | Adafruit-GPIO | /Adafruit_GPIO-1.0.3.tar.gz/Adafruit_GPIO-1.0.3/Adafruit_GPIO/Platform.py | Platform.py |
import Adafruit_GPIO.Platform as Platform
class RPi_PWM_Adapter(object):
"""PWM implementation for the Raspberry Pi using the RPi.GPIO PWM library."""
def __init__(self, rpi_gpio, mode=None):
self.rpi_gpio = rpi_gpio
# Suppress warnings about GPIO in use.
rpi_gpio.setwarnings(False)
# Set board or BCM pin numbering.
if mode == rpi_gpio.BOARD or mode == rpi_gpio.BCM:
rpi_gpio.setmode(mode)
elif mode is not None:
raise ValueError('Unexpected value for mode. Must be BOARD or BCM.')
else:
# Default to BCM numbering if not told otherwise.
rpi_gpio.setmode(rpi_gpio.BCM)
# Store reference to each created PWM instance.
self.pwm = {}
def start(self, pin, dutycycle, frequency_hz=2000):
"""Enable PWM output on specified pin. Set to intiial percent duty cycle
value (0.0 to 100.0) and frequency (in Hz).
"""
if dutycycle < 0.0 or dutycycle > 100.0:
raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inclusive).')
# Make pin an output.
self.rpi_gpio.setup(pin, self.rpi_gpio.OUT)
# Create PWM instance and save a reference for later access.
self.pwm[pin] = self.rpi_gpio.PWM(pin, frequency_hz)
# Start the PWM at the specified duty cycle.
self.pwm[pin].start(dutycycle)
def set_duty_cycle(self, pin, dutycycle):
"""Set percent duty cycle of PWM output on specified pin. Duty cycle must
be a value 0.0 to 100.0 (inclusive).
"""
if dutycycle < 0.0 or dutycycle > 100.0:
raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inclusive).')
if pin not in self.pwm:
raise ValueError('Pin {0} is not configured as a PWM. Make sure to first call start for the pin.'.format(pin))
self.pwm[pin].ChangeDutyCycle(dutycycle)
def set_frequency(self, pin, frequency_hz):
"""Set frequency (in Hz) of PWM output on specified pin."""
if pin not in self.pwm:
raise ValueError('Pin {0} is not configured as a PWM. Make sure to first call start for the pin.'.format(pin))
self.pwm[pin].ChangeFrequency(frequency_hz)
def stop(self, pin):
"""Stop PWM output on specified pin."""
if pin not in self.pwm:
raise ValueError('Pin {0} is not configured as a PWM. Make sure to first call start for the pin.'.format(pin))
self.pwm[pin].stop()
del self.pwm[pin]
class BBIO_PWM_Adapter(object):
"""PWM implementation for the BeagleBone Black using the Adafruit_BBIO.PWM
library.
"""
def __init__(self, bbio_pwm):
self.bbio_pwm = bbio_pwm
def start(self, pin, dutycycle, frequency_hz=2000):
"""Enable PWM output on specified pin. Set to intiial percent duty cycle
value (0.0 to 100.0) and frequency (in Hz).
"""
if dutycycle < 0.0 or dutycycle > 100.0:
raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inclusive).')
self.bbio_pwm.start(pin, dutycycle, frequency_hz)
def set_duty_cycle(self, pin, dutycycle):
"""Set percent duty cycle of PWM output on specified pin. Duty cycle must
be a value 0.0 to 100.0 (inclusive).
"""
if dutycycle < 0.0 or dutycycle > 100.0:
raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inclusive).')
self.bbio_pwm.set_duty_cycle(pin, dutycycle)
def set_frequency(self, pin, frequency_hz):
"""Set frequency (in Hz) of PWM output on specified pin."""
self.bbio_pwm.set_frequency(pin, frequency_hz)
def stop(self, pin):
"""Stop PWM output on specified pin."""
self.bbio_pwm.stop(pin)
def get_platform_pwm(**keywords):
"""Attempt to return a PWM instance for the platform which the code is being
executed on. Currently supports only the Raspberry Pi using the RPi.GPIO
library and Beaglebone Black using the Adafruit_BBIO library. Will throw an
exception if a PWM instance can't be created for the current platform. The
returned PWM object has the same interface as the RPi_PWM_Adapter and
BBIO_PWM_Adapter classes.
"""
plat = Platform.platform_detect()
if plat == Platform.RASPBERRY_PI:
import RPi.GPIO
return RPi_PWM_Adapter(RPi.GPIO, **keywords)
elif plat == Platform.BEAGLEBONE_BLACK:
import Adafruit_BBIO.PWM
return BBIO_PWM_Adapter(Adafruit_BBIO.PWM, **keywords)
elif plat == Platform.UNKNOWN:
raise RuntimeError('Could not determine platform.') | Adafruit-GPIO | /Adafruit_GPIO-1.0.3.tar.gz/Adafruit_GPIO-1.0.3/Adafruit_GPIO/PWM.py | PWM.py |
import Adafruit_GPIO.Platform as Platform
OUT = 0
IN = 1
HIGH = True
LOW = False
RISING = 1
FALLING = 2
BOTH = 3
PUD_OFF = 0
PUD_DOWN = 1
PUD_UP = 2
class BaseGPIO(object):
"""Base class for implementing simple digital IO for a platform.
Implementors are expected to subclass from this and provide an implementation
of the setup, output, and input functions."""
def setup(self, pin, mode, pull_up_down=PUD_OFF):
"""Set the input or output mode for a specified pin. Mode should be
either OUT or IN."""
raise NotImplementedError
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high)."""
raise NotImplementedError
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low."""
raise NotImplementedError
def set_high(self, pin):
"""Set the specified pin HIGH."""
self.output(pin, HIGH)
def set_low(self, pin):
"""Set the specified pin LOW."""
self.output(pin, LOW)
def is_high(self, pin):
"""Return true if the specified pin is pulled high."""
return self.input(pin) == HIGH
def is_low(self, pin):
"""Return true if the specified pin is pulled low."""
return self.input(pin) == LOW
# Basic implementation of multiple pin methods just loops through pins and
# processes each one individually. This is not optimal, but derived classes can
# provide a more optimal implementation that deals with groups of pins
# simultaneously.
# See MCP230xx or PCF8574 classes for examples of optimized implementations.
def output_pins(self, pins):
"""Set multiple pins high or low at once. Pins should be a dict of pin
name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins
will be set to the given values.
"""
# General implementation just loops through pins and writes them out
# manually. This is not optimized, but subclasses can choose to implement
# a more optimal batch output implementation. See the MCP230xx class for
# example of optimized implementation.
for pin, value in iter(pins.items()):
self.output(pin, value)
def setup_pins(self, pins):
"""Setup multiple pins as inputs or outputs at once. Pins should be a
dict of pin name to pin type (IN or OUT).
"""
# General implementation that can be optimized by derived classes.
for pin, value in iter(pins.items()):
self.setup(pin, value)
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
"""
# General implementation that can be optimized by derived classes.
return [self.input(pin) for pin in pins]
def add_event_detect(self, pin, edge):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH.
"""
raise NotImplementedError
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
raise NotImplementedError
def add_event_callback(self, pin, callback):
"""Add a callback for an event already defined using add_event_detect().
Pin should be type IN.
"""
raise NotImplementedError
def event_detected(self, pin):
"""Returns True if an edge has occured on a given GPIO. You need to
enable edge detection using add_event_detect() first. Pin should be
type IN.
"""
raise NotImplementedError
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH."""
raise NotImplementedError
def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
raise NotImplementedError
# helper functions useful to derived classes
def _validate_pin(self, pin):
# Raise an exception if pin is outside the range of allowed values.
if pin < 0 or pin >= self.NUM_GPIO:
raise ValueError('Invalid GPIO value, must be between 0 and {0}.'.format(self.NUM_GPIO))
def _bit2(self, src, bit, val):
bit = 1 << bit
return (src | bit) if val else (src & ~bit)
class RPiGPIOAdapter(BaseGPIO):
"""GPIO implementation for the Raspberry Pi using the RPi.GPIO library."""
def __init__(self, rpi_gpio, mode=None):
self.rpi_gpio = rpi_gpio
# Suppress warnings about GPIO in use.
rpi_gpio.setwarnings(False)
# Setup board pin mode.
if mode == rpi_gpio.BOARD or mode == rpi_gpio.BCM:
rpi_gpio.setmode(mode)
elif mode is not None:
raise ValueError('Unexpected value for mode. Must be BOARD or BCM.')
else:
# Default to BCM numbering if not told otherwise.
rpi_gpio.setmode(rpi_gpio.BCM)
# Define mapping of Adafruit GPIO library constants to RPi.GPIO constants.
self._dir_mapping = { OUT: rpi_gpio.OUT,
IN: rpi_gpio.IN }
self._pud_mapping = { PUD_OFF: rpi_gpio.PUD_OFF,
PUD_DOWN: rpi_gpio.PUD_DOWN,
PUD_UP: rpi_gpio.PUD_UP }
self._edge_mapping = { RISING: rpi_gpio.RISING,
FALLING: rpi_gpio.FALLING,
BOTH: rpi_gpio.BOTH }
def setup(self, pin, mode, pull_up_down=PUD_OFF):
"""Set the input or output mode for a specified pin. Mode should be
either OUTPUT or INPUT.
"""
self.rpi_gpio.setup(pin, self._dir_mapping[mode],
pull_up_down=self._pud_mapping[pull_up_down])
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high).
"""
self.rpi_gpio.output(pin, value)
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low.
"""
return self.rpi_gpio.input(pin)
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
"""
# maybe rpi has a mass read... it would be more efficient to use it if it exists
return [self.rpi_gpio.input(pin) for pin in pins]
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a
function for the event. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if callback:
kwargs['callback']=callback
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.rpi_gpio.add_event_detect(pin, self._edge_mapping[edge], **kwargs)
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
self.rpi_gpio.remove_event_detect(pin)
def add_event_callback(self, pin, callback):
"""Add a callback for an event already defined using add_event_detect().
Pin should be type IN.
"""
self.rpi_gpio.add_event_callback(pin, callback)
def event_detected(self, pin):
"""Returns True if an edge has occured on a given GPIO. You need to
enable edge detection using add_event_detect() first. Pin should be
type IN.
"""
return self.rpi_gpio.event_detected(pin)
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH.
"""
self.rpi_gpio.wait_for_edge(pin, self._edge_mapping[edge])
def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
if pin is None:
self.rpi_gpio.cleanup()
else:
self.rpi_gpio.cleanup(pin)
class AdafruitBBIOAdapter(BaseGPIO):
"""GPIO implementation for the Beaglebone Black using the Adafruit_BBIO
library.
"""
def __init__(self, bbio_gpio):
self.bbio_gpio = bbio_gpio
# Define mapping of Adafruit GPIO library constants to RPi.GPIO constants.
self._dir_mapping = { OUT: bbio_gpio.OUT,
IN: bbio_gpio.IN }
self._pud_mapping = { PUD_OFF: bbio_gpio.PUD_OFF,
PUD_DOWN: bbio_gpio.PUD_DOWN,
PUD_UP: bbio_gpio.PUD_UP }
self._edge_mapping = { RISING: bbio_gpio.RISING,
FALLING: bbio_gpio.FALLING,
BOTH: bbio_gpio.BOTH }
def setup(self, pin, mode, pull_up_down=PUD_OFF):
"""Set the input or output mode for a specified pin. Mode should be
either OUTPUT or INPUT.
"""
self.bbio_gpio.setup(pin, self._dir_mapping[mode],
pull_up_down=self._pud_mapping[pull_up_down])
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high).
"""
self.bbio_gpio.output(pin, value)
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low.
"""
return self.bbio_gpio.input(pin)
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
"""
# maybe bbb has a mass read... it would be more efficient to use it if it exists
return [self.bbio_gpio.input(pin) for pin in pins]
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a
function for the event. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if callback:
kwargs['callback']=callback
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.bbio_gpio.add_event_detect(pin, self._edge_mapping[edge], **kwargs)
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
self.bbio_gpio.remove_event_detect(pin)
def add_event_callback(self, pin, callback, bouncetime=-1):
"""Add a callback for an event already defined using add_event_detect().
Pin should be type IN. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.bbio_gpio.add_event_callback(pin, callback, **kwargs)
def event_detected(self, pin):
"""Returns True if an edge has occured on a given GPIO. You need to
enable edge detection using add_event_detect() first. Pin should be
type IN.
"""
return self.bbio_gpio.event_detected(pin)
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH.
"""
self.bbio_gpio.wait_for_edge(pin, self._edge_mapping[edge])
def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
if pin is None:
self.bbio_gpio.cleanup()
else:
self.bbio_gpio.cleanup(pin)
class AdafruitMinnowAdapter(BaseGPIO):
"""GPIO implementation for the Minnowboard + MAX using the mraa library"""
def __init__(self,mraa_gpio):
self.mraa_gpio = mraa_gpio
# Define mapping of Adafruit GPIO library constants to mraa constants
self._dir_mapping = { OUT: self.mraa_gpio.DIR_OUT,
IN: self.mraa_gpio.DIR_IN }
self._pud_mapping = { PUD_OFF: self.mraa_gpio.MODE_STRONG,
PUD_UP: self.mraa_gpio.MODE_HIZ,
PUD_DOWN: self.mraa_gpio.MODE_PULLDOWN }
self._edge_mapping = { RISING: self.mraa_gpio.EDGE_RISING,
FALLING: self.mraa_gpio.EDGE_FALLING,
BOTH: self.mraa_gpio.EDGE_BOTH }
def setup(self,pin,mode):
"""Set the input or output mode for a specified pin. Mode should be
either DIR_IN or DIR_OUT.
"""
self.mraa_gpio.Gpio.dir(self.mraa_gpio.Gpio(pin),self._dir_mapping[mode])
def output(self,pin,value):
"""Set the specified pin the provided high/low value. Value should be
either 1 (ON or HIGH), or 0 (OFF or LOW) or a boolean.
"""
self.mraa_gpio.Gpio.write(self.mraa_gpio.Gpio(pin), value)
def input(self,pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low.
"""
return self.mraa_gpio.Gpio.read(self.mraa_gpio.Gpio(pin))
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a
function for the event. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if callback:
kwargs['callback']=callback
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.mraa_gpio.Gpio.isr(self.mraa_gpio.Gpio(pin), self._edge_mapping[edge], **kwargs)
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
self.mraa_gpio.Gpio.isrExit(self.mraa_gpio.Gpio(pin))
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH.
"""
self.bbio_gpio.wait_for_edge(self.mraa_gpio.Gpio(pin), self._edge_mapping[edge])
def get_platform_gpio(**keywords):
"""Attempt to return a GPIO instance for the platform which the code is being
executed on. Currently supports only the Raspberry Pi using the RPi.GPIO
library and Beaglebone Black using the Adafruit_BBIO library. Will throw an
exception if a GPIO instance can't be created for the current platform. The
returned GPIO object is an instance of BaseGPIO.
"""
plat = Platform.platform_detect()
if plat == Platform.RASPBERRY_PI:
import RPi.GPIO
return RPiGPIOAdapter(RPi.GPIO, **keywords)
elif plat == Platform.BEAGLEBONE_BLACK:
import Adafruit_BBIO.GPIO
return AdafruitBBIOAdapter(Adafruit_BBIO.GPIO, **keywords)
elif plat == Platform.MINNOWBOARD:
import mraa
return AdafruitMinnowAdapter(mraa, **keywords)
elif plat == Platform.UNKNOWN:
raise RuntimeError('Could not determine platform.') | Adafruit-GPIO | /Adafruit_GPIO-1.0.3.tar.gz/Adafruit_GPIO-1.0.3/Adafruit_GPIO/GPIO.py | GPIO.py |
import operator
import time
import Adafruit_GPIO as GPIO
MSBFIRST = 0
LSBFIRST = 1
class SpiDev(object):
"""Hardware-based SPI implementation using the spidev interface."""
def __init__(self, port, device, max_speed_hz=500000):
"""Initialize an SPI device using the SPIdev interface. Port and device
identify the device, for example the device /dev/spidev1.0 would be port
1 and device 0.
"""
import spidev
self._device = spidev.SpiDev()
self._device.open(port, device)
self._device.max_speed_hz=max_speed_hz
# Default to mode 0.
self._device.mode = 0
def set_clock_hz(self, hz):
"""Set the speed of the SPI clock in hertz. Note that not all speeds
are supported and a lower speed might be chosen by the hardware.
"""
self._device.max_speed_hz=hz
def set_mode(self, mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise ValueError('Mode must be a value 0, 1, 2, or 3.')
self._device.mode = mode
def set_bit_order(self, order):
"""Set order of bits to be read/written over serial lines. Should be
either MSBFIRST for most-significant first, or LSBFIRST for
least-signifcant first.
"""
if order == MSBFIRST:
self._device.lsbfirst = False
elif order == LSBFIRST:
self._device.lsbfirst = True
else:
raise ValueError('Order must be MSBFIRST or LSBFIRST.')
def close(self):
"""Close communication with the SPI device."""
self._device.close()
def write(self, data):
"""Half-duplex SPI write. The specified array of bytes will be clocked
out the MOSI line.
"""
self._device.writebytes(data)
def read(self, length):
"""Half-duplex SPI read. The specified length of bytes will be clocked
in the MISO line and returned as a bytearray object.
"""
return bytearray(self._device.readbytes(length))
def transfer(self, data):
"""Full-duplex SPI read and write. The specified array of bytes will be
clocked out the MOSI line, while simultaneously bytes will be read from
the MISO line. Read bytes will be returned as a bytearray object.
"""
return bytearray(self._device.xfer2(data))
class SpiDevMraa(object):
"""Hardware SPI implementation with the mraa library on Minnowboard"""
def __init__(self, port, device, max_speed_hz=500000):
import mraa
self._device = mraa.Spi(0)
self._device.mode(0)
def set_clock_hz(self, hz):
"""Set the speed of the SPI clock in hertz. Note that not all speeds
are supported and a lower speed might be chosen by the hardware.
"""
self._device.frequency(hz)
def set_mode(self,mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise ValueError('Mode must be a value 0, 1, 2, or 3.')
self._device.mode(mode)
def set_mode(self,mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise ValueError('Mode must be a value 0, 1, 2, or 3.')
self._device.mode(mode)
def set_bit_order(self, order):
"""Set order of bits to be read/written over serial lines. Should be
either MSBFIRST for most-significant first, or LSBFIRST for
least-signifcant first.
"""
if order == MSBFIRST:
self._device.lsbmode(False)
elif order == LSBFIRST:
self._device.lsbmode(True)
else:
raise ValueError('Order must be MSBFIRST or LSBFIRST.')
def close(self):
"""Close communication with the SPI device."""
self._device.Spi()
def write(self, data):
"""Half-duplex SPI write. The specified array of bytes will be clocked
out the MOSI line.
"""
self._device.write(bytearray(data))
class BitBang(object):
"""Software-based implementation of the SPI protocol over GPIO pins."""
def __init__(self, gpio, sclk, mosi=None, miso=None, ss=None):
"""Initialize bit bang (or software) based SPI. Must provide a BaseGPIO
class, the SPI clock, and optionally MOSI, MISO, and SS (slave select)
pin numbers. If MOSI is set to None then writes will be disabled and fail
with an error, likewise for MISO reads will be disabled. If SS is set to
None then SS will not be asserted high/low by the library when
transfering data.
"""
self._gpio = gpio
self._sclk = sclk
self._mosi = mosi
self._miso = miso
self._ss = ss
# Set pins as outputs/inputs.
gpio.setup(sclk, GPIO.OUT)
if mosi is not None:
gpio.setup(mosi, GPIO.OUT)
if miso is not None:
gpio.setup(miso, GPIO.IN)
if ss is not None:
gpio.setup(ss, GPIO.OUT)
# Assert SS high to start with device communication off.
gpio.set_high(ss)
# Assume mode 0.
self.set_mode(0)
# Assume most significant bit first order.
self.set_bit_order(MSBFIRST)
def set_clock_hz(self, hz):
"""Set the speed of the SPI clock. This is unsupported with the bit
bang SPI class and will be ignored.
"""
pass
def set_mode(self, mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise ValueError('Mode must be a value 0, 1, 2, or 3.')
if mode & 0x02:
# Clock is normally high in mode 2 and 3.
self._clock_base = GPIO.HIGH
else:
# Clock is normally low in mode 0 and 1.
self._clock_base = GPIO.LOW
if mode & 0x01:
# Read on trailing edge in mode 1 and 3.
self._read_leading = False
else:
# Read on leading edge in mode 0 and 2.
self._read_leading = True
# Put clock into its base state.
self._gpio.output(self._sclk, self._clock_base)
def set_bit_order(self, order):
"""Set order of bits to be read/written over serial lines. Should be
either MSBFIRST for most-significant first, or LSBFIRST for
least-signifcant first.
"""
# Set self._mask to the bitmask which points at the appropriate bit to
# read or write, and appropriate left/right shift operator function for
# reading/writing.
if order == MSBFIRST:
self._mask = 0x80
self._write_shift = operator.lshift
self._read_shift = operator.rshift
elif order == LSBFIRST:
self._mask = 0x01
self._write_shift = operator.rshift
self._read_shift = operator.lshift
else:
raise ValueError('Order must be MSBFIRST or LSBFIRST.')
def close(self):
"""Close the SPI connection. Unused in the bit bang implementation."""
pass
def write(self, data, assert_ss=True, deassert_ss=True):
"""Half-duplex SPI write. If assert_ss is True, the SS line will be
asserted low, the specified bytes will be clocked out the MOSI line, and
if deassert_ss is True the SS line be put back high.
"""
# Fail MOSI is not specified.
if self._mosi is None:
raise RuntimeError('Write attempted with no MOSI pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
for byte in data:
for i in range(8):
# Write bit to MOSI.
if self._write_shift(byte, i) & self._mask:
self._gpio.set_high(self._mosi)
else:
self._gpio.set_low(self._mosi)
# Flip clock off base.
self._gpio.output(self._sclk, not self._clock_base)
# Return clock to base.
self._gpio.output(self._sclk, self._clock_base)
if deassert_ss and self._ss is not None:
self._gpio.set_high(self._ss)
def read(self, length, assert_ss=True, deassert_ss=True):
"""Half-duplex SPI read. If assert_ss is true, the SS line will be
asserted low, the specified length of bytes will be clocked in the MISO
line, and if deassert_ss is true the SS line will be put back high.
Bytes which are read will be returned as a bytearray object.
"""
if self._miso is None:
raise RuntimeError('Read attempted with no MISO pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
result = bytearray(length)
for i in range(length):
for j in range(8):
# Flip clock off base.
self._gpio.output(self._sclk, not self._clock_base)
# Handle read on leading edge of clock.
if self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
# Return clock to base.
self._gpio.output(self._sclk, self._clock_base)
# Handle read on trailing edge of clock.
if not self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
if deassert_ss and self._ss is not None:
self._gpio.set_high(self._ss)
return result
def transfer(self, data, assert_ss=True, deassert_ss=True):
"""Full-duplex SPI read and write. If assert_ss is true, the SS line
will be asserted low, the specified bytes will be clocked out the MOSI
line while bytes will also be read from the MISO line, and if
deassert_ss is true the SS line will be put back high. Bytes which are
read will be returned as a bytearray object.
"""
if self._mosi is None:
raise RuntimeError('Write attempted with no MOSI pin specified.')
if self._mosi is None:
raise RuntimeError('Read attempted with no MISO pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
result = bytearray(len(data))
for i in range(len(data)):
for j in range(8):
# Write bit to MOSI.
if self._write_shift(data[i], j) & self._mask:
self._gpio.set_high(self._mosi)
else:
self._gpio.set_low(self._mosi)
# Flip clock off base.
self._gpio.output(self._sclk, not self._clock_base)
# Handle read on leading edge of clock.
if self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
# Return clock to base.
self._gpio.output(self._sclk, self._clock_base)
# Handle read on trailing edge of clock.
if not self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
if deassert_ss and self._ss is not None:
self._gpio.set_high(self._ss)
return result | Adafruit-GPIO | /Adafruit_GPIO-1.0.3.tar.gz/Adafruit_GPIO-1.0.3/Adafruit_GPIO/SPI.py | SPI.py |
import numbers
import time
import numpy as np
from PIL import Image
from PIL import ImageDraw
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.SPI as SPI
# Constants for interacting with display registers.
ILI9341_TFTWIDTH = 240
ILI9341_TFTHEIGHT = 320
ILI9341_NOP = 0x00
ILI9341_SWRESET = 0x01
ILI9341_RDDID = 0x04
ILI9341_RDDST = 0x09
ILI9341_SLPIN = 0x10
ILI9341_SLPOUT = 0x11
ILI9341_PTLON = 0x12
ILI9341_NORON = 0x13
ILI9341_RDMODE = 0x0A
ILI9341_RDMADCTL = 0x0B
ILI9341_RDPIXFMT = 0x0C
ILI9341_RDIMGFMT = 0x0A
ILI9341_RDSELFDIAG = 0x0F
ILI9341_INVOFF = 0x20
ILI9341_INVON = 0x21
ILI9341_GAMMASET = 0x26
ILI9341_DISPOFF = 0x28
ILI9341_DISPON = 0x29
ILI9341_CASET = 0x2A
ILI9341_PASET = 0x2B
ILI9341_RAMWR = 0x2C
ILI9341_RAMRD = 0x2E
ILI9341_PTLAR = 0x30
ILI9341_MADCTL = 0x36
ILI9341_PIXFMT = 0x3A
ILI9341_FRMCTR1 = 0xB1
ILI9341_FRMCTR2 = 0xB2
ILI9341_FRMCTR3 = 0xB3
ILI9341_INVCTR = 0xB4
ILI9341_DFUNCTR = 0xB6
ILI9341_PWCTR1 = 0xC0
ILI9341_PWCTR2 = 0xC1
ILI9341_PWCTR3 = 0xC2
ILI9341_PWCTR4 = 0xC3
ILI9341_PWCTR5 = 0xC4
ILI9341_VMCTR1 = 0xC5
ILI9341_VMCTR2 = 0xC7
ILI9341_RDID1 = 0xDA
ILI9341_RDID2 = 0xDB
ILI9341_RDID3 = 0xDC
ILI9341_RDID4 = 0xDD
ILI9341_GMCTRP1 = 0xE0
ILI9341_GMCTRN1 = 0xE1
ILI9341_PWCTR6 = 0xFC
ILI9341_BLACK = 0x0000
ILI9341_BLUE = 0x001F
ILI9341_RED = 0xF800
ILI9341_GREEN = 0x07E0
ILI9341_CYAN = 0x07FF
ILI9341_MAGENTA = 0xF81F
ILI9341_YELLOW = 0xFFE0
ILI9341_WHITE = 0xFFFF
def color565(r, g, b):
"""Convert red, green, blue components to a 16-bit 565 RGB value. Components
should be values 0 to 255.
"""
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)
def image_to_data(image):
"""Generator function to convert a PIL image to 16-bit 565 RGB bytes."""
#NumPy is much faster at doing this. NumPy code provided by:
#Keith (https://www.blogger.com/profile/02555547344016007163)
pb = np.array(image.convert('RGB')).astype('uint16')
color = ((pb[:,:,0] & 0xF8) << 8) | ((pb[:,:,1] & 0xFC) << 3) | (pb[:,:,2] >> 3)
return np.dstack(((color >> 8) & 0xFF, color & 0xFF)).flatten().tolist()
class ILI9341(object):
"""Representation of an ILI9341 TFT LCD."""
def __init__(self, dc, spi, rst=None, gpio=None, width=ILI9341_TFTWIDTH,
height=ILI9341_TFTHEIGHT):
"""Create an instance of the display using SPI communication. Must
provide the GPIO pin number for the D/C pin and the SPI driver. Can
optionally provide the GPIO pin number for the reset pin as the rst
parameter.
"""
self._dc = dc
self._rst = rst
self._spi = spi
self._gpio = gpio
self.width = width
self.height = height
if self._gpio is None:
self._gpio = GPIO.get_platform_gpio()
# Set DC as output.
self._gpio.setup(dc, GPIO.OUT)
# Setup reset as output (if provided).
if rst is not None:
self._gpio.setup(rst, GPIO.OUT)
# Set SPI to mode 0, MSB first.
spi.set_mode(0)
spi.set_bit_order(SPI.MSBFIRST)
spi.set_clock_hz(64000000)
# Create an image buffer.
self.buffer = Image.new('RGB', (width, height))
def send(self, data, is_data=True, chunk_size=4096):
"""Write a byte or array of bytes to the display. Is_data parameter
controls if byte should be interpreted as display data (True) or command
data (False). Chunk_size is an optional size of bytes to write in a
single SPI transaction, with a default of 4096.
"""
# Set DC low for command, high for data.
self._gpio.output(self._dc, is_data)
# Convert scalar argument to list so either can be passed as parameter.
if isinstance(data, numbers.Number):
data = [data & 0xFF]
# Write data a chunk at a time.
for start in range(0, len(data), chunk_size):
end = min(start+chunk_size, len(data))
self._spi.write(data[start:end])
def command(self, data):
"""Write a byte or array of bytes to the display as command data."""
self.send(data, False)
def data(self, data):
"""Write a byte or array of bytes to the display as display data."""
self.send(data, True)
def reset(self):
"""Reset the display, if reset pin is connected."""
if self._rst is not None:
self._gpio.set_high(self._rst)
time.sleep(0.005)
self._gpio.set_low(self._rst)
time.sleep(0.02)
self._gpio.set_high(self._rst)
time.sleep(0.150)
def _init(self):
# Initialize the display. Broken out as a separate function so it can
# be overridden by other displays in the future.
self.command(0xEF)
self.data(0x03)
self.data(0x80)
self.data(0x02)
self.command(0xCF)
self.data(0x00)
self.data(0XC1)
self.data(0X30)
self.command(0xED)
self.data(0x64)
self.data(0x03)
self.data(0X12)
self.data(0X81)
self.command(0xE8)
self.data(0x85)
self.data(0x00)
self.data(0x78)
self.command(0xCB)
self.data(0x39)
self.data(0x2C)
self.data(0x00)
self.data(0x34)
self.data(0x02)
self.command(0xF7)
self.data(0x20)
self.command(0xEA)
self.data(0x00)
self.data(0x00)
self.command(ILI9341_PWCTR1) # Power control
self.data(0x23) # VRH[5:0]
self.command(ILI9341_PWCTR2) # Power control
self.data(0x10) # SAP[2:0];BT[3:0]
self.command(ILI9341_VMCTR1) # VCM control
self.data(0x3e)
self.data(0x28)
self.command(ILI9341_VMCTR2) # VCM control2
self.data(0x86) # --
self.command(ILI9341_MADCTL) # Memory Access Control
self.data(0x48)
self.command(ILI9341_PIXFMT)
self.data(0x55)
self.command(ILI9341_FRMCTR1)
self.data(0x00)
self.data(0x18)
self.command(ILI9341_DFUNCTR) # Display Function Control
self.data(0x08)
self.data(0x82)
self.data(0x27)
self.command(0xF2) # 3Gamma Function Disable
self.data(0x00)
self.command(ILI9341_GAMMASET) # Gamma curve selected
self.data(0x01)
self.command(ILI9341_GMCTRP1) # Set Gamma
self.data(0x0F)
self.data(0x31)
self.data(0x2B)
self.data(0x0C)
self.data(0x0E)
self.data(0x08)
self.data(0x4E)
self.data(0xF1)
self.data(0x37)
self.data(0x07)
self.data(0x10)
self.data(0x03)
self.data(0x0E)
self.data(0x09)
self.data(0x00)
self.command(ILI9341_GMCTRN1) # Set Gamma
self.data(0x00)
self.data(0x0E)
self.data(0x14)
self.data(0x03)
self.data(0x11)
self.data(0x07)
self.data(0x31)
self.data(0xC1)
self.data(0x48)
self.data(0x08)
self.data(0x0F)
self.data(0x0C)
self.data(0x31)
self.data(0x36)
self.data(0x0F)
self.command(ILI9341_SLPOUT) # Exit Sleep
time.sleep(0.120)
self.command(ILI9341_DISPON) # Display on
def begin(self):
"""Initialize the display. Should be called once before other calls that
interact with the display are called.
"""
self.reset()
self._init()
def set_window(self, x0=0, y0=0, x1=None, y1=None):
"""Set the pixel address window for proceeding drawing commands. x0 and
x1 should define the minimum and maximum x pixel bounds. y0 and y1
should define the minimum and maximum y pixel bound. If no parameters
are specified the default will be to update the entire display from 0,0
to 239,319.
"""
if x1 is None:
x1 = self.width-1
if y1 is None:
y1 = self.height-1
self.command(ILI9341_CASET) # Column addr set
self.data(x0 >> 8)
self.data(x0) # XSTART
self.data(x1 >> 8)
self.data(x1) # XEND
self.command(ILI9341_PASET) # Row addr set
self.data(y0 >> 8)
self.data(y0) # YSTART
self.data(y1 >> 8)
self.data(y1) # YEND
self.command(ILI9341_RAMWR) # write to RAM
def display(self, image=None):
"""Write the display buffer or provided image to the hardware. If no
image parameter is provided the display buffer will be written to the
hardware. If an image is provided, it should be RGB format and the
same dimensions as the display hardware.
"""
# By default write the internal buffer to the display.
if image is None:
image = self.buffer
# Set address bounds to entire display.
self.set_window()
# Convert image to array of 16bit 565 RGB data bytes.
# Unfortunate that this copy has to occur, but the SPI byte writing
# function needs to take an array of bytes and PIL doesn't natively
# store images in 16-bit 565 RGB format.
pixelbytes = list(image_to_data(image))
# Write data to hardware.
self.data(pixelbytes)
def clear(self, color=(0,0,0)):
"""Clear the image buffer to the specified RGB color (default black)."""
width, height = self.buffer.size
self.buffer.putdata([color]*(width*height))
def draw(self):
"""Return a PIL ImageDraw instance for 2D drawing on the image buffer."""
return ImageDraw.Draw(self.buffer) | Adafruit-ILI9341 | /Adafruit_ILI9341-1.5.1.tar.gz/Adafruit_ILI9341-1.5.1/Adafruit_ILI9341/ILI9341.py | ILI9341.py |
from .Matrix8x8 import Matrix8x8
# Color values as convenient globals.
# This is a bitmask value where the first bit is green, and the second bit is
# red. If both bits are set the color is yellow (red + green light).
OFF = 0
GREEN = 1
RED = 2
YELLOW = 3
class BicolorMatrix8x8(Matrix8x8):
"""Bi-color 8x8 matrix LED backpack display."""
def __init__(self, **kwargs):
"""Initialize display. All arguments will be passed to the HT16K33 class
initializer, including optional I2C address and bus number parameters.
"""
super(BicolorMatrix8x8, self).__init__(**kwargs)
def set_pixel(self, x, y, value):
"""Set pixel at position x, y to the given value. X and Y should be values
of 0 to 8. Value should be OFF, GREEN, RED, or YELLOW.
"""
if x < 0 or x > 7 or y < 0 or y > 7:
# Ignore out of bounds pixels.
return
# Set green LED based on 1st bit in value.
self.set_led(y * 16 + x, 1 if value & GREEN > 0 else 0)
# Set red LED based on 2nd bit in value.
self.set_led(y * 16 + x + 8, 1 if value & RED > 0 else 0)
def set_image(self, image):
"""Set display buffer to Python Image Library image. Red pixels (r=255,
g=0, b=0) will map to red LEDs, green pixels (r=0, g=255, b=0) will map to
green LEDs, and yellow pixels (r=255, g=255, b=0) will map to yellow LEDs.
All other pixel values will map to an unlit LED value.
"""
imwidth, imheight = image.size
if imwidth != 8 or imheight != 8:
raise ValueError('Image must be an 8x8 pixels in size.')
# Convert image to RGB and grab all the pixels.
pix = image.convert('RGB').load()
# Loop through each pixel and write the display buffer pixel.
for x in [0, 1, 2, 3, 4, 5, 6, 7]:
for y in [0, 1, 2, 3, 4, 5, 6, 7]:
color = pix[(x, y)]
# Handle the color of the pixel.
if color == (255, 0, 0):
self.set_pixel(x, y, RED)
elif color == (0, 255, 0):
self.set_pixel(x, y, GREEN)
elif color == (255, 255, 0):
self.set_pixel(x, y, YELLOW)
else:
# Unknown color, default to LED off.
self.set_pixel(x, y, OFF) | Adafruit-LED-Backpack | /Adafruit_LED_Backpack-1.8.1.tar.gz/Adafruit_LED_Backpack-1.8.1/Adafruit_LED_Backpack/BicolorMatrix8x8.py | BicolorMatrix8x8.py |
from . import HT16K33
# Digit value to bitmask mapping:
DIGIT_VALUES = {
' ': 0x00,
'-': 0x40,
'0': 0x3F,
'1': 0x06,
'2': 0x5B,
'3': 0x4F,
'4': 0x66,
'5': 0x6D,
'6': 0x7D,
'7': 0x07,
'8': 0x7F,
'9': 0x6F,
'A': 0x77,
'B': 0x7C,
'C': 0x39,
'D': 0x5E,
'E': 0x79,
'F': 0x71
}
IDIGIT_VALUES = {
' ': 0x00,
'-': 0x40,
'0': 0x3F,
'1': 0x30,
'2': 0x5B,
'3': 0x79,
'4': 0x74,
'5': 0x6D,
'6': 0x6F,
'7': 0x38,
'8': 0x7F,
'9': 0x7D,
'A': 0x7E,
'B': 0x67,
'C': 0x0F,
'D': 0x73,
'E': 0x4F,
'F': 0x4E
}
class SevenSegment(HT16K33.HT16K33):
"""Seven segment LED backpack display."""
def __init__(self, invert=False, **kwargs):
"""Initialize display. All arguments will be passed to the HT16K33 class
initializer, including optional I2C address and bus number parameters.
"""
super(SevenSegment, self).__init__(**kwargs)
self.invert = invert
def set_invert(self, _invert):
"""Set whether the display is upside-down or not.
"""
self.invert = _invert
def set_digit_raw(self, pos, bitmask):
"""Set digit at position to raw bitmask value. Position should be a value
of 0 to 3 with 0 being the left most digit on the display."""
if pos < 0 or pos > 3:
# Ignore out of bounds digits.
return
# Jump past the colon at position 2 by adding a conditional offset.
offset = 0 if pos < 2 else 1
# Calculate the correct position depending on orientation
if self.invert:
pos = 4-(pos+offset)
else:
pos = pos+offset
# Set the digit bitmask value at the appropriate position.
self.buffer[pos*2] = bitmask & 0xFF
def set_decimal(self, pos, decimal):
"""Turn decimal point on or off at provided position. Position should be
a value 0 to 3 with 0 being the left most digit on the display. Decimal
should be True to turn on the decimal point and False to turn it off.
"""
if pos < 0 or pos > 3:
# Ignore out of bounds digits.
return
# Jump past the colon at position 2 by adding a conditional offset.
offset = 0 if pos < 2 else 1
# Calculate the correct position depending on orientation
if self.invert:
pos = 4-(pos+offset)
else:
pos = pos+offset
# Set bit 7 (decimal point) based on provided value.
if decimal:
self.buffer[pos*2] |= (1 << 7)
else:
self.buffer[pos*2] &= ~(1 << 7)
def set_digit(self, pos, digit, decimal=False):
"""Set digit at position to provided value. Position should be a value
of 0 to 3 with 0 being the left most digit on the display. Digit should
be a number 0-9, character A-F, space (all LEDs off), or dash (-).
"""
if self.invert:
self.set_digit_raw(pos, IDIGIT_VALUES.get(str(digit).upper(), 0x00))
else:
self.set_digit_raw(pos, DIGIT_VALUES.get(str(digit).upper(), 0x00))
if decimal:
self.set_decimal(pos, True)
def set_colon(self, show_colon):
"""Turn the colon on with show colon True, or off with show colon False."""
if show_colon:
self.buffer[4] |= 0x02
else:
self.buffer[4] &= (~0x02) & 0xFF
def set_left_colon(self, show_colon):
"""Turn the left colon on with show color True, or off with show colon
False. Only the large 1.2" 7-segment display has a left colon.
"""
if show_colon:
self.buffer[4] |= 0x04
self.buffer[4] |= 0x08
else:
self.buffer[4] &= (~0x04) & 0xFF
self.buffer[4] &= (~0x08) & 0xFF
def set_fixed_decimal(self, show_decimal):
"""Turn on/off the single fixed decimal point on the large 1.2" 7-segment
display. Set show_decimal to True to turn on and False to turn off.
Only the large 1.2" 7-segment display has this decimal point (in the
upper right in the normal orientation of the display).
"""
if show_decimal:
self.buffer[4] |= 0x10
else:
self.buffer[4] &= (~0x10) & 0xFF
def print_number_str(self, value, justify_right=True):
"""Print a 4 character long string of numeric values to the display.
Characters in the string should be any supported character by set_digit,
or a decimal point. Decimal point characters will be associated with
the previous character.
"""
# Calculate length of value without decimals.
length = sum(map(lambda x: 1 if x != '.' else 0, value))
# Error if value without decimals is longer than 4 characters.
if length > 4:
self.print_number_str('----')
return
# Calculcate starting position of digits based on justification.
pos = (4-length) if justify_right else 0
# Go through each character and print it on the display.
for i, ch in enumerate(value):
if ch == '.':
# Print decimal points on the previous digit.
self.set_decimal(pos-1, True)
else:
self.set_digit(pos, ch)
pos += 1
def print_float(self, value, decimal_digits=2, justify_right=True):
"""Print a numeric value to the display. If value is negative
it will be printed with a leading minus sign. Decimal digits is the
desired number of digits after the decimal point.
"""
format_string = '{{0:0.{0}F}}'.format(decimal_digits)
self.print_number_str(format_string.format(value), justify_right)
def print_hex(self, value, justify_right=True):
"""Print a numeric value in hexadecimal. Value should be from 0 to FFFF.
"""
if value < 0 or value > 0xFFFF:
# Ignore out of range values.
return
self.print_number_str('{0:X}'.format(value), justify_right) | Adafruit-LED-Backpack | /Adafruit_LED_Backpack-1.8.1.tar.gz/Adafruit_LED_Backpack-1.8.1/Adafruit_LED_Backpack/SevenSegment.py | SevenSegment.py |
from . import HT16K33
from PIL import Image
import time
class Matrix8x8(HT16K33.HT16K33):
"""Single color 8x8 matrix LED backpack display."""
def __init__(self, **kwargs):
"""Initialize display. All arguments will be passed to the HT16K33 class
initializer, including optional I2C address and bus number parameters.
"""
super(Matrix8x8, self).__init__(**kwargs)
def set_pixel(self, x, y, value):
"""Set pixel at position x, y to the given value. X and Y should be values
of 0 to 8. Value should be 0 for off and non-zero for on.
"""
if x < 0 or x > 7 or y < 0 or y > 7:
# Ignore out of bounds pixels.
return
self.set_led(y * 16 + ((x + 7) % 8), value)
def set_image(self, image):
"""Set display buffer to Python Image Library image. Image will be converted
to 1 bit color and non-zero color values will light the LEDs.
"""
imwidth, imheight = image.size
if imwidth != 8 or imheight != 8:
raise ValueError('Image must be an 8x8 pixels in size.')
# Convert image to 1 bit color and grab all the pixels.
pix = image.convert('1').load()
# Loop through each pixel and write the display buffer pixel.
for x in [0, 1, 2, 3, 4, 5, 6, 7]:
for y in [0, 1, 2, 3, 4, 5, 6, 7]:
color = pix[(x, y)]
# Handle the color of the pixel, off or on.
if color == 0:
self.set_pixel(x, y, 0)
else:
self.set_pixel(x, y, 1)
def create_blank_image(self):
return Image.new("RGB", (8, 8))
def horizontal_scroll(self, image, padding=True):
"""Returns a list of images which appear to scroll from left to right
across the input image when displayed on the LED matrix in order.
The input image is not limited to being 8x8. If the input image is
larger than this, then all columns will be scrolled through but only
the top 8 rows of pixels will be displayed.
Keyword arguments:
image -- The image to scroll across.
padding -- If True, the animation will begin with a blank screen and the
input image will scroll into the blank screen one pixel column at a
time. Similarly, after scrolling across the whole input image, the
end of the image will scroll out of a blank screen one column at a
time. If this is not True, then only the input image will be scroll
across without beginning or ending with "whitespace."
(Default = True)
"""
image_list = list()
width = image.size[0]
# Scroll into the blank image.
if padding:
for x in range(8):
section = image.crop((0, 0, x, 8))
display_section = self.create_blank_image()
display_section.paste(section, (8 - x, 0, 8, 8))
image_list.append(display_section)
#Scroll across the input image.
for x in range(8, width + 1):
section = image.crop((x - 8, 0, x, 8))
display_section = self.create_blank_image()
display_section.paste(section, (0, 0, 8, 8))
image_list.append(display_section)
#Scroll out, leaving the blank image.
if padding:
for x in range(width - 7, width + 1):
section = image.crop((x, 0, width, 8))
display_section = self.create_blank_image()
display_section.paste(section, (0, 0, 7 - (x - (width - 7)), 8))
image_list.append(display_section)
#Return the list of images created
return image_list
def vertical_scroll(self, image, padding=True):
"""Returns a list of images which appear to scroll from top to bottom
down the input image when displayed on the LED matrix in order.
The input image is not limited to being 8x8. If the input image is
largerthan this, then all rows will be scrolled through but only the
left-most 8 columns of pixels will be displayed.
Keyword arguments:
image -- The image to scroll down.
padding -- If True, the animation will begin with a blank screen and the
input image will scroll into the blank screen one pixel row at a
time. Similarly, after scrolling down the whole input image, the end
of the image will scroll out of a blank screen one row at a time.
If this is not True, then only the input image will be scroll down
without beginning or ending with "whitespace." (Default = True)
"""
image_list = list()
height = image.size[1]
# Scroll into the blank image.
if padding:
for y in range(8):
section = image.crop((0, 0, 8, y))
display_section = self.create_blank_image()
display_section.paste(section, (0, 8 - y, 8, 8))
image_list.append(display_section)
#Scroll across the input image.
for y in range(8, height + 1):
section = image.crop((0, y - 8, 8, y))
display_section = self.create_blank_image()
display_section.paste(section, (0, 0, 8, 8))
image_list.append(display_section)
#Scroll out, leaving the blank image.
if padding:
for y in range(height - 7, height + 1):
section = image.crop((0, y, 8, height))
display_section = self.create_blank_image()
display_section.paste(section, (0, 0, 8, 7 - (y - (height - 7))))
image_list.append(display_section)
#Return the list of images created
return image_list
def animate(self, images, delay=.25):
"""Displays each of the input images in order, pausing for "delay"
seconds after each image.
Keyword arguments:
image -- An iterable collection of Image objects.
delay -- How many seconds to wait after displaying an image before
displaying the next one. (Default = .25)
"""
for image in images:
# Draw the image on the display buffer.
self.set_image(image)
# Draw the buffer to the display hardware.
self.write_display()
time.sleep(delay) | Adafruit-LED-Backpack | /Adafruit_LED_Backpack-1.8.1.tar.gz/Adafruit_LED_Backpack-1.8.1/Adafruit_LED_Backpack/Matrix8x8.py | Matrix8x8.py |
from __future__ import division
# Constants
DEFAULT_ADDRESS = 0x70
HT16K33_BLINK_CMD = 0x80
HT16K33_BLINK_DISPLAYON = 0x01
HT16K33_BLINK_OFF = 0x00
HT16K33_BLINK_2HZ = 0x02
HT16K33_BLINK_1HZ = 0x04
HT16K33_BLINK_HALFHZ = 0x06
HT16K33_SYSTEM_SETUP = 0x20
HT16K33_OSCILLATOR = 0x01
HT16K33_CMD_BRIGHTNESS = 0xE0
class HT16K33(object):
"""Driver for interfacing with a Holtek HT16K33 16x8 LED driver."""
def __init__(self, address=DEFAULT_ADDRESS, i2c=None, **kwargs):
"""Create an HT16K33 driver for devie on the specified I2C address
(defaults to 0x70) and I2C bus (defaults to platform specific bus).
"""
if i2c is None:
import Adafruit_GPIO.I2C as I2C
i2c = I2C
self._device = i2c.get_i2c_device(address, **kwargs)
self.buffer = bytearray([0]*16)
def begin(self):
"""Initialize driver with LEDs enabled and all turned off."""
# Turn on the oscillator.
self._device.writeList(HT16K33_SYSTEM_SETUP | HT16K33_OSCILLATOR, [])
# Turn display on with no blinking.
self.set_blink(HT16K33_BLINK_OFF)
# Set display to full brightness.
self.set_brightness(15)
def set_blink(self, frequency):
"""Blink display at specified frequency. Note that frequency must be a
value allowed by the HT16K33, specifically one of: HT16K33_BLINK_OFF,
HT16K33_BLINK_2HZ, HT16K33_BLINK_1HZ, or HT16K33_BLINK_HALFHZ.
"""
if frequency not in [HT16K33_BLINK_OFF, HT16K33_BLINK_2HZ,
HT16K33_BLINK_1HZ, HT16K33_BLINK_HALFHZ]:
raise ValueError('Frequency must be one of HT16K33_BLINK_OFF, HT16K33_BLINK_2HZ, HT16K33_BLINK_1HZ, or HT16K33_BLINK_HALFHZ.')
self._device.writeList(HT16K33_BLINK_CMD | HT16K33_BLINK_DISPLAYON | frequency, [])
def set_brightness(self, brightness):
"""Set brightness of entire display to specified value (16 levels, from
0 to 15).
"""
if brightness < 0 or brightness > 15:
raise ValueError('Brightness must be a value of 0 to 15.')
self._device.writeList(HT16K33_CMD_BRIGHTNESS | brightness, [])
def set_led(self, led, value):
"""Sets specified LED (value of 0 to 127) to the specified value, 0/False
for off and 1 (or any True/non-zero value) for on.
"""
if led < 0 or led > 127:
raise ValueError('LED must be value of 0 to 127.')
# Calculate position in byte buffer and bit offset of desired LED.
pos = led // 8
offset = led % 8
if not value:
# Turn off the specified LED (set bit to zero).
self.buffer[pos] &= ~(1 << offset)
else:
# Turn on the speciried LED (set bit to one).
self.buffer[pos] |= (1 << offset)
def write_display(self):
"""Write display buffer to display hardware."""
for i, value in enumerate(self.buffer):
self._device.write8(i, value)
def clear(self):
"""Clear contents of display buffer."""
for i, value in enumerate(self.buffer):
self.buffer[i] = 0 | Adafruit-LED-Backpack | /Adafruit_LED_Backpack-1.8.1.tar.gz/Adafruit_LED_Backpack-1.8.1/Adafruit_LED_Backpack/HT16K33.py | HT16K33.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.