Connexion d'un composant sur l'I2C (ex : Accéléromètre ADXL345)

De Wiki_du_Réseau_des_Electroniciens_du_CNRS
Aller à la navigationAller à la recherche

Revenir au sommaire du RasberryPi

Connexion d’un accéléromètre ADXL345 sur I2C

Tutorial disponible sur http://www.sparkfun.com/tutorials/240

Autodetection des périphériques:

 i2cdetect -y 0  #(attention : sur les dernières Raspberry l'I2C dispo est le 1 donc remplacer "0" par "1")

Le format des données et l’initialisation sont disponibles sur: http://www.i2cdevlib.com/devices/adxl345#registers

Commande en script bash via I2CTOOLS

Dans un fichier nommé measure.sh

 #!/bin/bash
 # configure adxl
 # start measurements
 i2cset -y 0 0x53 0x2D 0x08
 #change data format
 i2cset -y 0 0x53 0x31 0x0B
 #init vars
 xval="0"
 yval= "0"
 zval="0"
 while true; do
 #read X axis datas
 xval=$(i2cget -y 0 0x53 0x32 w )
 #read Y axis datas
 yval=$(i2cget -y 0 0x53 0x34 w )
 #read Z axis datas
 zval=$(i2cget -y 0 0x53 0x36 w )
 #output the values
 echo  "X= $xval Y= $yval Z= $zval"
 done

pour que ce fichier soit executable, il faut lui donner les droits

 sudo chmod +x measure.sh

Commande en python et tracé de courbe

Prérequis pout l'affichage des résultats dans un graphique:

 apt-get matplotlib python-smbus

Doc python I2C: http://wiki.erazor-zone.de/wiki:linux:python:smbus:doc

 #!/usr/bin/env python
 import time
 from smbus import SMBus
 import matplotlib.pyplot as plt
 import numpy as np
 class ADXL345(object):
       def __init__(self, bus, addr):
               self.bus = bus
               self.addr = addr
               self.bus.write_i2c_block_data(self.addr,0x31, [0b1111])
               self.bus.write_i2c_block_data(self.addr,0x2D, [0x08])
       def get_acc(self, shutdown=False):
               val=self.bus.read_i2c_block_data(self.addr,0x32,6)
               x=u2(val[0]|val[1]<<8)
               y=u2(val[2]|val[3]<<8)
               z=u2(val[4]|val[5]<<8)
               return (x,y,z)
 def u2(x):
       if x & 0x8000: # MSB set -> neg.
               return -((~x & 0xffff) + 1)
       else:
               return x
 def main():
       nacq=2000
       tab=np.zeros((nacq,3))
       sensor = ADXL345(SMBus(0), 0x53)
       try:
               print "Acquiring datas - Press ^C to stop"
               for i in range(0,nacq):
                       val=sensor.get_acc()
                       ##print val
                       tab[i,:]=val
       except KeyboardInterrupt:
           pass
       print "end of acquisition"
       plt.plot(tab)
       plt.show()
 if __name__ == "__main__":
   main()