import pigpio import time # 注意: 树莓派官方未表明支持5V输入,所以不能插传感器的SDA/SCL 5V跳线帽,需要使用内置或外置3.3V上拉 # 此例程由群友热心提供,因此 此例程无任何售后保证,仅供参考 I2C_SDA_PIN = 2 I2C_SCL_PIN = 3 # I2C端口 I2C_BUS_NUM = 1 # 传感器默认地址(无跳线帽) GW_GRAY_I2C_ADDR = 0x4C pi = pigpio.pi() # 设置I2C上拉 pi.set_pull_up_down(2, pigpio.PUD_UP) pi.set_pull_up_down(3, pigpio.PUD_UP) i2c_handle = pi.i2c_open(I2C_BUS_NUM, GW_GRAY_I2C_ADDR) def gw_gray_set_analog_mode(handle, normalization_en=True): """ 设置传感器自带模拟量归一化(写入0xCF,0XFF),设置模拟量模式(写入0xB0) :param handle: I2C端口柄 :param normalization_en: 是否启用传感器自带模拟量归一化 """ if normalization_en: write_data = [0xCF, 0xFF] write_rsp = pi.i2c_write_device(handle, write_data) print(write_rsp) write_data = [0xB0] write_rsp = pi.i2c_write_device(handle, write_data) print(write_rsp) def gw_gray_read_digital(handle): return pi.i2c_read_i2c_block_data(handle, 0xDD, 1) def gw_gray_read_analog(handle): return pi.i2c_read_i2c_block_data(handle, 0xB0, 8) if __name__ == '__main__': gw_gray_set_analog_mode(i2c_handle, normalization_en=True) # 每隔1秒打印一次数据 while True: read_data = gw_gray_read_analog(i2c_handle) # 是否有I2C错误 if read_data[0] < 0: print(f"read error with code {read_data[0]}") else: print(f"{['%3d' % x for x in list(read_data[1])]}") time.sleep(1)