Я пытаюсь контролировать вывод GPIO в моей программе, чтобы включить простое реле, все из кода работают отдельно от одной проблемы; пиковый код GPIO для отправки сигнала высокий не работает и не вызывает никаких ошибок. Я использую библиотеки pi4j для управления контактами на плате RaspberryPi.GPIO не идет высоко и код игнорируется при запуске PI4J
Вот мой код:
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 высокий, и я не вижу никаких результатов его просто ommits код, как он не был там.
Любая помощь была бы большой!
Вы уверены, что используете правильные резисторы? Если нет, возможно, что сигнал проходит, но он недостаточно силен, чтобы его можно было обнаружить с другой стороны. – blearn