You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

272 lines
9.3 KiB

  1. # The MIT License (MIT)
  2. #
  3. # Copyright (c) 2017 Scott Shawcroft for Adafruit Industries.
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. # THE SOFTWARE.
  22. """
  23. `simpleio` - Simple, beginner friendly IO.
  24. =================================================
  25. The `simpleio` module contains classes to provide simple access to IO.
  26. """
  27. import time
  28. try:
  29. import audioio
  30. except ImportError:
  31. pass # not always supported by every board!
  32. import array
  33. import digitalio
  34. import pulseio
  35. def tone(pin, frequency, duration=1, length=100):
  36. """
  37. Generates a square wave of the specified frequency on a pin
  38. :param ~microcontroller.Pin Pin: Pin on which to output the tone
  39. :param float frequency: Frequency of tone in Hz
  40. :param int length: Variable size buffer (optional)
  41. :param int duration: Duration of tone in seconds (optional)
  42. """
  43. try:
  44. with pulseio.PWMOut(pin, frequency=int(frequency), variable_frequency=False) as pwm:
  45. pwm.duty_cycle = 0x8000
  46. time.sleep(duration)
  47. except ValueError:
  48. sample_length = length
  49. square_wave = array.array("H", [0] * sample_length)
  50. for i in range(sample_length / 2):
  51. square_wave[i] = 0xFFFF
  52. sample_tone = audioio.AudioOut(pin, square_wave)
  53. sample_tone.frequency = int(len(square_wave) * frequency)
  54. if not sample_tone.playing:
  55. sample_tone.play(loop=True)
  56. time.sleep(duration)
  57. sample_tone.stop()
  58. def bitWrite(x, n, b): #pylint: disable-msg=invalid-name
  59. """
  60. Based on the Arduino bitWrite function, changes a specific bit of a value to 0 or 1.
  61. The return value is the original value with the changed bit.
  62. This function is written for use with 8-bit shift registers
  63. :param x: numeric value
  64. :param n: position to change starting with least-significant (right-most) bit as 0
  65. :param b: value to write (0 or 1)
  66. """
  67. if b == 1:
  68. x |= 1<<n & 255
  69. else:
  70. x &= ~(1 << n) & 255
  71. return x
  72. def shift_in(data_pin, clock, msb_first=True):
  73. """
  74. Shifts in a byte of data one bit at a time. Starts from either the LSB or
  75. MSB.
  76. .. warning:: Data and clock are swapped compared to other CircuitPython libraries
  77. in order to match Arduino.
  78. :param ~digitalio.DigitalInOut data_pin: pin on which to input each bit
  79. :param ~digitalio.DigitalInOut clock: toggles to signal data_pin reads
  80. :param bool msb_first: True when the first bit is most significant
  81. :return: returns the value read
  82. :rtype: int
  83. """
  84. value = 0
  85. i = 0
  86. for i in range(0, 8):
  87. if msb_first:
  88. value |= ((data_pin.value) << (7-i))
  89. else:
  90. value |= ((data_pin.value) << i)
  91. # toggle clock True/False
  92. clock.value = True
  93. clock.value = False
  94. i += 1
  95. return value
  96. def shift_out(data_pin, clock, value, msb_first=True):
  97. """
  98. Shifts out a byte of data one bit at a time. Data gets written to a data
  99. pin. Then, the clock pulses hi then low
  100. .. warning:: Data and clock are swapped compared to other CircuitPython libraries
  101. in order to match Arduino.
  102. :param ~digitalio.DigitalInOut data_pin: value bits get output on this pin
  103. :param ~digitalio.DigitalInOut clock: toggled once the data pin is set
  104. :param bool msb_first: True when the first bit is most significant
  105. :param int value: byte to be shifted
  106. Example for Metro M0 Express:
  107. .. code-block:: python
  108. import digitalio
  109. import simpleio
  110. from board import *
  111. clock = digitalio.DigitalInOut(D12)
  112. data_pin = digitalio.DigitalInOut(D11)
  113. latchPin = digitalio.DigitalInOut(D10)
  114. clock.direction = digitalio.Direction.OUTPUT
  115. data_pin.direction = digitalio.Direction.OUTPUT
  116. latchPin.direction = digitalio.Direction.OUTPUT
  117. while True:
  118. valueSend = 500
  119. # shifting out least significant bits
  120. # must toggle latchPin.value before and after shift_out to push to IC chip
  121. # this sample code was tested using
  122. latchPin.value = False
  123. simpleio.shift_out(data_pin, clock, (valueSend>>8), msb_first = False)
  124. latchPin.value = True
  125. time.sleep(1.0)
  126. latchPin.value = False
  127. simpleio.shift_out(data_pin, clock, valueSend, msb_first = False)
  128. latchPin.value = True
  129. time.sleep(1.0)
  130. # shifting out most significant bits
  131. latchPin.value = False
  132. simpleio.shift_out(data_pin, clock, (valueSend>>8))
  133. latchPin.value = True
  134. time.sleep(1.0)
  135. latchpin.value = False
  136. simpleio.shift_out(data_pin, clock, valueSend)
  137. latchpin.value = True
  138. time.sleep(1.0)
  139. """
  140. value = value&0xFF
  141. for i in range(0, 8):
  142. if msb_first:
  143. tmpval = bool(value & (1 << (7-i)))
  144. data_pin.value = tmpval
  145. else:
  146. tmpval = bool((value & (1 << i)))
  147. data_pin.value = tmpval
  148. # toggle clock pin True/False
  149. clock.value = True
  150. clock.value = False
  151. class Servo:
  152. """
  153. Easy control for hobby (3-wire) servos
  154. :param ~microcontroller.Pin pin: PWM pin where the servo is located.
  155. :param int min_pulse: Pulse width (microseconds) corresponding to 0 degrees.
  156. :param int max_pulse: Pulse width (microseconds) corresponding to 180 degrees.
  157. Example for Metro M0 Express:
  158. .. code-block:: python
  159. import simpleio
  160. import time
  161. from board import *
  162. pwm = simpleio.Servo(D9)
  163. while True:
  164. pwm.angle = 0
  165. print("Angle: ", pwm.angle)
  166. time.sleep(2)
  167. pwm.angle = pwm.microseconds_to_angle(2500)
  168. print("Angle: ", pwm.angle)
  169. time.sleep(2)
  170. """
  171. def __init__(self, pin, min_pulse=0.5, max_pulse=2.5):
  172. self.pwm = pulseio.PWMOut(pin, frequency=50)
  173. self.min_pulse = min_pulse
  174. self.max_pulse = max_pulse
  175. self._angle = None
  176. @property
  177. def angle(self):
  178. """Get and set the servo angle in degrees"""
  179. return self._angle
  180. @angle.setter
  181. def angle(self, degrees):
  182. """Writes a value in degrees to the servo"""
  183. self._angle = max(min(180, degrees), 0)
  184. pulse_width = self.min_pulse + (self._angle / 180) * (self.max_pulse - self.min_pulse)
  185. duty_percent = pulse_width / 20.0
  186. self.pwm.duty_cycle = int(duty_percent * 65535)
  187. def microseconds_to_angle(self, us): #pylint: disable-msg=no-self-use, invalid-name
  188. """Converts microseconds to a degree value"""
  189. return map_range(us, 500, 2500, 0, 180)
  190. def deinit(self):
  191. """Detaches servo object from pin, frees pin"""
  192. self.pwm.deinit()
  193. class DigitalOut:
  194. """
  195. Simple digital output that is valid until soft reset.
  196. """
  197. def __init__(self, pin):
  198. self.iopin = digitalio.DigitalInOut(pin)
  199. self.iopin.switch_to_output()
  200. @property
  201. def value(self):
  202. """The digital logic level of the output pin."""
  203. return self.iopin.value
  204. @value.setter
  205. def value(self, value):
  206. self.iopin.value = value
  207. class DigitalIn:
  208. """
  209. Simple digital input that is valid until soft reset.
  210. """
  211. def __init__(self, pin):
  212. self.iopin = digitalio.DigitalInOut(pin)
  213. self.iopin.switch_to_input()
  214. @property
  215. def value(self):
  216. """The digital logic level of the input pin."""
  217. return self.iopin.value
  218. @value.setter
  219. def value(self, value): #pylint: disable-msg=no-self-use, unused-argument
  220. raise AttributeError("Cannot set the value on a digital input.")
  221. def map_range(x, in_min, in_max, out_min, out_max):
  222. """
  223. Maps a number from one range to another.
  224. Note: This implementation handles values < in_min differently than arduino's map function does.
  225. :return: Returns value mapped to new range
  226. :rtype: float
  227. """
  228. mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min
  229. if out_min <= out_max:
  230. return max(min(mapped, out_max), out_min)
  231. return min(max(mapped, out_max), out_min)