千家信息网

树莓派怎么用Python实现i2c

发表于:2025-02-11 作者:千家信息网编辑
千家信息网最后更新 2025年02月11日,这篇文章给大家分享的是有关 树莓派怎么用Python实现i2c的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。首先树莓派得安装 python-smbus, i2c-tools
千家信息网最后更新 2025年02月11日树莓派怎么用Python实现i2c

这篇文章给大家分享的是有关 树莓派怎么用Python实现i2c的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

首先树莓派得安装 python-smbus, i2c-tools,

然后修改文件:sudo nano /etc/modules,添加上 i2c-bcm2708 和i2c-dev 这两行,Raspbian还需要在raspi-config中激活i2c.

用 sudo i2cdetect -y 1 查看设备地址,

例子1:LCD2004,设备地址 为0x27;

先写个驱动调用程序 i2c_driver_lcd.py

import smbusfrom time import *# LCD AddressADDRESS = 0x27# commandsLCD_CLEARDISPLAY = 0x01LCD_RETURNHOME = 0x02LCD_ENTRYMODESET = 0x04LCD_DISPLAYCONTROL = 0x08LCD_CURSORSHIFT = 0x10LCD_FUNCTIONSET = 0x20LCD_SETCGRAMADDR = 0x40LCD_SETDDRAMADDR = 0x80# flags for display entry modeLCD_ENTRYRIGHT = 0x00LCD_ENTRYLEFT = 0x02LCD_ENTRYSHIFTINCREMENT = 0x01LCD_ENTRYSHIFTDECREMENT = 0x00# flags for display on/off controlLCD_DISPLAYON = 0x04LCD_DISPLAYOFF = 0x00LCD_CURSORON = 0x02LCD_CURSOROFF = 0x00LCD_BLINKON = 0x01LCD_BLINKOFF = 0x00# flags for display/cursor shiftLCD_DISPLAYMOVE = 0x08LCD_CURSORMOVE = 0x00LCD_MOVERIGHT = 0x04LCD_MOVELEFT = 0x00# flags for function setLCD_8BITMODE = 0x10LCD_4BITMODE = 0x00LCD_2LINE = 0x08LCD_1LINE = 0x00LCD_5x10DOTS = 0x04LCD_5x8DOTS = 0x00# flags for backlight controlLCD_BACKLIGHT = 0x08LCD_NOBACKLIGHT = 0x00# set init LCD BACKLIGHT ON or OFFdef lcd_backlight(lcdbl=1):    if lcdbl == 0 :        return LCD_NOBACKLIGHT    return LCD_BACKLIGHTEn = 0b00000100 # Enable bitRw = 0b00000010 # Read/Write bitRs = 0b00000001 # Register select bitclass lcd(object):    #initializes objects and lcd    def __init__(self,lcd_bl,port=1):    self.addr = ADDRESS    self.bus = smbus.SMBus(port)        self.lcd_bl = lcd_bl                self.lcd_write(0x03)        self.lcd_write(0x03)        self.lcd_write(0x03)        self.lcd_write(0x02)                        self.lcd_write(LCD_FUNCTIONSET | LCD_2LINE | LCD_5x8DOTS | LCD_4BITMODE)        self.lcd_write(LCD_DISPLAYCONTROL | LCD_DISPLAYON)        self.lcd_write(LCD_CLEARDISPLAY)           self.lcd_write(LCD_ENTRYMODESET | LCD_ENTRYLEFT)        sleep(0.2)       def set_lcd(self,set_lcdbl):        self.lcd_bl = set_lcdbl        # clocks EN to latch command    def lcd_strobe(self, data):        self.write_cmd(data | En | lcd_backlight(self.lcd_bl))        sleep(.0005)        self.write_cmd(((data & ~En) | lcd_backlight(self.lcd_bl)))        sleep(.0001)       def lcd_write_four_bits(self, data):        self.write_cmd(data | lcd_backlight(self.lcd_bl))        self.lcd_strobe(data)    # write a command to lcd    def lcd_write(self, cmd, mode=0):        self.lcd_write_four_bits(mode | (cmd & 0xF0))        self.lcd_write_four_bits(mode | ((cmd << 4) & 0xF0))    # put string function    def lcd_display_string(self, string, raw=1, col=1):        if raw == 1:            self.lcd_write(0x80+col-1)        if raw == 2:            self.lcd_write(0xC0+col-1)        if raw == 3:            self.lcd_write(0x94+col-1)        if raw == 4:            self.lcd_write(0xD4+col-1)        for char in string:            self.lcd_write(ord(char), Rs)    # clear lcd and set to home    def lcd_clear(self):        self.lcd_write(LCD_CLEARDISPLAY)        self.lcd_write(LCD_RETURNHOME)    # Write a single command    def write_cmd(self, cmd):        self.bus.write_byte(self.addr, cmd)        sleep(0.0001)

