Using java to control LED lights on Ubuntu

Table of contents

 

1. Environment introduction

2. Equipment introduction

3. Preliminary preparation

3.1. Install jdk for Ubuntu

4. Write java code

        4.1. Get the gpio pin number and path

        4.2. Write java code

        5. Run on Ubuntu system

        6. Use the terminal to directly control the LED on Ubuntu, the operation is as follows:


1. Environment introduction

  • JAVA

Intellij IDEA 2022.3.3 (Ultimate Edition)

jdk-1.8.0_77

  • Ubuntu

Linux version 5.10.110 (root@seven-HP-ZHAN-99-Pro-G1-MT) (aarch64-none-linux-gnu-gcc (GNU Toolchain for the A-profile Architecture 10.3-2021.07 (arm-10.29)) 10.3.1 20210621, GNU ld (GNU Toolchain for the A-profile Architecture 10.3-2021.07 (arm-10.29)) 2.36.1.20210621) #11 SMP Fri Feb 10 18:15:24 CST 2023

openjdk version "11.0.18" 2023-01-17
OpenJDK Runtime Environment (build 11.0.18+10-post-Ubuntu-0ubuntu120.04.1)
OpenJDK 64-Bit Server VM (build 11.0.18+10-post-Ubuntu-0ubuntu120.04.1, mixed mode)

2. Equipment introduction

3. Preliminary preparation

3.1. Install jdk for Ubuntu

The code is as follows (terminal):

armt@localhost:~$ apt-cache search java11

openjdk-11-jdk - OpenJDK Development Kit (JDK)
openjdk-11-jdk-headless - OpenJDK Development Kit (JDK) (headless)
openjdk-11-jre - OpenJDK Java runtime, using Hotspot JIT
openjdk-11-jre-headless - OpenJDK Java runtime, using Hotspot JIT (headless)
default-jdk - Standard Java or Java compatible Development Kit
default-jdk-headless - Standard Java or Java compatible Development Kit (headless)

3.2 Select the jdk version to be installed, and then enter y to install 

armt@localhost:~$ sudo apt-get install openjdk-11-jdk

Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  openjdk-11-jdk-headless openjdk-11-jre openjdk-11-jre-headless
Suggested packages:
  openjdk-11-demo openjdk-11-source visualvm fonts-ipafont-gothic
  fonts-ipafont-mincho fonts-wqy-microhei | fonts-wqy-zenhei
The following NEW packages will be installed:
  openjdk-11-jdk openjdk-11-jdk-headless openjdk-11-jre
  openjdk-11-jre-headless
0 upgraded, 4 newly installed, 0 to remove and 4 not upgraded.
Need to get 281 MB of archives.
After this operation, 435 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

3.3 After the installation is complete, check whether the jdk is installed successfully, and print the following results to indicate that the installation is successful

armt@localhost:~$ java -version

openjdk version "11.0.18" 2023-01-17
OpenJDK Runtime Environment (build 11.0.18+10-post-Ubuntu-0ubuntu120.04.1)
OpenJDK 64-Bit Server VM (build 11.0.18+10-post-Ubuntu-0ubuntu120.04.1, mixed mode)

3.4 The following error occurs when installing JDK, execute  sudo apt update 

4. Write java code

        In this case, GPIO is used to control the light on and off. Simply put, it is an interface that changes the device by changing the state value.

        4.1. Get the gpio pin number and path

 In the figure, GPIO4_C6 ​​belongs to GPIO4 and belongs to the fourth group of pins. Group 1 has 32 pins. Group C of C6 is 0 if it is group A, group B is 8, group C is 16, and group D is 24 , and recursively calculate the pin number of GPIO4_C6 ​​as 4*32+16+6 =150

        LED_W means white light, pin number 150
        LED_G means green light, pin number 149
        LED_R means red light, pin number 122

        Path of RK chip: /sys/class/gpio/

Add other GPIO port numbers:

        GPIO_1_A4 corresponding pin number: 36
        GPIO_2_B0 corresponding pin number: 40
        GPIO_3_B1 corresponding pin number: 41
        GPIO_4_B2 corresponding pin number: 42

        4.2. Write java code

    private static final String GPIO_PATH = "/sys/class/gpio/";//路径

    
    private static final String GPIO_PIN_W = "150"; // 白灯引脚编号
    private static final String GPIO_PIN_G = "149"; // 绿灯引脚编号
    private static final String GPIO_PIN_R = "122"; // 红灯引脚编号

    //如果想控制其他IO口 记得替换引脚编号
    //private static final String GPIO1_A4 = "36";
    //private static final String GPIO1_B0 = "40"; 
    //private static final String GPIO1_B1 = "41";
    //private static final String GPIO1_B2 = "42";

        Operation steps:
                1. Export GPIO pins

    /**
     * 导出GPIO引脚
     */
    private static void exportPin(String pin) {
        writeFile(GPIO_PATH + "export", pin);
    }

                2. Set the GPIO pin to output mode

 /**
     * 设置GPIO引脚为输出模式
     */
    private static void setPinDirection(String pin, String direction) {
        writeFile(GPIO_PATH + "gpio" + pin + "/direction", direction);
    }

                3. Control LED lights on/off

