When I searched for a closet to see if there were any parts that could be used to make a robot, I bought a motor driver for Raspberry pi a long time ago, but only the library for Arduino was prepared and it was stored in the motor driver (Grove's I2C). Discovered Motor Driver V1.3). He decided to translate it in python for Raspberry pi because he was free on the make-up day.
Since the motor driver this time communicates with the microcomputer using the communication method called I2C, I decided to start with that understanding.
I can't put it together well, so I'll leave the details to this site ([How to use I2C communication] [1]). Roughly speaking, it seems to communicate like this.
I somehow understood the I2C communication method, so I saw how it was written in the sample program for Arduino. (Excerpt of communication part only)
Wire.begin();
delayMicrosecond(10000);
Wire.beginTransmission(i2c_add);
Wire.write(0x82);
Wire.write(0x0a);
Wire.write(0x01);
Wire.endTransmission();
Roughly speaking, the first and second lines initialize the communication, and the fourth line sends the slave address. Data is sent on the 5th to 7th lines. It was like the end of communication on the 9th line.
Since it is troublesome to make I2C communication from scratch, I decided to use the communication library smbus for Raspberry pi. With this,
import smbus
i2c = smbus.SMBus(1)
i2c.write_i2c_block_data(i2c_add,0x82,[0x0a,0x01])
It fits in 3 lines like this.
The first line is for importing the library, the second line is for creating an instance for communication, and the Raspberry pi uses 1 for the I2C bus (I'm not sure), so this seems to be SMBus (1), and the third line is the communication instruction. Sentence.
Here, the reason why the arguments 0x82, [0x0a, 0x01] are divided into the front one and the back two is On the Arduino side, all three of 0x82, 0x0a, 0x01 written in Wire.write have been grouped as "data" above, but 0x82 is the address of the register in the slave, and 0x0a, 0x01 is that register. It was because the meaning was a little different from the data written in.
If you use smbus, you can rewrite communication in about three lines above, and the most important thing is
i2c.write_i2c_block_data(Slave address,Register address,[Data to write])
This sentence. This time I used this instruction because the data to be written is 1 byte or more, but if it is 1 byte
i2c.write_byte_data(Slave address,Register address,Data to write)
Use this, both addresses and data can be specified as int type. [1]:http://www.picfun.com/c15.html#:~:text=I2C%EF%BC%88Inter%2DIntegrated%20Circuit%EF%BC%89,%E3%82%92%E5%AE%9F%E7%8F%BE%20%E3%81%99%E3%82%8B%E6%96%B9%E5%BC%8F%E3%81%A7%E3%81%99%E3%80%82
Recommended Posts