1
+ import sys
2
+ import re
3
+ import serial
4
+
5
+ class ArduinoSerialUIData :
6
+ def __init__ (self , serialport = 'COM4' ):
7
+ # Création d'une connection serie
8
+ self .serialcnx = serial .Serial (port = serialport , baudrate = 9600 , timeout = 1 , writeTimeout = 1 )
9
+
10
+ def getmesures ():
11
+ # Lecture Arduino
12
+ # Wait here until there is data
13
+ while (self .serialcnx .inWaiting ()== 0 ):
14
+ pass #do nothing
15
+
16
+ # Les données envoyées par arduino sont reçut par python au format "bytes object" : b'0.0;2.9\r\n'
17
+ # le b indique que les données sont au format bytes object
18
+ # @see: https://www.geeksforgeeks.org/byte-objects-vs-string-python/
19
+ # @see: https://www.pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/
20
+ # on utilise la methode .decode() pour convertir les données en caractères
21
+ data = self .serialcnx .readline ().decode ('ascii' )
22
+
23
+ # Extraction et validation des données avec une expression régulière
24
+ # Les données doivent être au format : 8.25;1.41 (il peut y avoir des caractères avant et/ou aprés)
25
+ # @see: http://apprendre-python.com/page-expressions-regulieres-regular-python
26
+ matchObj = re .match ( r'.*(\d+\.\d+);(\d+\.\d+).*' , data )
27
+ if (matchObj ) :
28
+ mesures = {'tension' :0 , 'intensity' :0 , 'power' :0 }
29
+ # traitement
30
+ mesures ['tension' ] = float (matchObj .group (1 ))
31
+ mesures ['intensity' ] = float (matchObj .group (2 ))
32
+ mesures ['puissance' ] = mesures ['tension' ]* mesures ['intensity' ]
33
+ return mesures
34
+ # problème avec le format de donné transmis
35
+ # on relance une lecture
36
+ else :
37
+ self .getmesures ()
38
+
39
+
40
+
41
+ class AppArduinoUI :
42
+ def __init__ (self , serialport = 'COM4' ):
43
+ self .serialport = serialport
44
+
45
+ def run (self ):
46
+ # Création d'une connection avec Arduino
47
+ # Pour la gestion des exceptions
48
+ # @see: http://apprendre-python.com/page-apprendre-exceptions-except-python-cours-debutant
49
+ try :
50
+ arduinodata = ArduinoSerialUIData (self .serialport )
51
+ except serial .serialutil .SerialException as errorException :
52
+ print ( "Erreur de connection avec le port série : " , errorException )
53
+ sys .exit ()
54
+ while True :
55
+ mesures = arduinodata .getmesures ()
56
+ # Affichage
57
+ print ("T = {:.2f} V | I = {:.2f} A | P = {:.2f} W" .format (mesures ['tension' ], mesures ['intensity' ], mesures ['puissance' ]) )
58
+
59
+
60
+
61
+
62
+ app = AppArduinoUI ('COM4' )
63
+ app .run ()
0 commit comments