首页 > 基础资料 博客日记
FileInputStream类写入数据到串口
2023-05-10 22:54:21基础资料围观811次
Java中的FileInputStream类是用于从文件中读取数据的类,而不是用于向串口写入数据的类。如果您需要向串口写入数据,可以使用Java中的SerialPort类。
以下是使用SerialPort类向串口写入数据的示例代码:
import java.io.OutputStream; import java.util.Scanner; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; public class SerialWriter { private OutputStream outputStream; public SerialWriter(String portName) throws Exception { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); if (portIdentifier.isCurrentlyOwned()) { System.out.println("Error: Port is currently in use"); } else { SerialPort serialPort = (SerialPort) portIdentifier.open(this.getClass().getName(), 1000); serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); outputStream = serialPort.getOutputStream(); } } public void write(String data) throws Exception { outputStream.write(data.getBytes()); } public static void main(String[] args) { try { SerialWriter serialWriter = new SerialWriter("/dev/ttyUSB0"); Scanner scanner = new Scanner(System.in); while(true) { System.out.print("Enter data to send: "); String data = scanner.nextLine(); serialWriter.write(data); } } catch (Exception e) { e.printStackTrace(); } } }
该示例代码会不断等待用户输入要发送的数据并通过串口将其发送出去。其中"/dev/ttyUSB0"为串口设备名,可以根据实际情况更改。
标签:
相关文章
最新发布
- springboot~3.x项目中使用集成测试
- Java测试类、工具类与JavaBean对比解析
- SpringBoot-日志
- springboot~http2的支持
- 解疑释惑 - 日志体系之 slf4j + logback 组合(一)
- Web server failed to start. Port 8080 was already in use. 端口被占用
- Springboot 项目配置多数据源
- 伙伴匹配系统(移动端 H5 网站(APP 风格)基于Spring Boot 后端 + Vue3 - 05
- 剑指offer-23、搜索⼆叉树的后序遍历序列
- 一个表示金额的数字是 100000000L,这是多少米?