In this video lesson, we show how to control an LED using python. Python sends commands to arduino, which then controls the LED. We also create a vPython visual, where the ‘Virtual’ LED mimics the behavior of the real LED. This a really cool demonstration and hope you enjoy it. I include below the code we develop in the video. On the arduino side we end up with the following:
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 | int redPin=11; int greenPin=10; int bluePin=9; int redVal=255; int greenVal=255; int blueVal=255; String cmd; void setup() { // put your setup code here, to run once: Serial.begin(115200); pinMode(redPin,OUTPUT); pinMode(greenPin,OUTPUT); pinMode(bluePin,OUTPUT); } void loop() { // put your main code here, to run repeatedly: while(Serial.available()==0){ } redVal=Serial.readStringUntil(':').toInt(); greenVal=Serial.readStringUntil(':').toInt(); blueVal=Serial.readStringUntil('\r').toInt(); analogWrite(redPin,redVal); analogWrite(greenPin,greenVal); analogWrite(bluePin,blueVal); } |
And on the python side we have:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import serial from vpython import * arduinoData=serial.Serial('com3',115200) myOrb=sphere(color=color.black,radius=1) while True: myCmd=input('Please Input Your Color R:G:B 0-255 ') myCmd=myCmd+'\r' arduinoData.write(myCmd.encode()) myColor=myCmd.split(':') red=int(myColor[0]) green=int(myColor[1]) blue=int(myColor[2]) myOrb.color=vector(red/255,green/255,blue/255) |