Serial port (RS232) Communications

A forum devoted to the discussion of all topics having to do with scripting and other advanced programming using iX Developer.
Post Reply
AMitchneck
Posts: 137
Joined: Mon Jun 11, 2012 2:10 pm

Serial port (RS232) Communications

Post by AMitchneck »

I've been trying to get a T4A to talk over serial to an external device via RS232 without luck. For some reason I'm not every receiving any bytes on the T4A.

This is the code in my script file:

Code: Select all

namespace Neo.ApplicationFramework.Generated
{
    using System;
    using System.Drawing;
    using Neo.ApplicationFramework.Tools;
    using Neo.ApplicationFramework.Common.Graphics.Logic;
    using Neo.ApplicationFramework.Controls;
    using Neo.ApplicationFramework.Interfaces;
    using System.Threading;
    using System.IO;
    using System.IO.Ports;
    
    public partial class Test
    {
        static Thread Test_COM = new Thread(new ThreadStart(Test_COM_Thread));
        static volatile bool Alive = true;
        public static volatile StreamWriter FileIO = null;
        public static volatile bool Write = false;
        public static volatile string FileName = "";
        
        void IR_Bus_Created(System.Object sender, System.EventArgs e)
        {
            Test_COM.Name = "Test COM";
            Test_COM.Priority = ThreadPriority.BelowNormal;
            Test_COM.IsBackground = true;
            
            Test_COM.Start();
        }
        
        ~Test()
        {
            Alive = false;
            Test_COM.Join();
        }
        
        public static bool IsWriting
        {
            get { return (FileIO != null); }
        }
        
        static void Test_COM_Thread()
        {
            TestPort tst_port = new TestPort();
            
            tst_port.Open();
            
            while (Alive)
            {
                Thread.Sleep(20);
                
                if (Write && (FileIO == null))
                {
                    FileIO = new StreamWriter(FileName, false, System.Text.Encoding.ASCII);
                }
                
                // read port
                tst_port.Read();
                
                if ((!Write) && (FileIO != null))
                {
                    FileIO.Close();
                    FileIO = null;
                }
            }
            
            if (FileIO != null)
            {
                FileIO.Close();
                FileIO = null;
            }
            
            tst_port.Close();
        }
        
        public static string ToHex(byte[] data)
        {
            int i = data.Length;
            int j = 0;
            char[] hex = new char[i << 1];
            
            for (i--; i >= 0; i--)
            {
                hex[j] = ToHex((byte)(data[i] >> 4));
                j++;
                hex[j] = ToHex(data[i]);
                j++;
            }
            
            return new string(hex);
        }
        public static char ToHex(byte nibble)
        {
            nibble &= 0x0F;
            
            if (nibble < 10)
                nibble += (byte)'0';
            else
                nibble += (byte)'A' - 10;
            
            return (char)nibble;
        }
    }
    
    public class TestPort : IDisposable
    {
        private SerialPort port = null;

        public void Open()
        {
            if (!IsOpen)
            {
                // Instantiate the communications port (RS232)
                port = new SerialPort("COM1", 38400, Parity.None, 8, StopBits.One);

                // Open the port for communications
                port.Open();
            }
        }

        public void Close()
        {
            if (port != null)
            {
                // Close the port
                port.Close();
                port = null;
            }
        }

        public void Dispose()
        {
            Close();
        }

        public bool IsOpen
        {
            get { return ((port != null) && (port.IsOpen)); }
        }

        public void Read()
        {
            if (!IsOpen) return;
            
            int BytesReceived;
            byte[] BusMsg;
            
            BytesReceived = port.BytesToRead;
            if (BytesReceived == 0) return;
            
            BusMsg = new byte[BytesReceived];
            port.Read(BusMsg, 0, BytesReceived);

            if (Test.FileIO != null)
            {
                Test.FileIO.WriteLine(Test.ToHex(BusMsg));
            }
        }
    }
}
On a PC, I'm running the following test code in a C# application:

