Digital In Out Sample
This sample demonstrates digital port read and write.

To run the sample:

    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:
1
python3 digital_in_out.py
Copied!

Sample Code

digital_in_out.py
1
#!/usr/bin/env python3
2
3
#This sample demonstrates digital port read and write.
4
#Install Modular HAT library with "pip3 install turta-modularhat"
5
6
#Raspberry Pi Configuration
7
# - You should enable SPI and I2C from the Raspberry Pi's configuration.
8
# To do so, type 'sudo raspi-config' to the terminal, then go to 'Interfacing Options' and enable both SPI and I2C.
9
10
11
from time import sleep
12
from turta_modularhat import Turta_Digital
13
14
#Initialize
15
#Set left digital port as output, right digital port as input
16
digital = Turta_Digital.DigitalPort(False, False, True, True)
17
18
try:
19
while True:
20
#Turn pin 1 on
21
digital.write(1, True)
22
print("Pin 1 is set to high.")
23
24
#Wait
25
sleep(1.0)
26
27
#Turn pin 1 off
28
digital.write(1, False)
29
print("Pin 1 is set to low.")
30
31
#Wait
32
sleep(1.0)
33
34
#Toggle pin 2
35
#Toggling inverts the pin state
36
digital.toggle(2)
37
print("Pin 2 is inverted to " + ("high." if digital.read(2) else "low."))
38
39
#Wait
40
sleep(1.0)
41
42
#Read pin 3 and 4
43
pin3 = digital.read(3)
44
pin4 = digital.read(4)
45
46
#Print pin 3 and 4 states
47
print("Pin 3 state is " + ("high." if pin3 else "low."))
48
print("Pin 4 state is " + ("high." if pin4 else "low."))
49
50
#Wait
51
sleep(1.0)
52
53
#Exit on CTRL+C
54
except KeyboardInterrupt:
55
print('Bye.')
Copied!

Result

When you run the sample, it toggles digital port 1 and reads digital port 2. The example output should be like this:
1
Pin 1 is set to high.
2
Pin 1 is set to low.
3
Pin 2 is inverted to high.
4
Pin 3 state is low.
5
Pin 4 state is low.
6
Pin 1 is set to high.
7
Pin 1 is set to low.
8
Pin 2 is inverted to low.
9
Pin 3 state is low.
10
Pin 4 state is low.
Copied!
To stop the Python script, just press CTRL + C.
Last modified 1yr ago
Copy link