Variable, welche Exeption wirft als "Global" deklarieren

aykay90

Mitglied
Hallo Liebe Forenmitglieder
Seit kurzem arbeite ich wieder mit Java und es fehlen mir Lösungsansätze, die funktionieren.
Konkret geht es um folgendes: Es soll mit der Bibliothek pi4j ein Projekt auf dem RaspberryPi realisiert werden, welches teilweise auch schon funktioniert, nur hald noch nicht alles.
Dabei geht es um die Ansteuerung einer Porterweiterung
Java:
final MCP23008GpioProvider DI_8Bit = new MCP23008GpioProvider(I2CBus.BUS_1, 0x20);
Später wird ein Array erstellt, welches die 8 Bit des Controllers abbilden
Java:
    GpioPinDigitalInput DI[] = {
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_00, "DI_0", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_01, "DI_1", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_02, "DI_2", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_03, "DI_3", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_04, "DI_4", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_05, "DI_5", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_06, "DI_6", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_07, "DI_7", PinPullResistance.OFF),
    };

Davor wird noch die "gpio"- Instanz erzeugt:
Java:
static GpioController gpio = GpioFactory.getInstance();

Für mein Programm wäre es schön, wenn ich diess Array in allen Klassen auslesen kann.
Das würde allerdings bedeuten (das ist mein Lösungsansatz), dass die Instanz "DI_8Bit" "Global" deklariert werden müsste, was aber nicht geht, da diese eine "I2CFactory.UnsupportedBusNumberException" werfen kann. Abgesehen davon kennt Java ja keine "globalen" Variablen. Da ich von der Hardwareentwicklung und der Programmierung mit prozeduralen Sprachen (C) komme, fehlt mir das Verständniss für OO Sprachen etwas.

Ich habe nun eine Klasse nur für das IO- Handling erstellt, sodass alle nötigen Informationen zur Ansteuerung des Portexpanders in einer Klasse vorhanden sind und diese ausserhalb nirgends gebraucht werden.
Jedoch funktioniert auch das nicht ganz so wie es sollte, ich bekomme beim Aufruf der Methode "init()" eine "java.lang.NullPointerExeption"

Hätte jemand eine Idee oder einen Ansatz wie ich das Problem lösen kann?
Hier ist der Code um den es konkret geht, anbei habe ich aber noch das ganze Projekt angefügt
Java:
package greenhouse_beta;

import com.pi4j.io.i2c.I2CFactory;
import java.io.IOException;

public class GreenHouse_beta {
  
    public GreenHouse_beta() throws I2CFactory.UnsupportedBusNumberException, IOException{
}// end constructor

   
    /**
     * @param args the command line arguments
     * @throws com.pi4j.io.i2c.I2CFactory.UnsupportedBusNumberException
     * @throws java.io.IOException
     * @throws java.lang.InterruptedException
     */
   

    public static void main(String[] args) throws I2CFactory.UnsupportedBusNumberException, IOException, InterruptedException {
       
        IO start = new IO();

        java.awt.EventQueue.invokeLater(() -> {
            new GUI_JFrame().setVisible(true);
        } // end run
        );

        start.init();

    }// end main
}// end class

Java:
package greenhouse_beta;

import com.pi4j.gpio.extension.mcp.MCP23008GpioProvider;
import com.pi4j.gpio.extension.mcp.MCP23008Pin;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CFactory;
import static greenhouse_beta.GUI_JFrame.jTextPane_DI0;
import static greenhouse_beta.GUI_JFrame.jTextPane_DI1;
import static greenhouse_beta.GUI_JFrame.jTextPane_DI2;
import static greenhouse_beta.GUI_JFrame.jTextPane_DI3;
import static greenhouse_beta.GUI_JFrame.jTextPane_DI4;
import static greenhouse_beta.GUI_JFrame.jTextPane_DI5;
import static greenhouse_beta.GUI_JFrame.jTextPane_DI6;
import static greenhouse_beta.GUI_JFrame.jTextPane_DI7;
import static greenhouse_beta.GUI_JFrame.jTextPane_SW1;
import static greenhouse_beta.GUI_JFrame.jTextPane_SW2;
import java.awt.Color;
import java.io.IOException;


public class IO { 
    public IO() throws I2CFactory.UnsupportedBusNumberException, IOException{
    }// end constuctor
   
    @SuppressWarnings("StaticNonFinalUsedInInitialization")
    static GpioController gpio = GpioFactory.getInstance();
   
