本文介绍了如何将以下java代码转换为C#dotnet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
System.out.println("Trying to open port...");
CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(comPort);
port = (SerialPort)portId.open("SMS Transceiver", 10);
port.setSerialPortParams(boardRates, dataBits, stopBits, 0);
out = new OutputStreamWriter(port.getOutputStream(), "ISO-8859-1");
in = new InputStreamReader(port.getInputStream(), "ISO-8859-1");
System.out.println("Port is opened successfully..... \n");
Thread.sleep(10000L);
我尝试过:
What I have tried:
Console.WriteLine("Trying to open port...");
Console.WriteLine(comPort);
port = new System.IO.Ports.SerialPort(comPort);
port.Open();
SerialPort Serial1 = new System.IO.Ports.SerialPort(comPort, boardRates, Parity.None, dataBits);
port.Encoding = Encoding.GetEncoding("iso-8859-1");
Console.WriteLine("Port is opened successfully..... \n");
Thread.Sleep(10000);
推荐答案
string portName = "COM1";
int baudRate = 9600;
Parity parity = Parity.None;
int dataBits = 8;
2.创建类SerialPort的实例
2. Create an instance of the class SerialPort
SerialPort serial = new SerialPort(portName, baudRate, parity, dataBits);
serial.Encoding = Encoding.GetEncoding("iso-8859-1");
3.打开端口
3. Open the port
serial.Open();
4.写入数据
4. Write data
serial.WriteLine("Hello World");
or
serial.Write(new byte[] {0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64});
5.读取数据
5. Read data
string retVal = serial.ReadLine(); // Requires that the data is ended with a new line
or
byte[] buffer = new byte[serial.BytesToRead()];
int bytesRead = serial.Read(buffer, 0, buffer.Length);
你也可以使用 []用于读取字节。例如,这对于可以随时从阅读器发送数据的条形码阅读器非常有用。
这是串行通信的基础知识。
使用MSDN并阅读文档: []
因为你没有解释你的目标是什么,它是很难提供比这更多的帮助。
You can also use the SerialPort.DataReceived Event (System.IO.Ports)[^] for reading bytes. This is useful for, for example, a barcode reader where data can be sent from the reader at any time.
That is the basics of serial communication.
Use MSDN and read the documentation: SerialPort Class (System.IO.Ports)[^]
As you don't explain what your goal is, it is difficult to give more help than this.
这篇关于如何将以下java代码转换为C#dotnet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!