我正在寻找一个关于如何通过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
我该怎么用?