Raspberry Pi 3的I2C使用(Python)

时间:2016-12-06 08:09:03

标签: python i2c raspberry-pi3

我正在尝试通过I2C连接和Python 2.7将HMC5983数字罗盘集成到我的Raspberry Pi 3中。我还使用Adafruit_GPIO库来管理与SMBus的交互。

我试图为HMC5983编写一个简单的Python库。在测试库时,我尝试读取模式寄存器(0x02)。我选择了这个寄存器,因为我希望代码返回一个已知值(每datasheet,模式字节为0x01或0x02),以验证我是否正确实现了I2C通信。但是,我的代码没有返回预期的值。这些值也会在寄存器的读数之间发生变化。

对我做错了什么的想法?

测试计划:

# Import HMC5983 library
import HMC5983

# Device default addresses
HMC5983_I2CADD = 0x42

# Create new HMC5983 object and provide the default address
# Note: address has been verified through Terminal (i2cdetect -y 1)
HMC5983 = HMC5983.HMC5983(HMC5983_I2CADD,1, None)

while True:
    # Call the read_mode() method and print the results in binary
    print 'Mode = {0:b}'.format(HMC5983.read_mode())
    time.sleep(1)

HMC5983图书馆:

import time

# HMC4983 Data Registers
HMC5983_CONF_A          = 0x00  #R/W
HMC5983_CONF_B          = 0x01  #R/W
HMC5983_MODE            = 0x02  #R/W
HMC5983_MSB_X           = 0x03  #R
HMC5983_LSB_X           = 0x04  #R
HMC5983_MSB_Z           = 0x05  #R
HMC5983_LSB_Z           = 0x06  #R
HMC5983_MSB_Y           = 0x07  #R
HMC5983_LSB_Y           = 0x08  #R
HMC5983_STATUS          = 0x09  #R
HMC5983_IDEN_A          = 0x0A  #R
HMC5983_IDEN_B          = 0x0B  #R
HMC5983_IDEN_C          = 0x0C  #R
HMC5983_MSB_TEMP        = 0x31  #R
HMC5983_LSB_TEMP        = 0x32  #R

# HMC4983 Modes
HMC5983_IDLE            = 0x02
HMC5983_SINGLE          = 0x01
HMC5983_CONT            = 0x00

class HMC5983(object):
    def __init__(self, IN_ADDRESS, mode=HMC5983_SINGLE, i2c=None, **kwargs):
        # Check if input mode is valid
        if mode not in [HMC5983_IDLE, HMC5983_SINGLE, HMC5983_CONT]:
            raise ValueError('Unexpected mode value {0}. Set mode to one of HMC5983_IDLE, HMC5983_SINGLE, or HMC5983_CONT.'.format(mode))
        self._mode = mode
        self._address = IN_ADDRESS
        # Create I2C device.
        if i2c is None:
            import Adafruit_GPIO.I2C as I2C
            i2c = I2C
        self._device = i2c.get_i2c_device(self._address, **kwargs)

    def read_mode(self):
        return self._device.readU8(HMC5983_MODE)

    def read_config_A(self):
        return self._device.readU8(HMC5983_CONF_A)

    def read_raw_magX(self):
        highX = self._device.readU8(HMC5983_MSB_X)
        lowX = self._device.readU8(HMC5983_LSB_X)
        return (highX << 8) | lowX

    def read_raw_magY(self):
        highY = self._device.readU8(HMC5983_MSB_Y)
        lowY = self._device.readU8(HMC5983_LSB_Y)
        return (highY << 8) | lowY

    def read_raw_magZ(self):
        highZ = self._device.readU8(HMC5983_MSB_Z)
        lowZ = self._device.readU8(HMC5983_LSB_Z)
        return (highZ << 8) | lowZ

输出(每次都有所不同):

Mode = 11111111
Mode = 100100
Mode = 11000111
Mode = 11001110
Mode = 10

0 个答案:

没有答案