繁体   English   中英

运行PI4J时GPIO不会变高并且代码将被忽略

[英]GPIO not going high and code being ignored when running PI4J

我试图控制程序中的GPIO引脚以打开一个简单的继电器,除了一个问题,所有代码都可以工作。 用于发送高电平信号的GPIO引脚代码不起作用,也不会引起任何错误,我正在使用pi4j库来控制RaspberryPi板上的引脚。

这是我的代码:

import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;


import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.sql.Timestamp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Calendar;


public class FileWatch {

    static String clkID;
    static String clkID2;
    static String ts;
    static String ts1;
    static boolean done = false;
    static boolean REdone = false;
    static boolean finished = false;
    static boolean ready;

    static String host ="jdbc:mysql://localhost/dancers";
    static String username ="root";
    static String password ="beaker19";


    public static void main(String[] args) throws IOException,
            InterruptedException {

       // create gpio controller
        final GpioController gpio = GpioFactory.getInstance();

        // provision gpio pin #01 as an output pin and turn on
        final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "MyLED", PinState.LOW);


        while (true) {
            done = false;
            REdone=false;
            checkFile();
            System.out.println("worked");
            pin.high();
            Thread.sleep(3000);
            REcheckFile();
            Thread.sleep(500);
            //Thread.
            if (clkID.equals(clkID2)) {

            uploadTimes();

            }

            else {
                System.out.println("Wrong matching ID's");
            }
            Thread.sleep(1000);
            pin.low();
         }
    }   

    // Thread th = new Thread(new FileWatch());
    // th.start();
    // checkFile();
    // REcheckFile();
    // if (clkID2.equals(clkID2)){
    // System.out.println("worked");
    // }
    // else {
    // System.out.println("not worked");
    // }
    //
    public static void check() throws InterruptedException{

        checkFile();
        Thread.sleep(3000);
        REcheckFile();
        Thread.sleep(500);

    }


    public String getClkId() {

        return clkID;

    }

    public static void connection() {

//      while(!finished){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("worked");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//      }
    }


    public static void checkFile() {
        while (!done) {
            try {
                WatchService watcher = FileSystems.getDefault()
                        .newWatchService();
                Path dir = Paths.get("/home/pi/rpi2ardu");
                dir.register(watcher, ENTRY_MODIFY);

                System.out.println("Watch Service registered for dir: "
                        + dir.getFileName());

                WatchKey key;
                try {
                    key = watcher.take();
                } catch (InterruptedException ex) {
                    return;
                }

                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();

                    @SuppressWarnings("unchecked")
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path fileName = ev.context();

                    System.out.println(kind.name() + ": " + fileName);

                    if (kind == ENTRY_MODIFY
                            && fileName.toString().equals("example.txt")) {
                        System.out.println("My source file has changed!!!");
                        String sCurrentLine = null;
                        try (BufferedReader br = new BufferedReader(
                                new FileReader("/home/pi/rpi2ardu/example.txt"))) {
                            while ((sCurrentLine = br.readLine()) != null) {
                                System.out.println(sCurrentLine);
                                clkID = sCurrentLine;
                                System.out.println(clkID);
                                java.util.Date date = new java.util.Date();
                                date = new Timestamp(date.getTime());
                                // System.out.println(new
                                // Timestamp(date.getTime()));
                                ts = date.toString();
                                System.out.println(ts);
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        File inputFile = new File("/home/pi/rpi2ardu/example.txt"); // Your
                                                                            // file
                        File tempFile = new File("/home/pi/rpi2ardu/temp.txt");// temp
                                                                                // file
                        BufferedReader reader = new BufferedReader(
                                new FileReader(inputFile));
                        BufferedWriter writer = new BufferedWriter(
                                new FileWriter(tempFile));
                        String currentLine;
                        while ((currentLine = reader.readLine()) != null) {
                            currentLine = ("");
                            writer.write(currentLine);
                        }
                        writer.close();
                        reader.close();
                        done = true;
                        boolean successful = tempFile.renameTo(inputFile);
                        System.out.println(successful);
                    }
                }

                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }

            catch (IOException ex) {
                System.err.println(ex);
            }

        }
    }

    public static void REcheckFile() {
        while (!REdone) {
            try {
                WatchService watcher = FileSystems.getDefault()
                        .newWatchService();
                Path dir = Paths.get("/home/pi/rpi2ardu");
                dir.register(watcher, ENTRY_MODIFY);

                System.out.println("Watch Service registered for dir: "
                        + dir.getFileName());

                WatchKey key;
                try {
                    key = watcher.take();
                } catch (InterruptedException ex) {
                    return;
                }

                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();

                    @SuppressWarnings("unchecked")
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path fileName = ev.context();

                    System.out.println(kind.name() + ": " + fileName);

                    if (kind == ENTRY_MODIFY
                            && fileName.toString().equals("example.txt")) {
                        System.out.println("My source file has changed!!!");
                        String sCurrentLine = null;
                        try (BufferedReader br = new BufferedReader(
                                new FileReader("/home/pi/rpi2ardu/example.txt"))) {
                            while ((sCurrentLine = br.readLine()) != null) {
                                System.out.println(sCurrentLine);
                                clkID2 = sCurrentLine;
                                System.out.println(clkID2);
                                java.util.Date date1 = new java.util.Date();
                                date1 = new Timestamp(date1.getTime());
                                // System.out.println(new
                                // Timestamp(date.getTime()));
                                String ts1 = date1.toString();
                                System.out.println(ts1);
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        File inputFile = new File("/home/pi/rpi2ardu/example.txt"); // Your
                                                                            // file
                        File tempFile = new File("/home/pi/rpi2ardu/temp.txt");// temp
                                                                                // file
                        BufferedReader reader = new BufferedReader(
                                new FileReader(inputFile));
                        BufferedWriter writer = new BufferedWriter(
                                new FileWriter(tempFile));
                        String currentLine;
                        while ((currentLine = reader.readLine()) != null) {
                            currentLine = ("");
                            writer.write(currentLine);
                        }
                        writer.close();
                        reader.close();
                        REdone = true;
                        boolean successful = tempFile.renameTo(inputFile);
                        System.out.println(successful);
                    }
                }

                boolean valid = key.reset();
                if (!valid) {
                    break;
                }
            }

            catch (IOException ex) {
                System.err.println(ex);
            }

        }
    }

    public static void uploadTimes(){
          try
            {
              String host ="jdbc:mysql://localhost/dancers";
                String username ="root";
                String password ="beaker19";
                connection();
               Connection conn = DriverManager.getConnection(host, username, password);
                System.out.println("Connected:");

                String t1= ts;
                String t2 =ts1;
                String id =clkID;

                // the mysql insert statement
                String query = " insert into test (id, ts, ts1)"
                  + " values (?, ?, ?)";     
              // create the mysql insert preparedstatement
              java.sql.PreparedStatement preparedStmt = conn.prepareStatement(query);
              preparedStmt.setString (1, id);
              preparedStmt.setString (2, t1);
              preparedStmt.setString (3, t2);

              // execute the preparedstatement
              preparedStmt.execute();
              System.out.println("worked"); 
              conn.close();
            }
            catch (Exception e)
            {
              System.err.println("Got an exception!");
              System.err.println(e.getMessage());
            }

    }


}

我不确定为什么它不发送gpio信号高,我没有看到任何结果,只是忽略了那里没有的代码。

任何帮助将非常感谢!

两件事情:

  1. 确保使用正确的GPIO引脚号。 Pi4J的管脚编号不同于python中常用的两种编号方法。 看一下此链接: http : //pi4j.com/pins/model-2b-rev1.html

  2. 继电器通常需要高电流才能开关。 GPIO引脚提供的电流不足以触发大多数继电器。 在该GPIO引脚上连接一个LED和电阻,以测试问题是否是该引脚未变高,或者是继电器需要的电流大于该引脚可提供的电流。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM