Giter Site home page Giter Site logo

pi4j-v2's Introduction

Pi4J :: Java I/O Library for Raspberry Pi

Maven Central Sonatype Nexus (Snapshots) License

Site Chat on Slack Pi4J on Mastodon Pi4J on LinkedIn Pi4J on Twitter

Project Map: Project Map


Project Information for V2 of Pi4J

Project website: pi4j.com.

This project is intended to provide a friendly object-oriented I/O API and implementation libraries for Java Programmers to access the full I/O capabilities of the Raspberry Pi platform. This project abstracts the low-level native integration and interrupt monitoring to enable Java programmers to focus on implementing their application business logic.

Pi4J diagram

Builds are available from:

Using Pi4J

When you want to use Pi4J in your project, you should definitely check out the Pi4J website where you can find a lot of information and many examples!

For example, for a minimal example to blink a LED (fully explained here), you need to import the dependencies and use this code:

var pi4j = Pi4J.newAutoContext();

var led = pi4j.digitalOutput().create(PIN_LED);

while (true) {
  if (led.state() == DigitalState.HIGH) {
    led.low();
  } else {
    led.high();
  }
  Thread.sleep(500);
}

Contributing to Pi4J

For full description of the code structure, how to compile... see the "About the code" on our website.

Pi4J V2 code structure

Project Overview

Starting with the Pi4J 2.0 builds, the Pi4J project is prioritizing focus on providing Java programs access, control and communication with the core I/O capabilities of the Raspberry Pi platform.

Read all about it on pi4j.com: "What’s New in 2.0?".

Build Instructions

The Pi4J V2 codebase can be built using Apache Maven 3.6.x. and Java JDK 11. The following command can be used to build the Pi4J V2 JARs:

mvn clean install

Pi4J V2 also includes native libraries that will need to be compiled if you are modifying any native code. Most users will never need to compile the native libraries as these artifacts are automatically downloaded
when building the Pi4J JARs from Maven repositories. One of the following commands can be used to build the Pi4J V2 JARs and Native Libraries:

mvn clean install -Pnative
mvn clean install -Pnative,docker

NOTE: A comprehensive set of build instructions can be found in the Pi4J V2 Documentation.

Adding a feature or solving a problem

If you have and idea to extend and improve Pi4J, please first create a ticket to discuss how it fits in the project and how it can be implemented.

If you find a bug, create a ticket, so we are aware of it and others with the same problem can contribute what they already investigated. And the quickest way to get a fix? Try to search for the cause of the problem or even better provide a code fix!

Join the team

You want to become a member of the Pi4J-team? Great idea! Send a short message to [email protected] with your experience, ideas, and what you would like to contribute to the project.

Previous Releases

License

Pi4J Version 2.0 and later is licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright (C) 2012-2024 Pi4J

pi4j-v2's People

Contributors

aero-don avatar akuhtz avatar alex9849 avatar bwaldvogel avatar eitch avatar fdelporte avatar fusetim avatar gevanco avatar gugrim avatar harlanhu avatar haumacher avatar iamnicknack avatar joelspecht avatar mheath avatar mirage22 avatar mmmmmng avatar savageautomate avatar taartspi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pi4j-v2's Issues

Native binaries for ARMv6 (Pi Zeros) are incompatible.

As noted in issue #27, the native builds for ARMv6 (Pi Zeros and all Generation 1 models) are not working.
The 32-bit binaries compiled are not ARMv6 compatible.

This issue affects the following Raspberry Pi models

  • RPi 1 Model A
  • RPi 1 Model A+
  • RPi 1 Model B
  • RPi 1 Model B+
  • RPi Compute Module 1
  • RPi Zero
  • RPi Zero W

