树莓派+java(pi4j)USB 串口通讯 485

Spoony 21.45m2020-10-1261 次点击
树莓派和串口转485的数据线。

执行命令
```
//可出现所有的串口
lsusb
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 0403:6001 Future Technology Devices International, Ltd FT232 Serial (UART) IC
Bus 001 Device 003: ID 1a2c:2c27 China Resource Semico Co., Ltd
Bus 001 Device 002: ID 2109:3431 VIA Labs, Inc. Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
//看到了识别成了ttyUSB0
ls -l /dev/tty*
crw--w---- 1 root tty 4, 9 Jan 3 09:17 /dev/tty9
crw-rw---- 1 root dialout 204, 64 Jan 6 01:40 /dev/ttyAMA0
crw------- 1 root root 5, 3 Jan 3 09:17 /dev/ttyprintk
crw--w---- 1 root tty 4, 64 Jan 6 01:40 /dev/ttyS0
crw-rw---- 1 root dialout 188, 0 Jan 6 02:59 /dev/ttyUSB0
//查看串口的波特率
stty -F /dev/ttyUSB0
speed 9600 baud; line = 0;
min = 0; time = 100;
-brkint -icrnl -imaxbel
-opost
-isig -icanon -iexten -echo -echoe
//查看串口的连接信息
dmesg | grep ttyUSB0
[ 6.621718] usb 1-1.4: FTDI USB Serial Device converter now attached to ttyUSB0

#保证 python 和pyserial 安装了。 树莓派4B
// 安装 pyserial
cd /tmp
wget https://project-downloads.drogon.net/wiringpi-latest.deb
sudo dpkg -i wiringpi-latest.deb
// 校验
gpio -v


pip list
//命令python查看安装到系统上的串口
python -m serial.tools.list_ports
// pyhon 调试
python
import serial
ser=serial.Serial('/dev/ttyUSB0',9600) #/dev/ttyUSB0 根据实际修改 波特率 根据传感器修改
ser.write('12345'.encode())

```

Java 程序

```
//确定 串口号/dev/ttyUSB0

package com.weepal.utils;// START SNIPPET: serial-snippet


import com.pi4j.io.serial.*;
import com.pi4j.util.CommandArgumentParser;
import com.pi4j.util.Console;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;
public class SerialExample {‌
static final Logger log = LoggerFactory.getLogger(SerialExample.class); //日志
final static Serial serial = SerialFactory.createInstance();

/**
* This example program supports the following optional command arguments/options:
* "--device (device-path)" [DEFAULT: /dev/ttyAMA0]
* "--baud (baud-rate)" [DEFAULT: 38400]
* "--data-bits (5|6|7|8)" [DEFAULT: 8]
* "--parity (none|odd|even)" [DEFAULT: none]
* "--stop-bits (1|2)" [DEFAULT: 1]
* "--flow-control (none|hardware|software)" [DEFAULT: none]
*
* @param args
* @throws InterruptedException
* @throws IOException
*/
public static void main(String args[]) throws InterruptedException, IOException {‌
try {‌

SerialConfig config = new SerialConfig();
config.device("/dev/ttyUSB0")
.baud(Baud._9600)
.dataBits(DataBits._8)
.parity(Parity.NONE)
.stopBits(StopBits._1)
.flowControl(FlowControl.NONE);

if(args.length > 0){‌
config = CommandArgumentParser.getSerialConfig(config, args);
}


serial.open(config);


serial.addListener(new SerialDataEventListener() {‌
@Override
public void dataReceived(SerialDataEvent event) {‌


try {‌
System.out.println("[HEX DATA] " + event.getHexByteString());
System.out.println("[ASCII DATA] " + event.getAsciiString());

} catch (IOException e) {‌
e.printStackTrace();
}
}
});

// continuous loop to keep the program running until the user terminates the program
while(true) {‌
try {‌
String order = "010300000001";
byte[] sbuf = CRC16MUtils.getSendBuf(order);
String requestStr = CRC16MUtils.getBufHexStr(sbuf);
serial.write(HexUtils.hexStringTobyte(requestStr));
System.out.println("write 010300000001" );
}
catch(IllegalStateException ex){‌
ex.printStackTrace();
}

Thread.sleep(1000 * 60 *5);
}

}
catch(IOException ex) {‌
System.out.println(" ==>> SERIAL SETUP FAILED : " + ex.getMessage());
return;
}
}


}
```
输出结果
```
write 010300000001
[HEX DATA] 01,03,02,00,27,F8,5E
```

/dev/ttyS0: Permission denied 提示的处理
```
//1方法一 永久有效
//树莓派4B
vim /boot/cmdline.txt
// 注释 console-serial,115200
sudo vi /boot/cmdline.txt
// 添加 enable_uart=1
sudo vi /boot/config.tx
// 开启 uart接口 关闭shell访问,打开硬件串口
sudo raspi-config
//选择Interfacing Options -> Serial -> Yes
// 重启
sudo reboot

//权限问题
groups ${‌USER}
sudo gpasswd --add ${‌USER} dialout

//2方法二 临时有效
chmod 660 /dev/ttyS0
```

转自 https://www.jianshu.com/p/211ff6fccdd8
收藏 ♥ 感谢
yfhaotian 10cm 2020-10-15 
pi4j只能基于32位系统吗?

登录注册 后可回复。