已有56人关注
serialport
发表在C#图书答疑 2010-07-08
是否精华
版块置顶:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace TRY
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}

private void button1_Click(object sender, EventArgs e)
{
SerialPort serialPort1 = new SerialPort();
serialPort1.PortName = "COM1";

serialPort1.BaudRate = 9600;

serialPort1.Open();

byte[] data = Encoding.Unicode.GetBytes(textBox1.Text);

string str = Convert.ToBase64String(data);




serialPort1.WriteLine(str);

MessageBox.Show("数据发送成功!", "系统提示");


}

private void button2_Click(object sender, EventArgs e)
{
SerialPort serialPort1 = new SerialPort();


[font color=#FF0000]byte[] data = Convert.FromBase64String(serialPort1.ReadLine());
[/font]textBox2.Text = Encoding.Unicode.GetString(data);

MessageBox.Show("错误");
//处理错误



serialPort1.Close();

MessageBox.Show("数据接收成功!", "系统提示");


}
}
}
老师您好:
我想用串口接收和发送数据
我把串口的2.3短接。
红色的那地方总出现错误,说未处理invalidoperationexception。端口被关闭
请问老师问题出在哪里?
我一直在用C#开发实战宝典学习,书上没有这方面的内容,希望您能给解决一下!非常感谢
分享到:
精彩评论 2
小科_mrkj
学分:43 LV2
2010-07-08
沙发
读者朋友:
    您好,把SerialPort serialPort1 = new SerialPort();实例化成公有的,让button1和button2都使用这个对象,这样再看一下。
gaopeng218
学分:0 LV1
TA的每日心情
开心
2023-09-05 11:07:10
2010-07-08
板凳
小科老师,谢谢您!成功了
首页上一页 1 下一页尾页 2 条记录 1/1页
手机同步功能介绍
友情提示:以下图书配套资源能够实现手机同步功能
明日微信公众号
明日之星 明日之星编程特训营
客服热线(每日9:00-17:00)
400 675 1066
mingrisoft@mingrisoft.com
吉林省明日科技有限公司Copyright ©2007-2022,mingrisoft.com, All Rights Reserved长春市北湖科技开发区盛北大街3333号长春北湖科技园项目一期A10号楼四、五层
吉ICP备10002740号-2吉公网安备22010202000132经营性网站备案信息 营业执照