Python 与raspberry pi和arduino的I2C通信问题
我能够实现raspberry pi和arduino之间的I2C通信,并且能够将传感器数据传输到主机一次。但是,我的问题是,如果我第二次尝试启动I2C通信,就会出现“OSError:[Errno 9]错误文件描述符”错误。下面是我的代码-Python 与raspberry pi和arduino的I2C通信问题,python,arduino,raspberry-pi3,i2c,Python,Arduino,Raspberry Pi3,I2c,我能够实现raspberry pi和arduino之间的I2C通信,并且能够将传感器数据传输到主机一次。但是,我的问题是,如果我第二次尝试启动I2C通信,就会出现“OSError:[Errno 9]错误文件描述符”错误。下面是我的代码- import time import smbus import struct #Slave Address from Arduinos SLAVE_ADDRESS = 0x04 #Creating I2C Bus I2C_Bus = smbus.SMBus(1
import time
import smbus
import struct
#Slave Address from Arduinos
SLAVE_ADDRESS = 0x04
#Creating I2C Bus
I2C_Bus = smbus.SMBus(1)
weight = 0
def get_data():
return I2C_Bus.read_i2c_block_data(SLAVE_ADDRESS,0,16)
def get_int(data, index):
bytes = bytearray(data[4*index:(index+1)*4])
return struct.unpack("<i",bytes)[0]
def send_data(value):
I2C_Bus.write_byte(SLAVE_ADDRESS,value)
time.sleep(1)
def start():
while True:
for x in range(1,2):
send_data(1)
x = x +1
data = get_data()
weight = get_int(data,0)
if (weight == 25000):
I2C_Bus.close()
time.sleep(5)
x = 1
get_input()
else:
print("The transaction weight is: "+str(weight))
time.sleep(1)
def get_input():
var = input("Enter a number from 1-9: ")
print(var)
while (var != "1"):
print ("Please select only 1 for now")
get_input()
if (var == "1"):
start()
while True:
get_input()
导入时间
导入smbus
导入结构
#来自Arduinos的从属地址
从机地址=0x04
#创建I2C总线
I2C_总线=smbus.smbus(1)
重量=0
def get_data():
返回I2C_总线。读取I2C_块_数据(从机_地址,0,16)
def get_int(数据、索引):
字节=字节数组(数据[4*索引:(索引+1)*4])
return struct.unpack(“再次调用start()
将调用send_data()
,调用I2C_总线。在I2C_总线上写入字节(从地址、值)
,该字节在上次调用start()
时已关闭,并且在脚本执行时仅打开一次
在尝试读取或写入之前,必须再次打开总线
可能按照文档中的建议使用:
from smbus2 import SMBus
with SMBus(1) as bus:
b = bus.read_byte_data(80, 0)
print(b)
您能告诉我如何再次打开总线吗?@Shining在您的脚本中是这一行I2C_-bus=smbus.smbus(1)
。您没有阅读文档吗???谢谢。我会看一遍。