    @SuppressWarnings("StaticNonFinalUsedInInitialization")
    static GpioPinDigitalOutput LED_state = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_27, "LED_state", PinState.LOW);
    static GpioPinDigitalOutput LED_sig1 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_05, "LED_sig1", PinState.LOW);
    static GpioPinDigitalOutput LED_sig2 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "LED_sig2", PinState.LOW);
   
    static GpioPinDigitalInput SW1 = gpio.provisionDigitalInputPin(RaspiPin.GPIO_28, "SW1");
    static GpioPinDigitalInput SW2 = gpio.provisionDigitalInputPin(RaspiPin.GPIO_29, "SW2");
   
    final MCP23008GpioProvider DI_8Bit = new MCP23008GpioProvider(I2CBus.BUS_1, 0x20);

    // provision gpio input pins from MCP23008
    GpioPinDigitalInput DI[] = {
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_00, "DI_0", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_01, "DI_1", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_02, "DI_2", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_03, "DI_3", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_04, "DI_4", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_05, "DI_5", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_06, "DI_6", PinPullResistance.OFF),
        gpio.provisionDigitalInputPin(DI_8Bit, MCP23008Pin.GPIO_07, "DI_7", PinPullResistance.OFF),
    };
   
    public void init(){
       
        //DI_0====================================================================================================
        if(gpio.isHigh(DI[0])){
            jTextPane_DI0.setText("HIGH");
            jTextPane_DI0.setBackground(Color.GREEN);
        }// end if

        if(gpio.isLow(DI[0])){
            jTextPane_DI0.setText("LOW");
            jTextPane_DI0.setBackground(null);
        }// end if
        //DI_0/end================================================================================================
       
        //DI_1====================================================================================================
        if(gpio.isHigh(DI[1])){
            jTextPane_DI1.setText("HIGH");
            jTextPane_DI1.setBackground(Color.GREEN);
        }// end if
        if(gpio.isLow(DI[1])){
            jTextPane_DI1.setText("LOW");
            jTextPane_DI1.setBackground(Color.LIGHT_GRAY);
        }// end if
        //DI_1/end================================================================================================

        //DI_2====================================================================================================
        if(gpio.isHigh(DI[2])){
            jTextPane_DI2.setText("HIGH");
            jTextPane_DI2.setBackground(Color.GREEN);
        }// end if
        if(gpio.isLow(DI[2])){
            jTextPane_DI2.setText("LOW");
            jTextPane_DI2.setBackground(Color.LIGHT_GRAY);
        }// end if
        //DI_2/end================================================================================================

        //DI_3====================================================================================================
        if(gpio.isHigh(DI[3])){
            jTextPane_DI3.setText("HIGH");
            jTextPane_DI3.setBackground(Color.GREEN);
        }// end if
        if(gpio.isLow(DI[3])){
            jTextPane_DI3.setText("LOW");
            jTextPane_DI3.setBackground(Color.LIGHT_GRAY);
        }// end if
        //DI_3/end================================================================================================
       
        //DI_4====================================================================================================
        if(gpio.isHigh(DI[4])){
            GUI_JFrame.jTextPane_DI4.setText("HIGH");
            GUI_JFrame.jTextPane_DI4.setBackground(Color.GREEN);
        }// end if
       
        if(gpio.isLow(DI[4])){
            GUI_JFrame.jTextPane_DI4.setText("LOW");
            GUI_JFrame.jTextPane_DI4.setBackground(Color.LIGHT_GRAY);
        }// end if
        //DI_4/end================================================================================================
       
        //DI_5====================================================================================================
        if(gpio.isHigh(DI[5])){
            jTextPane_DI5.setText("HIGH");
            jTextPane_DI5.setBackground(Color.GREEN);
        }// end if
        if(gpio.isLow(DI[5])){
            jTextPane_DI5.setText("LOW");
            jTextPane_DI5.setBackground(Color.LIGHT_GRAY);
        }// end if
        //DI_5/end================================================================================================   

        //DI_6====================================================================================================
        if(gpio.isHigh(DI[6])){
            jTextPane_DI6.setText("HIGH");
            jTextPane_DI6.setBackground(Color.GREEN);
        }// end if
        if(gpio.isLow(DI[6])){
            jTextPane_DI6.setText("LOW");
            jTextPane_DI6.setBackground(Color.LIGHT_GRAY);
        }// end if
        //DI_6/end================================================================================================

        //DI_7====================================================================================================
        if(gpio.isHigh(DI[7])){
            jTextPane_DI7.setText("HIGH");
            jTextPane_DI7.setBackground(Color.GREEN);
        }// end if
        if(gpio.isLow(DI[7])){
            jTextPane_DI7.setText("LOW");
            jTextPane_DI7.setBackground(Color.LIGHT_GRAY);
        }// end if
        //DI_7/end================================================================================================   
       
    }// end init
 

