In: Computer Science
Create a code where you click on the appropriate buttons on your Python GUI and it turns on and off the corresponding LEDs for Arduino, please.
Here you are not only going to find code but a depp discussion of circuit and its connection along with Python Code.
Digital inputs can have only two possible values. In a circuit, each of these values is represented by a different voltage. The table below shows the digital input representation for a standard Arduino Uno board:
Value | Level | Voltage |
---|---|---|
0 | Low | 0V |
1 | High | 5V |
To control the LED, we’ll use a push button to send digital input values to the Arduino. The button should send 0V to the board when it’s released and 5V to the board when it’s pressed. The figure below shows how to connect the button to the Arduino board:
We may notice that the LED is connected to the Arduino on digital pin 13, just like before. Digital pin 10 is used as a digital input. To connect the push button, you have to use the 10 KOhm resistor, which acts as a pull down in this circuit. A pull down resistor ensures that the digital input gets 0V when the button is released.
When we release the button, we open the connection between the two wires on the button. Since there’s no current flowing through the resistor, pin 10 just connects to the ground (GND). The digital input gets 0V, which represents the 0 (or low) state. When you press the button, you apply 5V to both the resistor and the digital input. A current flows through the resistor and the digital input gets 5V, which represents the 1 (or high) state.
We can use a breadboard to assemble the above circuit as well:
Now that you’ve assembled the circuit, you have to run a program on the PC to control it using Firmata. This program will turn on the LED, based on the state of the push button:
import pyfirmata
2 import time
3
4 board = pyfirmata.Arduino('/dev/ttyACM0')
5
6 it = pyfirmata.util.Iterator(board)
7 it.start()
8
9 board.digital[10].mode = pyfirmata.INPUT
10
11 while True:
12 sw = board.digital[10].read()
13 if sw is True:
14 board.digital[13].write(1)
15 else:
16 board.digital[13].write(0)
17 time.sleep(0.1)
pyfirmata
and time
.pyfirmata.Arduino()
to set the connection with the Arduino board.board.iterate()
to update the input values obtained
from the Arduino board.pyfirmata.INPUT
. This is necessary since the default
configuration is to use digital pins as outputs.while
loop. This loop reads the status of the input pin, stores it in
sw
, and uses this value to turn the LED on or off by
changing the value of pin 13.while
loop. This isn’t strictly necessary, but
it’s a nice trick to avoid overloading the CPU, which reaches 100%
load when there isn’t a wait command in the loop.