- Code: Select all
import lejos.nxt.*;
/**
* This class is used to communicate with a PCF8574 two-wire I2C-bus
* to 8-bit parallel bus I/O expander.
*
*/
public class PCF8574 {
/**
* Returns the sensor port.
*/
private I2CPort I2Cport;
/**
* Returns the sensor address.
* Values range from 0x20 - 0x27 (or 0x38 - 0x3F when using a PCF8574A).
*/
private byte address;
/**
* Returns the current data value.
*/
private byte[] data = {0x00};
/**
* Initializes the PCF8574 sensor.
* @param sensorPort NXT sensor port.
* @param address sensor address. Values range from 0x20 - 0x27
* (or 0x38 - 0x3F when using a PCF8574A).
*/
public PCF8574(I2CPort sensorPort, byte sensorAddress) {
I2Cport = sensorPort;
address = sensorAddress;
I2Cport.i2cEnable(I2CPort.STANDARD_MODE);
}
/**
* Method for sending data to sensor.
* @param value Data to send.
* @return
*/
public void sendData(byte value) {
data[0] = value;
I2Cport.i2cStart(address, 0x00, 0, data, 1, 1);
while (I2Cport.i2cBusy() != 0) {
Thread.yield();
}
}
/**
* Method for retrieving the data from the sensor.
* @return value of 8-bit parallel bus port.
*/
public int getData() {
int ret = I2Cport.i2cStart(address, 0x00, 0, data, 1, 0);
if (ret != 0) return -1;
while (I2Cport.i2cBusy() != 0) {
Thread.yield();
}
return (0xFF & data[0]);
}
/**
* Method for retrieving the status of one sensor port.
* @param port the sensor port. Values range from 1-8. This is the PCF8574, not the NXT port.
* @return value of sensor port. 1 means port is high, 0 means port is low (pulled to ground).
*/
public int getSensorPortStatus(int sensorPort) {
int result = -1;
int mask = -1;
int data = getData(); //get status of all ports from sensor
//create a mask to logically AND the data with...
mask = 1 << (sensorPort - 1);
result = (byte)mask & (byte)data;
if ( result > 0 ) {
return 1;
}else {
return 0;
}
}
}

