You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import com.pi4j.context.Context;
import com.pi4j.io.spi.Spi;
import com.pi4j.io.spi.SpiMode;
import com.pi4j.io.spi.SpiProvider;
import com.pi4j.io.gpio.digital.DigitalOutput;
import com.pi4j.io.gpio.digital.DigitalState;
/**
* Base class for {@link SPIBus} devices.
*/
public class MCP3008 extends SPIBus {
public static DigitalOutput chipSelectMCP3008;
/**
* Creates a {@link MCP3008}.
*/
public MCP3008(Spi bus) {
super(bus);
}
/**
* Creates a new {@link MCP3008} device.
*
* @param pi4j {@link Context}
* @param cs Number of Pin for ChipSelect
* @return The new device.
*/
public static MCP3008 create(Context pi4j, int cs) {
createCS(pi4j,cs);
SpiProvider spiProvider = pi4j.provider("pigpio-spi");
var config = Spi.newConfigBuilder(pi4j)
.id("mcp3008")
.name("MCP3008 ADC-Module")
.address(0)
.mode(SpiMode.MODE_1)
.baud(500000)
.build();
return new MCP3008(spiProvider.create(config));
}
/**
* Creates a new {@link MCP3008} device.
*
* @param pi4j {@link Context}
* @param cs Number of Pin for ChipSelect
*/
public static void createCS(Context pi4j, int cs) {
var lgpio8Config = DigitalOutput.newConfigBuilder(pi4j)
.id("gpio8")
.name("Output for Chipselect MCP3008")
.address(cs)
.shutdown(DigitalState.HIGH)
.initial(DigitalState.HIGH)
.provider("pigpio-digital-output");
chipSelectMCP3008 = pi4j.create(lgpio8Config);
}
/**
* reads the ADC-Value (0..1023 | 1024 digits);
*
* @param channel ADC-Channel we read from
* @return Integer with ADC-Value.
*/
public int readADC(byte channel){
chipSelectMCP3008.low();
transferMessageMCP3008(channel);
chipSelectMCP3008.high();
return messageToUnsignedIntMCP3008();
}
}
SPIBus.java
import com.pi4j.io.spi.Spi;
/**
* Base class for {@link SPIBus} devices.
*/
public class SPIBus {
private final Spi _bus;
private final byte[] _wrBufSpi = new byte[3];
private final byte[] _rdBufSpi = new byte[3];
/**
* Creates a {@link SPIDevice}.
*
* @param bus The {@link Spi} bus to communicate with.
*/
public SPIBus(Spi bus) {
_bus = bus;
}
public final void transferMessageMCP3008(byte channel) {
_wrBufSpi[0] = (byte) 0b00000001;
_wrBufSpi[1] = channel;
_wrBufSpi[2] = 0x00;
_bus.transfer(_wrBufSpi,_rdBufSpi,3);
}
public int messageToUnsignedIntMCP3008 () {
int unsignedInt;
unsignedInt = ((_rdBufSpi[1] & 0xff) << 8) | (_rdBufSpi[2] & 0xff);
return unsignedInt;
}
}```
The text was updated successfully, but these errors were encountered:
Heres an example for MCP3008 on SPI
MCP3008.java
SPIBus.java
The text was updated successfully, but these errors were encountered: