In this lesson we show how you can measure a voltage from a potentiometer using Arduino, and then pass that data to Visual Python over the serial port. Then we use visual python to create a 3D model that is animated by the live data.
On the Arduino side we use the following code to measure the voltage from the potentiometer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | int potPin=A0; int DL=100; int potVal; void setup() { // put your setup code here, to run once: pinMode(potPin,INPUT); Serial.begin(115200); } void loop() { // put your main code here, to run repeatedly: potVal=analogRead(potPin); Serial.println(potVal); delay(DL); } |
Then on the python side we read and display the data with the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import time import serial from vpython import * tube=cylinder(color=color.blue, radius=1, length=5, axis=vector(0,1,0)) lab=label(text='0 Volts',box=False) arduinoData=serial.Serial('com3',115200) time.sleep(1) while True: while arduinoData.in_waiting==0: pass dataPacket=arduinoData.readline() dataPacket=str(dataPacket,'utf-8') dataPacket=dataPacket.strip('\r\n') dataPacket=int(dataPacket) potVal=dataPacket vol=(5./1023.)*potVal if vol==0: vol=.0001 tube.length=vol vol=round(vol,1) lab.text=str(vol)+' Volts' |
Watch the video for a complete explanation of the code.