Virtual Serial Port Control

 Get Started with Virtual Serial Port Control - Virtual Serial Port Control - Quick Start (virtual-serial-port-control.com)


DLL API Integration - Virtual Serial Port Control SDK - DLL API Integration (virtual-serial-port-control.com)


ActiveX Component Integration - Virtual Serial Port Control SDK - ActiveX Component Integration (virtual-serial-port-control.com)



Microsoft Visual Studio 2005, Visual C# - Virtual Serial Port Control SDK - Microsoft Visual Studio 2005, Visual C# (virtual-serial-port-control.com)


using System;

using System.Net.Sockets;

using System.Threading;


class Program

{

    static void Main()

    {

        string host = "192.168.8.202"; // Set IP

        int port = 4196;               // Set port


        byte[] cmd = new byte[8];

        cmd[0] = 0x01;  // Device address

        cmd[1] = 0x05;  // Command


        using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))

        {

            s.Connect(host, port); // Connect to server

            while (true)

            {

                for (int i = 0; i < 8; i++)

                {

                    cmd[2] = 0;

                    cmd[3] = (byte)i;

                    cmd[4] = 0xFF;

                    cmd[5] = 0;

                    ushort crc = CalculateCRC(cmd, 6);

                    cmd[6] = (byte)(crc & 0xFF);

                    cmd[7] = (byte)(crc >> 8);

                    Console.WriteLine(BitConverter.ToString(cmd));

                    s.Send(cmd);

                    Thread.Sleep(200);

                }


                for (int i = 0; i < 8; i++)

                {

                    cmd[2] = 0;

                    cmd[3] = (byte)i;

                    cmd[4] = 0;

                    cmd[5] = 0;

                    ushort crc = CalculateCRC(cmd, 6);

                    cmd[6] = (byte)(crc & 0xFF);

                    cmd[7] = (byte)(crc >> 8);

                    Console.WriteLine(BitConverter.ToString(cmd));

                    s.Send(cmd);

                    Thread.Sleep(200);

                }

            }

        }

    }


    // CRC calculation method for Modbus

    public static ushort CalculateCRC(byte[] data, int length)

    {

        ushort crc = 0xFFFF;

        for (int pos = 0; pos < length; pos++)

        {

            crc ^= (ushort)data[pos];

            for (int i = 8; i != 0; i--)

            {

                if ((crc & 0x0001) != 0)

                {

                    crc >>= 1;

                    crc ^= 0xA001;

                }

                else

                {

                    crc >>= 1;

                }

            }

        }

        return crc;

    }

}


Ulasan

Catatan popular daripada blog ini

SISTEM PENGOPERASIAN KOMPUTER (OS)

JENIS-JENIS SISTEM PENGOPERASIAN KOMPUTER

JENIS - JENIS ARAHAN SQL