Anhänge

Hallo Klaus,

danke für die Antwort. Ups, das wusste ich nicht. Trifft dann wohl eher meine eigene Einstellung zu mir 😀
Mein Output sieht so aus:

Exception in thread "main" java.lang.NullPointerException
at greenhouse_beta.IO.init(IO.java:78)
at greenhouse_beta.GreenHouse_beta.main(GreenHouse_beta.java:43)

Danke und Gruss,
Andi
 
Wenn ich das richtig interpretiere, dann ist das Zeile 78 in der Methode init() und der Aufruf dieser Methode in der main- Methode "start.init();"

show.php
 
EDIT: Bei diesem Aufruf soll nun in der Klasse "GUI_JFrame" den Text eine jTextPane geändert werden. Entsteht der Fehler nun dadurch, dass von der Methode init() nicht in der Klasse GUI_JFrame etwas geändert werden kann?
 
okay, dann vertehe ich aber etwas nicht. Ich habe in der gleichen Klasse (IO) eine weitere Methode "input()", welche folgendermassen aussieht:
Java:
public void input(){
       
        // create and register gpio pin listener for DI_8Bit GpioPinDigitalStateChangeEvent
        gpio.addListener((GpioPinListenerDigital) (GpioPinDigitalStateChangeEvent event) -> {
            // display pin state on console
            System.out.println(" --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
           
            //DI_0====================================================================================================
            if((event.getPin() == DI[0]) & (event.getState() == PinState.HIGH)){
                jTextPane_DI0.setText("HIGH");
                jTextPane_DI0.setBackground(Color.GREEN);
            }// end if
            if((event.getPin() == DI[0]) & (event.getState() == PinState.LOW)){
                jTextPane_DI0.setText("LOW");
                jTextPane_DI0.setBackground(null);
            }// end if
            //DI_0/end================================================================================================                
      
            //DI_1====================================================================================================
            if((event.getPin() == DI[1]) & (event.getState() == PinState.HIGH)){
                jTextPane_DI1.setText("HIGH");
                jTextPane_DI1.setBackground(Color.GREEN);
            }// end if
            if((event.getPin() == DI[1]) & (event.getState() == PinState.LOW)){
                jTextPane_DI1.setText("LOW");
                jTextPane_DI1.setBackground(null);
            }// end if
            //DI_1/end================================================================================================                        
           
            //DI_2====================================================================================================
            if((event.getPin() == DI[2]) & (event.getState() == PinState.HIGH)){
                jTextPane_DI2.setText("HIGH");
                jTextPane_DI2.setBackground(Color.GREEN);
            }// end if
            if((event.getPin() == DI[2]) & (event.getState() == PinState.LOW)){
                jTextPane_DI2.setText("LOW");
                jTextPane_DI2.setBackground(null);
            }// end if
            //DI_2/end================================================================================================        
                      
            //DI_3====================================================================================================
            if((event.getPin() == DI[3]) & (event.getState() == PinState.HIGH)){
                jTextPane_DI3.setText("HIGH");
                jTextPane_DI3.setBackground(Color.GREEN);
            }// end if
            if((event.getPin() == DI[3]) & (event.getState() == PinState.LOW)){
                jTextPane_DI3.setText("LOW");
                jTextPane_DI3.setBackground(null);
            }// end if
            //DI_3/end================================================================================================        
           
            //DI_4====================================================================================================
            if((event.getPin() == DI[4]) & (event.getState() == PinState.HIGH)){
                jTextPane_DI4.setText("HIGH");
                jTextPane_DI4.setBackground(Color.GREEN);
            }// end if
            if((event.getPin() == DI[4]) & (event.getState() == PinState.LOW)){
                jTextPane_DI4.setText("LOW");
                jTextPane_DI4.setBackground(null);
            }// end if
            //DI_4/end================================================================================================

            //DI_5====================================================================================================
            if((event.getPin() == DI[5]) & (event.getState() == PinState.HIGH)){
                jTextPane_DI5.setText("HIGH");
                jTextPane_DI5.setBackground(Color.GREEN);
            }// end if
            if((event.getPin() == DI[5]) & (event.getState() == PinState.LOW)){
                jTextPane_DI5.setText("LOW");
                jTextPane_DI5.setBackground(null);
            }// end if
            //DI_5/end================================================================================================           

            //DI_6====================================================================================================
            if((event.getPin() == DI[6]) & (event.getState() == PinState.HIGH)){
                jTextPane_DI6.setText("HIGH");
                jTextPane_DI6.setBackground(Color.GREEN);
            }// end if
            if((event.getPin() == DI[6]) & (event.getState() == PinState.LOW)){
                jTextPane_DI6.setText("LOW");
                jTextPane_DI6.setBackground(null);
            }// end if
            //DI_6/end================================================================================================           

            //DI_7====================================================================================================
            if((event.getPin() == DI[7]) & (event.getState() == PinState.HIGH)){
                jTextPane_DI7.setText("HIGH");
                jTextPane_DI7.setBackground(Color.GREEN);
            }// end if
            if((event.getPin() == DI[7]) & (event.getState() == PinState.LOW)){
                jTextPane_DI7.setText("LOW");
                jTextPane_DI7.setBackground(null);
            }// end if
            //DI_7/end================================================================================================
           
        }, DI);
       
        // create and register gpio pin listener for SW1
        gpio.addListener((GpioPinListenerDigital) (GpioPinDigitalStateChangeEvent event) -> {
            // display pin state on console
            System.out.println("SW1 " + event.getPin() + " = " + event.getState());

            if(event.getState() == PinState.LOW){
            jTextPane_SW1.setText("Pressed");
            }// end if
            else{
            jTextPane_SW1.setText("Released");
            }// end if

        }, SW1);
       
        // create and register gpio pin listener for SW2
        gpio.addListener((GpioPinListenerDigital) (GpioPinDigitalStateChangeEvent event) -> {
            // display pin state on console
            System.out.println("SW2 " + event.getPin() + " = " + event.getState());

            if(event.getState() == PinState.LOW){
            jTextPane_SW2.setText("Pressed");
            }// end if
            else{
            jTextPane_SW2.setText("Released");
            }// end if

        }, SW2);
       
    }// end Input

Wenn ich nun einen Taster betätige (siehe Bild), dann wird mir das auch problemlos im GUI angezeigt, die Texänderung sowie auch den Farbwechsel. Ich verstehe nicht, wieso es bei einem event geht, aber bei einem Aufruf der Methode nicht.
 
Ok, meine Vermutung ist folgendes:

Da die invokeLater() Methode asynchron ausgeführt wird, kommt es dazu, dass in der init() Methode der IO Klasse bereits auf TextPanes zugegriffen wird, die aber noch nicht initialisiert wurden. Wie Thallius schon sagte.
Versuch mal statt invokeLater() invokeAndWait() zu benutzen.
 
Okay, das funktioniert soweit mal, danke euch! aber ein anderes Problem ist nun aufgetaucht. Das GUI reagiert nicht immer auf die Änderungen an den beiden Eingängen (DI4 und DI5). Das Gui reagiert teilweise verspätet oder gar nicht. Zum Teil bleibt ein Zustand auch hängen und erst beim Betätigen des anderen Einganges setzt er sich wieder zurück.
Da dies sporadisch auftritt weiss ich nicht so ich anfangen suchen soll. Es wird auch keine Exception geworfen.
 
Da es sich hier um GUI Veränderungen handelt könnte ein repaint() helfen. Also:
Code:
textPane.setText("ein text");
textPane.setBackground(Color.GREEN);
textPane.repaint();
 
Leider hilft auch das nicht. Es scheint so, als würde der event nicht registriert. Zu Beginn der Methode "input()" wird ja noch etwas auf die Komandozeile geschrieben:
Java:
System.out.println(" --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());

Da dieser Text schon nicht erscheint, gehe ich davon aus, dass dieser event gar nicht abgefangen wird. Was allerdings gut funktioniert ist, wenn der Text auf der Kommandozeile ausgegeben wird, sich auch das GUI ändert. Somit würde ich behaupten, dass es nicht an der Darstellung ligt.
 
Du hast Recht. Wenn dein System.out nicht auftaucht, sieht es wohl so aus als wenn kein Event dem Listener übergeben wird. Woran das nun liegt kann ich nicht sagen, da ich mit dem Raspi und der Library noch nichts zu tun hatte.
 
Heureka! Das sporadische erfassen des events hat an mangelndem Speicherplatz auf der SD- Karte des RasPi's gelegen.
Nach dem Löschen von unbenutzten Daten funktioniert der Code nun einwandfrei!

Danke euch für die Hilfe.

Gruss,
Andi
 

Zurück
Oben