1

我正在寻找一个关于如何通过 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);
    }

  }
}

目标:
我通过 I2Clong从我的 Arduino 板向 Raspberry Pi 发送一个号码,但我试图让这个示例工作但没有成功。如何获取long从 Raspberry Pi 读取的数字?

在 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

我该如何使用它?

4

1 回答 1

0

I2C 在“从属”系统下工作,您必须在其中发送字节以确认您想要从中获取数据的连接设备,并且设备会做出相应的响应。正在使用的读取方法不发送标志字节,因此永远不会取回数据;I2C 是一种按需通信方式。

I2C 概述:I2C 总线协议教程,与应用程序的接口

于 2019-03-12T14:59:10.240 回答