(from https://en.wikipedia.org/wiki/Raspberry_Pi)

Changes to native build happened here: a7c29d0

I switched from ARM compiler toolchain available from RaspberryPi Tools to a newer GCC version 32-bit cross-compiler (gcc-arm-linux-gnueabihf) toolchain available in APT repositories.

REF: https://github.com/Pro/raspi-toolchain

By default, newer GCC versions do not create correct binaries for ARMv6. Even though you pass the correct -mcpu= flag to gcc, it will create startup code for the newer ARMv7 architecture. Running them on your RasPI Zero will cause an "Illegal Instruction" exception.

I probably need to instrument one of these custom toolchains in the build logic for building 32-bit rather than the default linarogcc-arm-linux-gnueabihf

PWM does not work for Pi4J 2.0 - Why?

Hi!

I'm doing PWM but I cannot see any PWM signal when I try to connect.

I'm set the duty cycle the PWM with
pwm0.setDutyCycle(do0/ControlView.MAX_SLIDER_VALE);

https://github.com/DanielMartensson/OpenSourceLogger/blob/master/src/main/java/se/danielmartensson/threads/ControlThread.java

And the PWM decleration looks like this:

// This will turn on/off the FQP30N06L MOSFET
	private Pwm createDigitalPWMOutput(int pinOutput, Context pi4j, String id) {
        try {
            // use try-with-resources to auto-close I2C when complete
        	PwmConfig config = Pwm.newConfigBuilder(pi4j)
                    .id(id)
                    .name("PWM Pin output")
                    .address(pinOutput)
                    .pwmType(PwmType.SOFTWARE)
                    .frequency(pwmFrequency)   // optionally pre-configure the desired frequency to 1KHz
                    .dutyCycle(0)     // optionally pre-configure the desired duty-cycle (50%)
                    .shutdown(0)       // optionally pre-configure a shutdown duty-cycle value (on terminate)
                    .initial(0)     // optionally pre-configure an initial duty-cycle value (on startup)
                    .build();
        	Pwm pwm = pi4j.providers().get(PiGpioPwmProvider.class).create(config);
        	pwm.on();
			return pwm;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

https://github.com/DanielMartensson/OpenSourceLogger/blob/master/src/main/java/se/danielmartensson/pi4j/IO.java

The pwmFrequency is 100

libpi4j-pigpio.so: to include or not to include, that's the question...

At this moment libpi4j-pigpio.so is packaged inside a jar

Pro

  • will be available when needed
  • no separate installation needed

Contra

  • when building Pi4J on another device, cross-compiling needed
  • problem 32 versus 64 bit?

To be decided

  • Include - not include
  • If not included can we check at program startup if necesarry file can be found?
  • If not found, can we show clear message about the missing file?
  • If not found, can we provide easy-to-use install script?

66666

i am the first one write Issues .haha
wish pi4j v2 better

Data from SPI not correct

As reported by Jim Darby:
I've had some very strange errors when not running as root and using pigpiod. Sometimes when you read from a SPI device you get back more data than you sent. This shouldn't be possible and I'm still investigating.

SPI configuration example

Hello,

I'm looking for some example of SPI configuration where it is possible to select CS line and spiFlags as it is in pigpio:

int spiOpen(unsigned spiChan, unsigned baud, unsigned spiFlags)

Current SPI implementation available as example does not allowed to set even CS line:

        var config = Spi
                .newConfigBuilder(pi4j)
                    .id("my-spi-device")
                    .name("My SPI Device")
                    .address(SPI_CHANNEL)
                    .mode(SpiMode.MODE_0)
                    .baud(Spi.DEFAULT_BAUD)
                    .build();

I've found that SPI implementation I'm looking for is available in PiGpioNativeImpl. This is how I'm going to use it:

piGpio = PiGpioNativeImpl.newInstance();
piGpio.initialize();
spiHandler = piGpio.spiOpen(1, 15600000, 0x0140);    //0x140 -> SPI AUX with BCM17 as CS

byte[] data = new byte[2];
data[0] = (byte)0x70;
data[1] = (byte)0x3C;
piGpio.spiWrite(spiHandler, data, 2);
piGpio.spiClose(spiHandler);
piGpio.shutdown();

I'm not sure how to incorporate above to Context. Should I create context (var pi4j = Pi4J.newAutoContext()) before using SPI?

Thanks in advance for your support.

BTW: please consider to release pi4j v2 and let people to play with it. Thanks to this you will have users feedback and probably more pull-requests and maybe few more contributors in development.

Multipurpose (Input & Output) GPIO

The Context
I'm in the process of porting the libraries of Skywriter & Flick I2C gesture sensing boards from python to Java/pi4j. Both boards utilise the MGC3130 chipset.

The Problem
The MGC3130 chipset requires the transfer pin (BCM 27) to be used as both input and output within each polling cycle. At the start of the cycle the library waits for a low transfer line (input). However, the library then reconfigures the same pin (BCM27) as a low output to assert that the MGC3130 does not update data buffers before reading from them.

The Issue
Does pi4j-v2 support Multipurpose GPIO that can be reconfigured to work as input and output?

Unmapping/remapping pins

If I create an IO config for a pin with

config = DigitalInput.newConfigBuilder(rpi4j).provider("pigpio-digital-input").id("pin-"+pinNumber).address(pinNumber)....
pin = rpi4j.create(config);

the name "pinX" is registered in the Registry and the pin works accordingly.

If I then want to disconnect the pin I call
pin.shutdown(rpi4j);
which seems to forward the disconnect to pigpio but doesn't unregister the IO in the Registry.

Any attempt to then create a new config with the same id creates an exception:

com.pi4j.io.exception.IOAlreadyExistsException: IO instance [pin14] already exists in the Pi4J runtime context; unable to create a new instance using this reserved id.
	at com.pi4j.provider.impl.ProviderProxyHandler.invoke(ProviderProxyHandler.java:99)
	at com.sun.proxy.$Proxy2.create(Unknown Source)
	at com.pi4j.context.Context.create(Context.java:309)
	at com.pi4j.internal.IOCreator.create(IOCreator.java:60)
	at com.pi4j.internal.IOCreator.create(IOCreator.java:101)
	at com.pi4j.internal.IOCreator.create(IOCreator.java:189)
        ...

The registry on the autoContext doesn't seem to have a way to remove things from it (it is a DefaultRegistry not RuntimeRegistry)

Extend GitHub actions for automated publishing to oss.sonatype.org

Up till now pushing new versions to Maven Repository has been a manual process, but to improve the release of new versions, it would be great to have this further automated.

Already done

To do (initial idea for further discussion)

  • Add oss.sonatype.org commit keys to github project > settings > secrets > actions
  • Define roles and restrict merge rights for feature, bug and release branches
  • Further configure pom.xml, github action(s) and repository settings to have an automated way to publish
    • each change in main branch = new snapshot push to oss.sonatype.org
    • when release branch gets merged = new release push to oss.sonatype.org

Inspiration can be found on

Better Support for Custom Plugin Class Loading Strategies

I'd like to compile my code against pi4j-core but allow the user to provide plugin jars (such as pi4j-plugin-mock) in a well-known directory at runtime. In order to do this, I need to use a custom ClassLoader to look for plugins in the plugins directory. This is typically done by setting the current Thread's context ClassLoader, but current PI4J v2 code is not respecting this ClassLoader in com.pi4j.provider.impl.DefaultRuntimeProviders#add(Collection<T> provider) (around line 267). When creating a provider proxy, it is instead using the ClassLoader which loaded the com.pi4j.provider.Provider class, which will be the Application's ClassLoader instance (which will not know how to find plugins in our special directory).

The simple fix is to change this provider proxy creation code from:

var providerProxy = Proxy.newProxyInstance(
        Provider.class.getClassLoader(),
        ReflectionUtil.getAllInterfaces(providerInstance).toArray(new Class[]{}),
        handler);

to:

var providerProxy = Proxy.newProxyInstance(
        Thread.currentThread().getContextClassLoader(),
        ReflectionUtil.getAllInterfaces(providerInstance).toArray(new Class[]{}),
        handler);

See this SSCCE for a more detailed example: https://github.com/joelspecht/pi4j-v2-classloader-sscce

Use of signal handlers needs to be improved

As reported by Jim Darby:
If you're running as root (never a good idea) and using pigpio directly then pigpio steals all the signal handlers. The JVM doesn't like this as it uses them in running the JVM so it ends up with the program crashing. I'm working on this by getting pi4j-v2 to put back the signal handlers that the JVM uses.

Build profile `javadoc` fails to compile.

When attempting to Maven compile the project with build profile javadoc, the build fails.

Build command:

 mvn clean install -Pjavadoc

Error message:

[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary for Pi4J :: Parent POM 2.0-SNAPSHOT:
[INFO] 
[INFO] Pi4J :: Parent POM ................................. SUCCESS [  1.493 s]
[INFO] Pi4J :: DOCKER   :: Docker Parent POM .............. SUCCESS [  0.292 s]
[INFO] Pi4J :: LIBRARY  :: Libraries Parent POM ........... SUCCESS [  0.032 s]
[INFO] Pi4J :: LIBRARY  :: JNI Wrapper for PIGPIO Library . FAILURE [  5.232 s]
[INFO] Pi4J :: LIBRARY  :: Java Library (CORE) ............ SKIPPED
[INFO] Pi4J :: PLUGIN   :: Plugins Parent POM ............. SKIPPED
[INFO] Pi4J :: PLUGIN   :: Mock Platform & Providers ...... SKIPPED
[INFO] Pi4J :: PLUGIN   :: PIGPIO I/O Providers ........... SKIPPED
[INFO] Pi4J :: PLUGIN   :: RaspberryPi Platform & Providers SKIPPED
[INFO] Pi4J :: TESTING  :: Unit/Integration Tests ......... SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  8.986 s
[INFO] Finished at: 2020-06-11T15:30:35-04:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:3.2.0:jar (attach-javadocs) on project pi4j-library-pigpio: MavenReportException: Error while generating Javadoc: 
[ERROR] Exit code: 1 - /Users/roberts/dev/pi4j-v2/libraries/pi4j-library-pigpio/src/main/java/module-info.java:32: error: module not found: org.slf4j
[ERROR]     requires org.slf4j;
[ERROR]                 ^
[ERROR] 
[ERROR] Command line was: /Library/Java/JavaVirtualMachines/jdk-11.0.4.jdk/Contents/Home/bin/javadoc @options @packages @argfile
[ERROR] 
[ERROR] Refer to the generated Javadoc files in '/Users/roberts/dev/pi4j-v2/libraries/pi4j-library-pigpio/target/apidocs' dir.
[ERROR] 

This Javadoc build profile is part of the release build steps to generate JavaDoc for all project JARs and attach them as artifacts to deploy to Maven repositories.

This issue will need to get resolved prior to a release build.

PS: Apart from this initial error, there are also several JavaDoc specific code issues that will also need to get addressed.

[Enhancement] Wifi scan and connection

MOVED FROM Pi4J/pi4j-v1#508


It would be nice to be able to:

  • Scan Wifis
  • Get all the informations about distant Wifis
  • Connect to a Wifi
  • Disconnect from the current Wifi

I know how to do it using:

  • The /etc/wpa_supplicant/wpa_supplicant.conf to reference all the known Wifis ssid and password.
  • Hash the password using the wpa_passphrase command.
  • Enable/Disable the wifi using the sudo ifconfig wlan0 up or sudo ifconfig wlan0 down command.
  • Reboot the wifi using the sudo wpa_cli -i wlan0 reconfigure command.

I can help you on that but I need your opinion. Do you authorize bash wrappers ?
Thanks

Can a flag be added to define the polarity of a digital output?

In a project where a relay is used, the digital output must be used "inverted" to control the relay because "LOW" sets the relay and "HIGH" resets it. This results in this code:

image

Maybe it could be an idea to extend DigitalOutput in the library with an isInverted flag. But this would also mean all output methods have to take this flag into account.

Extend the Platform implementation

Note from a discussion on the state of Pi4J V2

The idea was "Platform" represented the target hardware or embedded device and environment a user would run Pi4J from. Such as the "RaspberryPi" platform. A platform could support multiple providers. A platform may assign default providers for each IO type.

When creating a Pi4J Context only a single (default) Platform is held by the context. This platform may be auto-detected based on the presence of a Pi4J platform JAR in the path. If multiple platform JARs are detected there must be some order of precedence determined which is the Default platform.

Not sure how evolved or how complete the concept of Platform is in the current codebase. So it may need some work.

Context should be renamed

I think we should rename Pi4j class to Pi4jProvider and Context to Pi4j.

Currently in all the code examples we use the following code:

var pi4j = Pi4J.newAutoContext();

Some people like to use these vars, but others like to use the actual class. And in this case the class is Context, but the variable is pi4j. IMHO this does not make sense.

So if we rename as described, we get this:

var pi4j = Pi4JProvider.newAutoContext();

or this:

Pi4j pi4j = Pi4JProvider.newAutoContext();

which looks much better and makes more sense for newbies.

I2C does not work

With the following setup:

JARs built from main:

pi4j-core-2.0-SNAPSHOT.jar
pi4j-library-pigpio-2.0-SNAPSHOT.jar
pi4j-plugin-pigpio-2.0-SNAPSHOT.jar
pi4j-plugin-raspberrypi-2.0-SNAPSHOT.jar
slf4j-api-1.7.30.jar
slf4j-simple-1.7.30.jar

Script:

import com.pi4j.Pi4J;
import com.pi4j.context.Context;
import com.pi4j.io.i2c.I2C;
import com.pi4j.io.i2c.I2CConfig;
import com.pi4j.io.i2c.I2CProvider;

public class Tca9534Test {

  private static final byte TCA9534_REG_ADDR_OUT_PORT = 0x01;
  private static final byte TCA9534_REG_ADDR_CFG = 0x03;

  public static void main(String[] args) throws Exception {

    Context pi4j = Pi4J.newAutoContext();
    I2CProvider i2CProvider = pi4j.provider("pigpio-i2c");
    I2CConfig i2cConfig = I2C.newConfigBuilder(pi4j).id("TCA9534").bus(1).device(0x3f).build();
    try (I2C tca9534Dev = i2CProvider.create(i2cConfig)) {

      int config = tca9534Dev.readRegister(TCA9534_REG_ADDR_CFG);
      if (config < 0)
        throw new IllegalStateException(
            "Failed to read configuration from address 0x" + String.format("%02x", TCA9534_REG_ADDR_CFG));

      byte currentState = (byte) tca9534Dev.readRegister(TCA9534_REG_ADDR_OUT_PORT);

      if (config != 0x00) {
        System.out.println("TCA9534 is not configured as OUTPUT, setting register 0x" + String
            .format("%02x", TCA9534_REG_ADDR_CFG) + " to 0x00");
        currentState = 0x00;
        tca9534Dev.writeRegister(TCA9534_REG_ADDR_OUT_PORT, currentState);
        tca9534Dev.writeRegister(TCA9534_REG_ADDR_CFG, (byte) 0x00);
      }

      currentState = setPin(currentState, 8, tca9534Dev, true);
      Thread.sleep(500L);
      currentState = setPin(currentState, 8, tca9534Dev, false);
      Thread.sleep(500L);

      currentState = setPin(currentState, 7, tca9534Dev, true);
      Thread.sleep(500L);
      currentState = setPin(currentState, 7, tca9534Dev, false);
      Thread.sleep(500L);
    }
  }

  public static byte setPin(byte currentState, int pin, I2C tca9534Dev, boolean high) {
    byte newState;
    if (high)
      newState = (byte) (currentState | (1 << pin));
    else
      newState = (byte) (currentState & ~(1 << pin));

    System.out.println("Setting TCA9534 to new state " + asBinary(newState));
    tca9534Dev.writeRegister(TCA9534_REG_ADDR_OUT_PORT, newState);
    return newState;
  }

  public static String asBinary(byte b) {

    StringBuilder sb = new StringBuilder();

    sb.append(((b >>> 7) & 1));
    sb.append(((b >>> 6) & 1));
    sb.append(((b >>> 5) & 1));
    sb.append(((b >>> 4) & 1));
    sb.append(((b >>> 3) & 1));
    sb.append(((b >>> 2) & 1));
    sb.append(((b >>> 1) & 1));
    sb.append(((b >>> 0) & 1));

    return sb.toString();
  }
}

Running:

java -cp pi4j-core-2.0-SNAPSHOT.jar:pi4j-library-pigpio-2.0-SNAPSHOT.jar:pi4j-plugin-pigpio-2.0-SNAPSHOT.jar:pi4j-plugin-raspberrypi-2.0-SNAPSHOT.jar:slf4j-api-1.7.30.jar:slf4j-simple-1.7.30.jar Tca9534Test.java

The pi4j context fails with the following output:

[main] INFO com.pi4j.Pi4J - New auto context
[main] INFO com.pi4j.Pi4J - New context builder
[main] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_INIT_FAILED; pigpio initialisation failed
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
    at com.sun.proxy.$Proxy3.create(Unknown Source)
    at Tca9534Test.main(Tca9534Test.java:17)
Caused by: java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.pi4j.provider.impl.ProviderProxyHandler.invoke(ProviderProxyHandler.java:102)
    at com.sun.proxy.$Proxy3.create(Unknown Source)
    at Tca9534Test.main(Tca9534Test.java:17)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at jdk.compiler/com.sun.tools.javac.launcher.Main.execute(Main.java:404)
    at jdk.compiler/com.sun.tools.javac.launcher.Main.run(Main.java:179)
    at jdk.compiler/com.sun.tools.javac.launcher.Main.main(Main.java:119)
Caused by: com.pi4j.library.pigpio.PiGpioException: PIGPIO ERROR: PI_INIT_FAILED; pigpio initialisation failed
    at com.pi4j.library.pigpio.impl.PiGpioBase.validateResult(PiGpioBase.java:265)
    at com.pi4j.library.pigpio.impl.PiGpioBase.validateResult(PiGpioBase.java:251)
    at com.pi4j.library.pigpio.impl.PiGpioNativeImpl.gpioInitialise(PiGpioNativeImpl.java:97)
    at com.pi4j.library.pigpio.PiGpio.initialize(PiGpio.java:146)
    at com.pi4j.plugin.pigpio.provider.i2c.PiGpioI2CProviderImpl.create(PiGpioI2CProviderImpl.java:62)
    at com.pi4j.plugin.pigpio.provider.i2c.PiGpioI2CProviderImpl.create(PiGpioI2CProviderImpl.java:43)
    ... 14 more

PiGpio error: PI_I2C_READ_FAILED; I2C read failed

Hi!

Just started to read values with I2C and it failed.
Code: https://github.com/DanielMartensson/OpenSourceLogger/blob/master/src/main/java/se/danielmartensson/pi4j/ADS1115_ADS1015.java

Also code in C:
https://github.com/DanielMartensson/STM32-Libraries/blob/master/ADS1015_ADS1115/ADS1015_ADS1115.c

Suggestion:
It should be a method in I2C library so it's possible to send int arrays, instead of only byte arrays.
Java don't have unsigned datatypes. But int can be between 0 and 255 and above that. Byte can only be between -127 and 128.

[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_READ_FAILED; I2C read failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_READ_FAILED; I2C read failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_READ_FAILED; I2C read failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_READ_FAILED; I2C read failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed
^C[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_READ_FAILED; I2C read failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[SpringContextShutdownHook] INFO org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor - Shutting down ExecutorService 'applicationTaskExecutor'
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[SpringContextShutdownHook] INFO org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[SpringContextShutdownHook] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
[Thread-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_BAD_HANDLE; unknown handle
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x8ea32080, pid=1839, tid=1910
#
# JRE version: OpenJDK Runtime Environment (11.0.7+10) (build 11.0.7+10-post-Raspbian-3deb10u1)
# Java VM: OpenJDK Server VM (11.0.7+10-post-Raspbian-3deb10u1, mixed mode, g1 gc, linux-)
# Problematic frame:
# C  [libpigpio.so.1+0x13080]  gpioRead+0x7c
#
# No core dump will be written. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# /home/pi/Documents/hs_err_pid1839.log
[SpringContextShutdownHook] INFO com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.
#
# If you would like to submit a bug report, please visit:
#   Unknown
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
Avbruten (SIGABRT)
pi@raspberrypi:~/Documents $ 

Create BUILD.INSTRUCTIONS

Add a BUILD.INSTRUCTIONS file to the project to document how users and contributors can build the project sources.

Make sure to include information about the following:

  • Build Profiles (native, javadoc, docker, etc)
  • Native Builds (32-bit, 64-bit, Cross-compiler, Docker-compiler, etc)
  • Release Builds
  • Custom Maven settings.xml profile settings for Pi4J developers/contributrors
  • Environment variables
  • Requirements (JDK Version, Maven version, Docker, etc)

Trouble with I2C

Hi,

I try to get a stripped-down version of the example for I2C from the PI4J site (https://pi4j.com/documentation/io-examples/i2c/) running.

The main method starts with the following statements:

		Context pi4j = Pi4J.newAutoContext();
		I2CProvider i2CProvider = pi4j.provider("linuxfs-i2c");

Unfortunately I get teh following exception when trying to get the I2CProvider:

Exception in thread "main" com.pi4j.provider.exception.ProviderNotFoundException: Pi4J provider [linuxfs-i2c] could not be found.  Please include this 'provider' JAR in the classpath.
        at [email protected]/com.pi4j.provider.impl.DefaultRuntimeProviders.get(DefaultRuntimeProviders.java:238)
        at [email protected]/com.pi4j.provider.impl.DefaultProviders.get(DefaultProviders.java:147)
        at [email protected]/com.pi4j.context.Context.provider(Context.java:240)
        at [email protected]/de.rziegaus.SimpleATECC608A.main(SimpleATECC608A.java:18)

So I added the dependency for linuxfs-i2c, but now I get a different problem with the program. Now I get an exception saying

Error occurred during initialization of boot layer
java.lang.LayerInstantiationException: Package lib.armhf in both module com.pi4j.library.pigpio and module com.pi4j.library.linuxfs

If I remove the jar files concerning pigpio (library and plugin) manually everything works fine - at least I don't get any errors when I run the stripped-down version of the program.

What concerns me a bit - do I really have to choose between either pigpio and linuxfs-i2c? Or is there a workaround?

No hardware PWM's on all GPIO

Hi!

Just started with Pi4J 2.0 and I got an error.

2020-07-10 15:44:02 gpioHardwarePWM: bad gpio for PWM (3)
[http-nio-8080-exec-5] WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_NOT_HPWM_GPIO; GPIO has no hardware PWM

And the Java code:

   // This will turn on/off the FQP30N06L MOSFET
  private Pwm createDigitalPWMOutput(int pinOutput, Context pi4j) {
      try {
          // use try-with-resources to auto-close I2C when complete
      	PwmConfig config = Pwm.newConfigBuilder(pi4j)
                  .id("my-pwm-pin")
                  .name("My Test PWM Pin")
                  .address(pinOutput)
                  .pwmType(PwmType.HARDWARE)
                  .frequency(pwmFrequency)   // optionally pre-configure the desired frequency to 1KHz
                  .dutyCycle(0)     // optionally pre-configure the desired duty-cycle (50%)
                  .shutdown(0)       // optionally pre-configure a shutdown duty-cycle value (on terminate)
                  .initial(0)     // optionally pre-configure an initial duty-cycle value (on startup)
                  .build();
      	Pwm pwm = pi4j.providers().get(PiGpioPwmProvider.class).create(config);
      	pwm.on();
  		return pwm;
  	} catch (Exception e) {
  		e.printStackTrace();
  	}
  	return null;
  }

I call that function with:

Context pi4j = Pi4J.newAutoContext();
Pwm pwm0 = createDigitalPWMOutput(3, pi4j);

That's weird because Pigpio says that there are 0-31 hard ware PWM's
http://abyz.me.uk/rpi/pigpio/

pigpio initialisation failed

I get the following error:

WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_INIT_FAILED; pigpio initialisation failed
java.lang.reflect.InvocationTargetException

when I try:

var pi4j = Pi4J.newAutoContext();

        var ledConfig = DigitalOutput.newConfigBuilder(pi4j)
                .id("led")
                .name("LED Flasher")
                .address(PIN_LED)
                .shutdown(DigitalState.LOW)
                .initial(DigitalState.LOW)
                .provider("pigpio-digital-output");

I have turned off any pigpio daemons before running the program, please also
Led1.pdf
see attached.

Setting hardware PWM frequency on Raspberry Pi Zero W

Hello!
I just started using pi4j 2.0 in my project and came across this. I am using one of the pins on PWM channel 1 to drive a MOSFET that dimms a LED strip, I want it to be running at 100 kHz, but it seems that to achieve so I need to add two extra zeros in the frequency:

displayLed = pi4j.create(Pwm.newConfigBuilder(pi4j)
                  .id("displayLed")
                  .pwmType(PwmType.HARDWARE)
                  .address(13)
                  .provider("pigpio-pwm")
                  .frequency(10000000)// Shouldn't this be 100 000?
                  .build());
displayLed.dutyCycle(80).on();

Also, the last line here actually doesn't turn the PWM output on, I need to call displayLed.on(); later to enable it.

Cannot extract native libraries from jar on Pi 4B

Hi, I get this error message when trying to use Pi4J v2 on a Raspberry Pi 4B from a "fat jar":

UnsatisfiedLinkError: Pi4J was unable to extract and load the native library [/lib/armhf/libpi4j-pigpio.so] from the embedded resources inside this JAR [/home/pi/myjar.jar]. to a temporary location on this system.  You can alternatively define the 'pi4j.library.path' system property to override this behavior and specify the library path.
	at com.pi4j.library.pigpio.util.NativeLibraryLoader.load(NativeLibraryLoader.java:172)
	at com.pi4j.library.pigpio.internal.PIGPIO.<clinit>(PIGPIO.java:76)
	at com.pi4j.library.pigpio.impl.PiGpioNativeImpl.gpioInitialise(PiGpioNativeImpl.java:97)
	at com.pi4j.library.pigpio.PiGpio.initialize(PiGpio.java:155)
	at com.pi4j.plugin.pigpio.provider.gpio.digital.PiGpioDigitalInputProviderImpl.create(PiGpioDigitalInputProviderImpl.java:64)
	at com.pi4j.plugin.pigpio.provider.gpio.digital.PiGpioDigitalInputProviderImpl.create(PiGpioDigitalInputProviderImpl.java:45)

The /tmp directory is writeable, and the library is in the correct path within the jar [/lib/armhf/libpi4j-pigpio.so], so I don't know why this is failing.

How do I enable log4j logging in Pi4j v2? I looked at the code in NativeLibraryLoader, but I can't see the debug messages on the console to determine what is going wrong here. I checked the docs but didn't see a suggestion about how to enable logging.

Error reporting on I2C write failure

Using pi4j-v2 and the writeRegister function on an SPI device I've found that I get the error:

WARN com.pi4j.library.pigpio.impl.PiGpioNativeImpl - PIGPIO ERROR: PI_I2C_WRITE_FAILED; I2C write failed

but the return value from writeRegister is the length of the data that I wanted written so I don't get to hear of the problem.

Ideas anyone?

Pi4J is unusable with lambdas because of all the checked exceptions

I'm finding it incredibly difficult to use Pi4J 2.x with lambdas because so many methods are declared to throw Exception.

For example, I find myself often wanting to iterate over a List of configuration objects and then produce a List<DigitalOutput>. So I code something like:

properties.getPumps().stream()
	.map(pumpProperties -> pi4j.create(DigitalOutput.newConfigBuilder(context)
		.id(pumpProperties.getId())
		.name(pumpProperties.getName())
		.address(pumpProperties.getPin())
		.shutdown(DigitalState.LOW)
		.initial(DigitalState.LOW)))
	.collect(Collectors.toList());

but this can't compile because Context.create throws Exception. Can we introduce something like a Pi4jException that extends RuntimeException and forgo using checked exceptions?

I know checked exceptions have been a bike shed issue for a long long time in the Java world but with the introduction of lambda syntax, using checked exceptions has for many (may I be so bold to say most?) Java projects become an anti-pattern.

Collaboration - diozero

I've just come across this rewrite of Pi4j having been quite familiar with Pi4j v1. I'm the author of diozero as well as pigpioj and can see a huge overlap between pi4j v2 and diozero/pigpioj. diozero is completely device independent, supports dynamic loading of providers, has its own built-in provider - a goal that I see Pi4j v2 is also trying to achieve. I notice that you are also implementing pigpioj support - my pigpioj library is very stable now and supports local as well as remote interfacing via sockets.
It's seems a shame to duplicate so much effort. I'd be interested in your thoughts on how we could collaborate.

Regards,
Matt Lewis

Support Native Library Docker Builds from Windows

RE: https://github.com/Pi4J/pi4j-v2/blob/master/libraries/pi4j-library-pigpio/pom.xml#L283

<!-- TODO :: Reconfigure the build script to execute the Docker commands directly
             instead of bash script (to provide build support for Windows) -->

Add support to the Maven build script to enable building the native libraries via Docker on a Windows-based operating system.

All that needs to be done is to update the maven/ant build instructions to perform the docker build steps directly in the build instructions rather than calling out to a bash shell script. An example of how this can be done is has already been completed in Pi4J v1.4 at: https://github.com/Pi4J/pi4j/blob/develop/1.4/pi4j-native/build.xml

Pi 4B crashes if trying to attach a listener to all GPIO pins

This piece of code crashes the Pi 4B:

for (int pin = 0; pin < 31; pin++) {
    try {
        int pinNum = pin;
        DigitalInput digitalInput = Bonnet.pi4j
                .create(DigitalInput.newConfigBuilder(Bonnet.pi4j).id("gpio-pin-" + pin).name("Pin #" + pin)
                        .address(pin).pull(PullResistance.PULL_UP).build());
        digitalInput.addListener(new DigitalStateChangeListener() {
            @Override
            public void onDigitalStateChange(DigitalStateChangeEvent event) {
                System.out.println("GPIO pin " + pinNum + " state change");
            }
        });
    } catch (Exception e) {
        System.err.println("Could not set up digital input " + pin + ": " + e);
    }
}

Improve the annotations-implementation

@annotations is an area that needs to be improved in the code. A standards-based approach for dependency injection and handling Pi4J specific annotations needs to be investigated

Annotations are also a feature that could be removed from an initial release and added later.

These two examples show the idea of how the annotations could offer users internals of annotated syntax:

I2CRegister.write ignores length value

As reported by @hackerjimbo

There is an issue with I2CRegister.write (data, offset, length). It seems to ignore the length and fire the whole amount of data in one go.

Starting points for research

Support for camera

Hi!

I want to give a suggestion for this project. Pi4J 2.0 should have access to a camera.

I can help with picture identification/classification in pure Java if you want implement PCA + LDA methods for image classification. It's the same methods being used in OpenCV.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.