Comment on page
Digital In Out Sample
This sample demonstrates digital port read and write.
- 1.Download the sample code from https://github.com/Turta-io/IoTHAT3/blob/master/Samples/Python/Digital_Port_In_Out.py
- 2.Copy the sample code to a folder on the Raspberry Pi.
- 3.Open terminal, and then go to the folder you copied the sample.
- 4.Run the sample with the following command:
python3 Digital_Port_In_Out.py
Digital_Port_In_Out.py
#!/usr/bin/env python3
#This sample demonstrates digital port read and write.
#Install IoT HAT 3 library with "pip3 install turta-iothat3"
from time import sleep
from turta_iothat3 import Turta_Digital
#Initialize
#Set left digital port as output, right digital port as input
digital = Turta_Digital.DigitalPort(False, False, True, True)
try:
while True:
#Turn pin 1 on
digital.write(1, True)
print("Pin 1 is set to high.")
#Wait
sleep(1.0)
#Turn pin 1 off
digital.write(1, False)
print("Pin 1 is set to low.")
#Wait
sleep(1.0)
#Toggle pin 2
#Toggling inverts the pin state
digital.toggle(2)
print("Pin 2 is inverted to " + ("high." if digital.read(2) else "low."))
#Wait
sleep(1.0)
#Read pin 3 and 4
pin3 = digital.read(3)
pin4 = digital.read(4)
#Print pin 3 and 4 states
print("Pin 3 state is " + ("high." if pin3 else "low."))
print("Pin 4 state is " + ("high." if pin4 else "low."))
#Wait
sleep(1.0)
#Exit on CTRL+C
except KeyboardInterrupt:
print('Bye.')
When you run the sample, it toggles digital port 1 and reads digital port 2. The example output should be like this:
Pin 1 is set to high.
Pin 1 is set to low.
Pin 2 is inverted to high.
Pin 3 state is low.
Pin 4 state is low.
Pin 1 is set to high.
Pin 1 is set to low.
Pin 2 is inverted to low.
Pin 3 state is low.
Pin 4 state is low.
To stop the Python script, just press CTRL + C.
Last modified 4yr ago