/**
     * 控制LED灯
     */
    private static void setPinValue(String pin, String value) {
        writeFile(GPIO_PATH + "gpio" + pin + "/value", value);
    }

                4. Clean up the GPIO pins

 /**
     * 清理GPIO引脚
     */
    private static void unexportPin(String pin) {
        writeFile(GPIO_PATH + "unexport", pin);
    }
    private static void writeFile(String path, String value) {
        try (FileWriter fileWriter = new FileWriter(path)) {
            fileWriter.write(value);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

                Turn on the LED lights

  /**
     * 打开灯
     * @param pin 引脚编号
     */
    private static void openLED(String pin){
        //打开前关闭所有led,避免多个灯同时点亮烧坏电路板
        closeLED(GPIO_PIN_W);
        closeLED(GPIO_PIN_G);
        closeLED(GPIO_PIN_R);

        // 导出GPIO引脚
        exportPin(pin);

        // 设置GPIO引脚为输出模式
        setPinDirection(pin, "out");

        // 控制LED灯
        setPinValue(pin, "1"); // 打开LED灯
    }

                Turn off the LED light

 /**
     * 关闭灯
     * @param pin 引脚编号
     */
    private static void closeLED(String pin){
        // 控制LED灯
        setPinValue(pin, "0"); // 关闭LED灯

        // 清理GPIO引脚
        unexportPin(pin);
    }

       Full code:

package org.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
    private static final String GPIO_PATH = "/sys/class/gpio/";

    private static final String GPIO_PIN_W = "150"; // 白灯引脚编号
    private static final String GPIO_PIN_G = "149"; // 绿灯引脚编号
    private static final String GPIO_PIN_R = "122"; // 红灯引脚编号

    public static void main(String[] args) {

        createAndShowGUI();
    }

    /**
     * 打开灯
     * @param pin 引脚编号
     */
    private static void openLED(String pin){
        //打开前关闭所有led,避免多个灯同时点亮烧坏电路板
        closeLED(GPIO_PIN_W);
        closeLED(GPIO_PIN_G);
        closeLED(GPIO_PIN_R);

        // 导出GPIO引脚
        exportPin(pin);

        // 设置GPIO引脚为输出模式
        setPinDirection(pin, "out");

        // 控制LED灯
        setPinValue(pin, "1"); // 打开LED灯
    }

    /**
     * 关闭灯
     * @param pin 引脚编号
     */
    private static void closeLED(String pin){
        // 控制LED灯
        setPinValue(pin, "0"); // 关闭LED灯

        // 清理GPIO引脚
        unexportPin(pin);
    }


    /**
     * 导出GPIO引脚
     */
    private static void exportPin(String pin) {
        writeFile(GPIO_PATH + "export", pin);
    }

    /**
     * 清理GPIO引脚
     */
    private static void unexportPin(String pin) {
        writeFile(GPIO_PATH + "unexport", pin);
    }

    /**
     * 设置GPIO引脚为输出模式
     */
    private static void setPinDirection(String pin, String direction) {
        writeFile(GPIO_PATH + "gpio" + pin + "/direction", direction);
    }

    /**
     * 控制LED灯
     */
    private static void setPinValue(String pin, String value) {
        writeFile(GPIO_PATH + "gpio" + pin + "/value", value);
    }


    private static void writeFile(String path, String value) {
        try (FileWriter fileWriter = new FileWriter(path)) {
            fileWriter.write(value);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建UI
     */
    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("GPIO控制LED开关");
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                //窗口关闭时关闭LED
                closeLED(GPIO_PIN_W);
                closeLED(GPIO_PIN_G);
                closeLED(GPIO_PIN_R);
            }
        });

        //设置弹窗大小
        frame.setLocation(200, 200);

        JPanel panel = new JPanel();
        panel.setPreferredSize(new Dimension(600, 400));
        panel.setLayout(null);

        // 添加面板
        JButton wBtn = new JButton("打开-白灯");
        wBtn.addActionListener(e -> openLED(GPIO_PIN_W));
        wBtn.setBounds(60, 25, 130, 30);

        JButton gBtn = new JButton("打开-绿灯");
        gBtn.addActionListener(e -> openLED(GPIO_PIN_G));
        gBtn.setBounds(220, 25, 130, 30);

        JButton rBtn = new JButton("打开-红灯");
        rBtn.addActionListener(e -> openLED(GPIO_PIN_R));
        rBtn.setBounds(380, 25, 130, 30);
        // 关闭按钮
        JButton wBtnC = new JButton("关闭-白灯");
        wBtnC.addActionListener(e -> closeLED(GPIO_PIN_W));
        wBtnC.setBounds(60, 75, 130, 30);

        JButton gBtnC = new JButton("关闭-绿灯");
        gBtnC.addActionListener(e -> closeLED(GPIO_PIN_G));
        gBtnC.setBounds(220, 75, 130, 30);

        JButton rBtnC = new JButton("关闭-红灯");
        rBtnC.addActionListener(e -> closeLED(GPIO_PIN_R));
        rBtnC.setBounds(380, 75, 130, 30);


        panel.add(wBtn);
        panel.add(gBtn);
        panel.add(rBtn);
        panel.add(wBtnC);
        panel.add(gBtnC);
        panel.add(rBtnC);


        frame.add(panel);

        // 显示窗口
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

        5. Run on Ubuntu system

                Export the java program to the jar package (testGPIO.jar, the name is random), put it in any location, open the terminal and enter:

        java -jar testGPIO.jar

                 The software operation diagram is as follows:

        6. Use the terminal to directly control the LED on Ubuntu, the operation is as follows:

Guess you like

Origin blog.csdn.net/qaz96801/article/details/130869452