In this lesson we begin coding a 3D analog voltmeter model in vPython. We begin by connecting a potentiometer to an arduino to create a voltage divider. The voltage is read from the center tap of the potentiometer by the arduino, and then the arduino passes the data to python. Then, we animate the analog voltmeter based on the readings passed from the Arduino. Enjoy!
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 this is the code we developed for the Python side.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import time import serial from vpython import * import numpy as np arrowLength=1 arrowWidth=.02 myArrow=arrow(length=arrowLength,shaftwidth=arrowWidth,color=color.red,axis=vector(1,1,0)) tickL=.1 tickW=.02 tickH=.02 for theta in np.linspace(5*np.pi/6,np.pi/6,6): tickMajor=box(color=color.black,pos=vector(arrowLength*np.cos(theta),arrowLength*np.sin(theta),0),size=vector(tickL,tickW,tickH),axis=vector(arrowLength*np.cos(theta),arrowLength*np.sin(theta),0)) boxX=2.5 boxY=1.5 boxZ=.1 myCase=box(color=color.white,size=vector(boxX,boxY,boxZ),pos=vector(0,.9*boxY/2,-boxZ)) 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 theta=-2*np.pi/3069*potVal+5*np.pi/6 myArrow.axis=vector(arrowLength*np.cos(theta),arrowLength*np.sin(theta),0) # for theta in np.linspace(5*np.pi/6,np.pi/6,150): # rate(25) # myArrow.axis=vector(arrowLength*np.cos(theta),arrowLength*np.sin(theta),0) # for theta in np.linspace(np.pi/6,5*np.pi/6,150): # rate(25) # myArrow.axis=vector(arrowLength*np.cos(theta),arrowLength*np.sin(theta),0) |