java如何发送指令到单片机_用java编的上位机中,如何向下位机发送命令?

本文介绍如何利用Java Communications API在Windows平台上通过Java程序向单片机发送指令。示例代码展示了如何打开串口,设置波特率,并发送预定义的字符串消息。
摘要由CSDN通过智能技术生成

你可以用 Java Communications API 里面有例子。

windows 平台 Java Communications API  2.0还可以工作,其它不支持

其它平台 都有相应的版本,可以从sun下载

下面是写的例子,jdk里面的

import java.io.*;

import java.util.*;

import javax.comm.*;

public class SimpleWrite {

static Enumeration portList;

static CommPortIdentifier portId;

static String messageString = "Hello, world!\n";

static SerialPort serialPort;

static OutputStream outputStream;

public static void main(String[] args) {

portList = CommPortIdentifier.getPortIdentifiers();

while (portList.hasMoreElements()) {

portId = (CommPortIdentifier) portList.nextElement();

if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

// if (portId.getName().equals("COM1")) {

if (portId.getName().equals("/dev/term/a")) {

try {

serialPort = (SerialPort)

portId.open("SimpleWriteApp", 2000);

} catch (PortInUseException e) {}

try {

outputStream = serialPort.getOutputStream();

} catch (IOException e) {}

try {

serialPort.setSerialPortParams(9600,

SerialPort.DATABITS_8,

SerialPort.STOPBITS_1,

SerialPort.PARITY_NONE);

} catch (UnsupportedCommOperationException e) {}

try {

outputStream.write(messageString.getBytes());

} catch (IOException e) {}

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值