我正在寻找一个关于如何通过I2C在Raspberry Pi上读取超过1个字节的示例。我只看到这个,但只适用于发送的第一个字节:
package i2crpiarduino;
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CDevice;
import com.pi4j.io.i2c.I2CFactory;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Arduino
{
public final static int ARDUINO_ADDRESS = 0x04; // See RPi_I2C.ino
private static boolean verbose = "true".equals(System.getProperty("arduino.verbose", "false"));
private I2CBus bus;
private I2CDevice arduino;
public Arduino() throws I2CFactory.UnsupportedBusNumberException
{
this(ARDUINO_ADDRESS);
}
public Arduino(int address) throws I2CFactory.UnsupportedBusNumberException
{
try
{
// Get i2c bus
bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends onthe RasPI version
if (verbose)
System.out.println("Connected to bus. OK.");
// Get device itself
arduino = bus.getDevice(address);
if (verbose)
System.out.println("Connected to device. OK.");
}
catch (IOException e)
{
System.err.println(e.getMessage());
}
}
public void close()
{
try { this.bus.close(); }
catch (IOException ioe) { ioe.printStackTrace(); }
}
/*
* methods readArduino, writeArduino
* This where the communication protocol would be implemented.
*/
public int readArduino()
throws Exception
{
int r = arduino.read();
return r;
}
public void writeArduino(byte b)
throws Exception
{
arduino.write(b);
}
private static void delay(float d) // d in seconds.
{
try { Thread.sleep((long)(d * 1000)); } catch (Exception ex) {}
}
public static void main(String[] args) throws I2CFactory.UnsupportedBusNumberException
{
final NumberFormat NF = new DecimalFormat("##00.00");
Arduino sensor = new Arduino();
int read = 0;
while(true)
{
try
{
read = sensor.readArduino();
}
catch (Exception ex)
{
System.err.println(ex.getMessage());
ex.printStackTrace();
}
System.out.println("Read: " + NF.format(read));
delay(1);
}
}
}
目的:
我通过I2C向我的Arduino板发送了一个long
号码给Raspberry Pi,但是我试图使这个例子无效。我如何从Raspberry Pi中读取long
数字?
在javadoc我看到这个:
public int read(byte[] buffer, int offset, int size) throws IOException
This method reads bytes directly from the i2c device to given buffer at asked offset.
Parameters:
buffer - buffer of data to be read from the i2c device in one go offset - offset in buffer size - number of bytes to be read
Returns:
number of bytes read
Throws:
IOException - thrown in case byte cannot be read from the i2c device or i2c bus
我该怎么用?
I2C工作在“从”系统中,您必须发送字节,确认您想要数据的连接设备,并且设备会相应地做出响应。使用的read方法不发送标志字节,因此永远不会返回数据; I2C是一种按需的通信方法。
I2C概述:I2C bus protocol Tutorial, Interface with applications