

If the value has no data, then it will return none, and this will crash the code. while True:Ī conditional test is now applied to the value variable. This value will then be printed to the Python shell. The main body of code is a while True loop, which will read the current value of analogue pin 0, which is connected to the potentiometer, and store the value in a variable called value. We should create an object called it and then connect this to the Arduino, before then starting the thread. To read the analogue values from the Arduino we need to create a thread that will run and not interrupt the main code. We’ll start the code for this project In a new blank file, using the same lines to import and configure the pin being used on the Arduino. Please see the diagram below for more information on this.Īrduino Uno board connected to a potentiometer and LED light.

We will add the potentiometer to the existing LED test circuit that we have just built and tested. We can use the value returned from the Arduino to control the speed at which the LED flashes. This will be an LED that flashes, but the interval between each flash is controlled via a potentiometer, an analogue electronic component –- something that the Raspberry Pi cannot ordinarily use without extra ADC (analog-to-digital conversion) boards. Sleep(0.2) Flashing LED Lights with Raspberry Pi and Arduino The final python script should look like this: from pyfirmata import Arduino, util Save the code and then run it from your editor (IDLE Run > Run Module/Thonny Run > Run Current Script) and after a few seconds the LED connected to the Arduino will flash, proving that we have a working connection. Then we sleep for 0.2 seconds, before turning the pin off and sleeping once more. Note that we use the variable led to identify the pin.

We will call the object board, with a class to control the pin digitally (0,1) and then write 1 to the pin to turn it on. Inside of a while True loop, we can write the code that will turn the LED on and off every 0.2 seconds. You create it by adding the line: led = 12 board = Arduino('/dev/ttyUSB0')Ī variable called led is used to store the Arduino pin number. For this, we shall need to use the USB device information from dmesg. The next step is to create an object called board that will be the connection from our Pi to the Arduino. We can then import the sleep function from the time library, by typing: from pyfirmata import Arduino, util Start by importing two classes from the pyFirmata library, which will enable our code to connect to the Arduino. We shall now write some Python code into this file. Using your favourite Python 3 editor (IDLE, Thonny, nano, Vim), create a new file and name it LED_test.py. Look for USB devices such as ttyUSB0 and ttyACM0.

Plug in the Arduino, and in the terminal type the following code. Diagram showing how Arduino Uno connects to LED light.
