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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| import RPi.GPIO as GPIO
import time
clockS = 14
clockE = 18
dataS = 15
dataE = 23
global n
global data
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(clockS, GPIO.OUT, initial = GPIO.LOW) #sortie clock
GPIO.setup(dataS, GPIO.OUT, initial = GPIO.LOW) #sortie data
GPIO.setup(clockE, GPIO.IN) #entrée clock
GPIO.setup(dataE, GPIO.IN) #entrée data
def Lecture():
"Permet de lire un octet de données envoyées par le périphérique"
data = ''
n = 0
lecture = 0
flagLecture = 1 #initialisation des variables
while GPIO.input(clockE) == 1 : #attendre un flanc descendant (bit de start)
{}
while n < 8 : #faire cela pour les 8 bits
lecture = GPIO.input(clockE) #lecture de l'état de la clock
if lecture == 1: #si état haut ne rien faire
flagLecture = 0
else : #sinon
if flagLecture == 0 : #si pas déjà lu
data += str(GPIO.input(dataE)) #lecture du bit et ajout à la chaine
flagLecture = 1
n += 1
FlancD() #bit de parité
FlancD() #bit de stop
while (GPIO.input(clockE) == 0) | (GPIO.input(dataE) == 0):
{} #attente que les lignes soient libérées
return data
def Ecriture(octet):
"Ecrit un octet de données (paramètre à donner en hexa)"
n = 0
flagEcriture = 0
lecture = 0
octet = (int(octet,16)^0xFF) #masque XOR
octet = bin(int(octet)) #conversion en binaire string
octet = octet[::-1] #inversion LSB en premier
octet = octet[0:len(octet)-2] #suppression du 0b
while len(octet) < 8:
octet += '0' #ajout des bits manquants
GPIO.output(clockS, GPIO.HIGH)
time.sleep(0.0005)
GPIO.output(dataS, GPIO.HIGH)
time.sleep(0.00005)
GPIO.output(clockS, GPIO.LOW) #demande à envoyer + bit de start
while n < 8 :
lecture = GPIO.input(clockE)
if lecture == 1:
flagEcriture = 0
else :
if flagEcriture == 0 :
GPIO.output(15, int(octet[n])) #écriture du bit (lsb d'abord) (15 au lieu de dataS pour gagner du temps)
flagEcriture = 1
n += 1
if (octet.count('1')%2) == 0: #calcul du bit de parité
parite = 0
else :
parite = 1
FlancD()
GPIO.output(dataS, parite) #envoi du bit de parité
FlancD()
GPIO.output(dataS, GPIO.LOW) #envoi du bit de stop
FlancD() #ACK
while (GPIO.input(clockE) == 0) | (GPIO.input(dataE) == 0):
{} #attente que les lignes soient libérées
def FlancD():
"Attend un flanc descendant"
while GPIO.input(clockE) == 0:
{}
while GPIO.input(clockE) == 1:
{}
def Test():
Ecriture("F2")
l1 = Lecture()
l2 = Lecture()
Ecriture("F2")
l3 = Lecture()
l4 = Lecture()
print(hex(int(l1[::-1],2)))
print(hex(int(l2[::-1],2)))
print(hex(int(l3[::-1],2)))
print(hex(int(l4[::-1],2))) |
Partager