Code: Select all

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        using (SerialPort port = new SerialPort("COM1", 38400, Parity.None, 8, StopBits.One))
        {
            port.Open();

            byte[] data = new byte[] { 1, 2, 3, 4, 5 };
            port.Write(data, 0, data.Length);
            MessageBox.Show("Message sent");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("ERROR: " + ex.Message);
    }
}
Does anyone know what I'm doing wrong?
Adam M.
Controls Engineer
FlexEnergy

mark.monroe
Posts: 824
Joined: Tue Mar 13, 2012 9:53 am

Re: Serial port (RS232) Communications

Post by mark.monroe »

Hi AMitchneck,

A few things that I see:

You are writing the serial data to a StreamWriter, yet you do not give the file a name. FileName should be set to a name somewhere, maybe you do that outside this class. But I do not see it anywhere in the code you provided.

Code: Select all

public static volatile string FileName = "";
FileIO = new StreamWriter(FileName, false, System.Text.Encoding.ASCII);
Second:
The below section of code will first open a StreamWrite with 'append to file' set to false, then write some data to the file, and immediately close the StreamWrite. Normally you leave the StreamWrite open, rather than open/close it every time you get new data. Because 'append to file' is set to false, it looks like every time you open that file, you will destroy any data in that file. Try setting 'append to file' to true, and do not destroy the FileIO object every time you are done writing data to the file..

Code: Select all

                if (Write && (FileIO == null))
                {
                    FileIO = new StreamWriter(FileName, false, System.Text.Encoding.ASCII);
                }
               
                // read port
                tst_port.Read();
               //Write = false and FileIO !=null, therefore you will close the
               // FileIO object.
                if ((!Write) && (FileIO != null))
                {
                    FileIO.Close();
                    FileIO = null;
                }
Best Regards,
Mark Monroe

Beijer Electronics, Inc. | Applications Engineer

AMitchneck
Posts: 137
Joined: Mon Jun 11, 2012 2:10 pm

Re: Serial port (RS232) Communications

Post by AMitchneck »

Hi Mark,

I initialize FileName before I set Write to true in a testing screen script. The bool "Write" then remains true until the test is complete. Thus, the file is opened once (erasing the file if it already exists) and only closed once across the entire test.

I did test writing several lines to the file (as if several data packets arrived) and the file did contain all the lines.

The problem seems to be with the serial port control code - it also doesn't work running alone on my computer (once again, I'm receiving nothing).
Adam M.
Controls Engineer
FlexEnergy

mark.monroe
Posts: 824
Joined: Tue Mar 13, 2012 9:53 am

Re: Serial port (RS232) Communications

Post by mark.monroe »

I would use maxterm to send data to the HMI. I would also use the code you have to send data on the PC and put in on the terminal to see if it can send data to the PC. Then you know that your PC and terminal can talk. And your PC code works.

maxterm
Best Regards,
Mark Monroe

Beijer Electronics, Inc. | Applications Engineer

AMitchneck
Posts: 137
Joined: Mon Jun 11, 2012 2:10 pm

Re: Serial port (RS232) Communications

Post by AMitchneck »

Hi Mark,

When I switch the port from COM1 to COM2 (232 to 485) the communications work. Is there something special I need to do to communicate using RS232?
Adam M.
Controls Engineer
FlexEnergy

mark.monroe
Posts: 824
Joined: Tue Mar 13, 2012 9:53 am

Re: Serial port (RS232) Communications

Post by mark.monroe »

No, com 1 will send out the single in 232 format. Are you sure the 232 cable you are using is correct? The pin out for the terminal is below. If you want to use com 1 and com 2 at the same time, you need to use a CAB 109 Beijer cable.

Snap 2012-07-25 at 13.19.52.png
Snap 2012-07-25 at 13.19.52.png (42.32 KiB) Viewed 23683 times
Best Regards,
Mark Monroe

Beijer Electronics, Inc. | Applications Engineer

AMitchneck
Posts: 137
Joined: Mon Jun 11, 2012 2:10 pm

Re: Serial port (RS232) Communications

Post by AMitchneck »

Thank you.

Figured out that the cable I was using needed to be a cross-over cable.
Adam M.
Controls Engineer
FlexEnergy

Post Reply