树莓派用Python写几个简单程序3_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 smbus
from time import *

# LCD Address
ADDRESS = 0x27

# commands
LCD_CLEARDISPLAY = 0x01
LCD_RETURNHOME = 0x02
LCD_ENTRYMODESET = 0x04
LCD_DISPLAYCONTROL = 0x08
LCD_CURSORSHIFT = 0x10
LCD_FUNCTIONSET = 0x20
LCD_SETCGRAMADDR = 0x40
LCD_SETDDRAMADDR = 0x80

# flags for display entry mode
LCD_ENTRYRIGHT = 0x00
LCD_ENTRYLEFT = 0x02
LCD_ENTRYSHIFTINCREMENT = 0x01
LCD_ENTRYSHIFTDECREMENT = 0x00

# flags for display on/off control
LCD_DISPLAYON = 0x04
LCD_DISPLAYOFF = 0x00
LCD_CURSORON = 0x02
LCD_CURSOROFF = 0x00
LCD_BLINKON = 0x01
LCD_BLINKOFF = 0x00

# flags for display/cursor shift
LCD_DISPLAYMOVE = 0x08
LCD_CURSORMOVE = 0x00
LCD_MOVERIGHT = 0x04
LCD_MOVELEFT = 0x00

# flags for function set
LCD_8BITMODE = 0x10
LCD_4BITMODE = 0x00
LCD_2LINE = 0x08
LCD_1LINE = 0x00
LCD_5x10DOTS = 0x04
LCD_5x8DOTS = 0x00

# flags for backlight control
LCD_BACKLIGHT = 0x08
LCD_NOBACKLIGHT = 0x00
# set init LCD BACKLIGHT ON or OFF
def lcd_backlight(lcdbl=1):
    if lcdbl == 0 :
        return LCD_NOBACKLIGHT
    return LCD_BACKLIGHT

En = 0b00000100 # Enable bit
Rw = 0b00000010 # Read/Write bit
Rs = 0b00000001 # Register select bit

class 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_driver
from time import *

lcd = lcd_driver.lcd(0,1)#设置背光开关,port=1
lcd.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 smbus
import math

class 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<<len)
        return val

    def __convert(self, data, offset):
        val = self.twos_complement(data[offset] << 8 | data[offset+1], 16)
        if val == -4096: return None
        return round(val * self.__scale, 4)

    def axes(self):
        data = self.bus.read_i2c_block_data(self.address, 0x00)
        #print map(hex, data)
        x = self.__convert(data, 3)
        y = self.__convert(data, 7)
        z = self.__convert(data, 5)
        return (x,y,z)

    def heading(self):
        (x, y, z) = self.axes()
        headingRad = math.atan2(y, x)
        headingRad += self.__declination

        # Correct for reversed heading
        if headingRad < 0:
            headingRad += 2 * math.pi

        # Check for wrap and compensate
        elif headingRad > 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 hmc5883l
import time
import 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写几个简单程序3_i2c)