Firstly ensure i2c interface is opened by raspberry pi.
1
sudo apt install build-essentials i2c-tools
then check by
1
sudo i2cdetect -y 1
If a problem happened showing ‘no i2c device found, /dev/i2c-1 or /dev/i2c/1’. You should edit /boot/config.txt, then open by uncomment
1
# dtparam=i2c1=on
Then install python2.7 package ‘smbus2’. You may install python-setuptools first. Then you can download source code to install or use pip install.
When connecting Arduino, check i2c pinout on your Pi by typing pinout. But this command might not be found on Raspbian Lite, so firstly you should install
defreadNumber(): number = bus.read_byte(address) return number
whileTrue: var=input("Enter1–9:") ifnot var: continue writeNumber(var) print"RPI: Hi Arduino, I sent you ", var # sleep one second time.sleep(1) number = readNumber() print"Arduino: Hey RPI,I received a digit", number print"======================================\n"
#!/usr/bin/env python # -*- coding:utf-8 -*- import smbus import time bus = smbus.SMBus(1) address = 0x20
defreadString(len): tmp = bus.read_i2c_block_data(address, 0, len) message = "".join([chr(i) for i in tmp]) return message
whileTrue: var=input("Enter one byte to get a string:") ifnot var: continue print"RPi: Hi Arduino, I sent you ", var writeNumber(var) # sleep one second time.sleep(1) message = readString(14) print"RPi: I receive the string: ", message
voidsetup(){ Serial.begin(9600); // for serial debugging Wire.begin(IIC_SLAVE_ADDR); Wire.onReceive(receiveData); Wire.onRequest(sendData); Serial.println("Ready"); }
On Arduino you will see:
On RPi you will see:
This suggests that these two kinds of IIC protocals are slightly different. Because everytime when Pi requires Arduino to send a block of data, Arduino takes it as not only a send command but also an invalid receive command. Also Arduino won’t send the ‘\0’ of a string. Therefore, we can let Arduino take the receive data 0 as a signal of bytes transfer.
Experiment: write random numbers into EEPROM of Arduino and read from Pi
评论
shortname
for Disqus. Please set it in_config.yml
.