C#串口连接无法正常工作

时间:2014-08-28 18:55:30

标签: c# io serial-port

我正在尝试通过RS-232电缆(串行)将ASCII字符发送到VideoJet Excel 170i打印机

当我使用测试程序时,我从打印机获得响应没有问题,我可以更改打印机的状态。

这是我做的代码

 public partial class Form1 : Form
{
    private SerialPort port = new SerialPort("COM1");
    private delegate void SetTextDeleg(string data);

    public Form1()
    {
        InitializeComponent();
    }

    private void addtoText(string text)
    {
        this.richTextBox1.Text = this.richTextBox1.Text + "\n" + text;
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            port.BaudRate = 9600;
            port.Parity = Parity.None;
            port.StopBits = StopBits.One;
            port.DataBits = 8;
            port.Handshake = Handshake.None;
            port.ReadTimeout = 2000;
            port.WriteTimeout = 500;

            port.DtrEnable = true;
            port.RtsEnable = true;

            port.Open();

            port.DataReceived += DataReceivedHandler;

            addtoText("Port is ready");
        }
        catch (Exception ex)
        {
            //Console.WriteLine("Error opening my port: {0}", ex.Message);
            addtoText("Error opening my port: {0}" + ex.Message);
        }
    }

    public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        System.Threading.Thread.Sleep(500);
        string indata = sp.ReadExisting();
        this.BeginInvoke(new SetTextDeleg(DisplayToUI), new object[] { indata });
    }

    private void DisplayToUI(string displayData)
    {
        addtoText(displayData);

    }


    private void button1_Click(object sender, EventArgs e)
    {
        port.Write(tbxAscii.Text);
    }

    private void Form1_Leave(object sender, EventArgs e)
    {
        port.Close();
    }
}

我需要将ASCII字符发送到打印机,例如

[1B][01][09]

将打印机转为打印模式。

打印机应该响应,我没有响应,打印机不会改变其状态。

我有一个程序来测试打印机的串行连接,我可以看到所有设置都正常(波特率,奇偶校验...端口),实际上是在端口COM1上。

所以我认为我的port.write没有向打印机发送任何信息......或者我正在发送损坏信息而我没有读取打印机的响应。

1 个答案:

答案 0 :(得分:2)

您确定要发送[1B][01][09]还是要发送该字节序列0x1b,0x01,0x09

只是为了查看是否有效,请在点击处理程序

中发送以下内容
private void button1_Click(object sender, EventArgs e)
{
    var bytes = new byte[] { 0x1b, 0x01, 0x09 };
    port.Write(bytes, 0, bytes.Length);
    port.Flush(); // make sure everything is written
}

必须更改读取,以处理字节

SerialPort sp = (SerialPort)sender;
System.Threading.Thread.Sleep(500);

var available = sp.BytesToRead; // check how many bytes are ready to be read
if (available < 1)
    return;

var buffer = new byte[available];
sp.Read(buffer, 0, available);

var indata = BitConverter.ToString(buffer); // convert bytes to a hex representation

this.BeginInvoke(new SetTextDeleg(DisplayToUI), new object[] { indata });