Circuit Python tutorials in Robotics II
View the Project on GitHub MrPrattASH/Robotics-II-Circuit-Python
The RC signal is read from specific pins on a microcontroller, and the code then outputs the duty cycle value of the signal. We’ll first learn how to read our x2 joystick values.
"""Basic RC Analog input Control
Outputs an analog channel duty cycle rating in 0>100.
50 is the deadpoint. 0 is miniumum, 100 is maximum.
"""
import time
import board
from rc import RCReceiver
rc = RCReceiver(ch1=board.D10, ch2=board.D11, ch3=None, ch4=None, ch5=board.D12, ch6=board.D13)
# Main code
while True:
# Read channels
channel_1 = rc.read_channel(1)
channel_2 = rc.read_channel(2)
if channel_1 is not None and channel_2 is not None: # must not be None to do something with the output
print("1: ", channel_1, "2: ", channel_2)
rc.ensure_cycle() # Maintains sync with our 20ms cycle every loop iteration
"""
Basic RC Analog input Control
Outputs an analog channel duty cycle rating in 0 > 100.
50 is the deadpoint. 0 is miniumum, 100 is maximum.
"""
import time
import board
from rc import RCReceiver
import time
: Imports the time
module, which allows us to work with time-related functions, such as delays.import board
: Imports the board
module, which maps the microcontroller’s pins.from rc import RCReceiver
: Imports the RCReceiver
class from the rc
module, allowing us to create an RC receiver object.The next section of the code initializes the RC receiver channels.
rc = RCReceiver(ch1=board.D10, ch2=board.D11, ch3=None, ch4=None, ch5=board.D12, ch6=board.D13)
rc
: This is an instance of the RCReceiver
class, which we will use to read the values from the RC receiver.ch1
to ch6
represent the input channels from the RC receiver. They are connected to specific pins (e.g., board.D10
, board.D11
, etc.).
None
so that the library will ignore these channels.This is the main part of our script where we continuously read and print the values from the RC receiver.
# Main code
while True:
# Read channels
channel_1 = rc.read_channel(1)
channel_2 = rc.read_channel(2)
if channel_1 is not None and channel_2 is not None: # must not be None to do something with the output
print("1: ", channel_1, "2: ", channel_2)
rc.ensure_cycle() # Maintains sync with our 20ms cycle every loop iteration
channel_1 = rc.read_channel(1)
: Reads the value from channel 1 (and 2 respectively)0-100
:50
0
100
if channel_1 is not None and channel_2 is not None
: Ensures that both channels have valid readings before proceeding. If there is ever an error in reading a channel, the method will return None
.rc.ensure_cycle()
: maintains correct sync for cycle readings of our rc reciever (20 milliseconds). This matches the length of a single duty cycle of the RC receiver, ensuring the code reads the next cycle’s data.while True:
loop in order to keep our readings in sync with our duty cycle.