Commander trois leds avec la plateforme arduino et une interface python
Une des grandes questions que je me posais depuis que j’ai mon module arduino était : “comment commander la carte depuis ma machine ?” En parcourant le forum arduino, j’ai finalement trouvé la réponse à ma question. Je me suis inspiré de ce post.
C’est finalement une chose assez simple à realiser et qui se décompose en deux parties:
- le code destiné à la plateforme arduino avec un simple switch case;
- le code python qui communique avec arduino via le port série virtuel.
Le code arduino
/* Pin number declaration, W,Y G standing for white, yellow, green.
Actually, my leds are yellow...*/
int WPin = 4;
int YPin = 5;
int GPin = 6;
int delayVal;
/* set the virtual serial port speed and the type of my pins*/
void setup() {
Serial.begin(115200);
pinMode(WPin, OUTPUT);
pinMode(YPin, OUTPUT);
pinMode(GPin, OUTPUT);
}
void loop() {
// Check if a character is available in the serial buffer
if(Serial.available() > 0){
switch( byte( Serial.read() )) { // read one character
/* this case makes the leds blink */
case 'b':
delayVal = int(Serial.read());
delayVal = delayVal * 100;
Serial.print(delayVal,DEC);
do{
digitalWrite(WPin, HIGH);
delay(delayVal);
digitalWrite(WPin, LOW);
digitalWrite(YPin, HIGH);
delay(delayVal);
digitalWrite(YPin, LOW);
digitalWrite(GPin, HIGH);
delay(delayVal);
digitalWrite(GPin, LOW); }while(Serial.available() < 2);
break;
/* this case sets all the pins to a high level */
case 'f':
digitalWrite(WPin, HIGH);
digitalWrite(GPin, HIGH);
digitalWrite(YPin, HIGH);
break;
/* this case sets all the pins to a low level, switching off the leds */
case 's':
digitalWrite(WPin, LOW);
digitalWrite(GPin, LOW);
digitalWrite(YPin, LOW);
break;
}
}
delay(100);
}
Le code python de commande
import serial
# Setup the Serial Object
ser = serial.Serial()
# Set the Serial Port to use
ser.setPort('/dev/ttyUSB0')
# Set the Baudrate
ser.baudrate = 115200
# Open the Serial Connection
ser.open()
loopVar = True
if (ser.isOpen()):
# Start a main loop
while (loopVar):
# Prompt for Red value
action = raw_input('Action : ')
if action == "b":
delayVal = int(input('delay :'))
ser.write("b"+chr(int(delayVal)))
if action == "f":
ser.write("f"+str(0))
if action == "s":
ser.write("s"+str(0))
# loopVar = False
# After loop exits, close serial connection
ser.close()