然后写个lcd_main.py

import i2c_driver_lcd as lcd_driverfrom time import *lcd = lcd_driver.lcd(0,1)#设置背光开关,port=1lcd.lcd_display_string("hello raspberry", 1,3)s= raw_input("input:")lcd.set_lcd(1)#设置背光开关lcd.lcd_display_string(s, 2, 2)

例子2:hmc5883l ; 设备地址为 0x1e

先写个驱动调用程序 i2c_driver_hmc5883l.py

#!/usr/bin/env python# vim: set fileencoding=UTF-8 :# HMC5888L Magnetometer (Digital Compass) wrapper class# Based on https://bitbucket.org/thinkbowl/i2clibraries/src/14683feb0f96,# but uses smbus rather than quick2wire and sets some different init# params.import smbusimport mathclass hmc5883l:    __scales = {        0.88: [0, 0.73],        1.30: [1, 0.92],        1.90: [2, 1.22],        2.50: [3, 1.52],        4.00: [4, 2.27],        4.70: [5, 2.56],        5.60: [6, 3.03],        8.10: [7, 4.35],    }    def __init__(self, port=1, address=0x1E, gauss=1.3, declination=(0,0)):        self.bus = smbus.SMBus(port)        self.address = address        (degrees, minutes) = declination        self.__declDegrees = degrees        self.__declMinutes = minutes        self.__declination = (degrees + minutes / 60) * math.pi / 180        (reg, self.__scale) = self.__scales[gauss]        self.bus.write_byte_data(self.address, 0x00, 0x70) # 8 Average, 15 Hz, normal measurement        self.bus.write_byte_data(self.address, 0x01, reg << 5) # Scale        self.bus.write_byte_data(self.address, 0x02, 0x00) # Continuous measurement    def declination(self):        return (self.__declDegrees, self.__declMinutes)    def twos_complement(self, val, len):        # Convert twos compliment to integer        if (val & (1 << len - 1)):            val = val - (1< 2 * math.pi:            headingRad -= 2 * math.pi        # Convert to degrees from radians        headingDeg = headingRad * 180 / math.pi        return headingDeg    def degrees(self, headingDeg):        degrees = math.floor(headingDeg)        minutes = round((headingDeg - degrees) * 60)        return (degrees, minutes)    def __str__(self):        (x, y, z) = self.axes()        return "Axis X: " + str(x) + "\n" \               "Axis Y: " + str(y) + "\n" \               "Axis Z: " + str(z) + "\n" \               "Declination: " + self.degrees(self.declination()) + "\n" \               "Heading: " + self.degrees(self.heading()) + "\n"

再写个gy273_main.py

import i2c_driver_hmc5883l as hmc5883limport timeimport sys# http://magnetic-declination.com/Great%20Britain%20(UK)/Harrogate#compass = hmc5883l.hmc5883l(gauss = 4.7, declination = (-2,5))while True:    sys.stdout.write("\rHeading: " + str(compass.degrees(compass.heading())) + "     ")    #sys.stdout.write("\rAxis X: " + str(str(x))    sys.stdout.flush()    time.sleep(0.5)

i2c设备容易共用总线,比如上述两个i2c设备,可以接在同一个i2c总线上,但要注意LCD可能需要5V供电,而模块gy273供电VCC为3.3V。

感谢各位的阅读!关于" 树莓派怎么用Python实现i2c"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

0