Skip to content

godsharp/GodSharp.SerialPort

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GodSharp.SerialPort

Easy to use SerialPort class.

AppVeyor build status NuGet MyGet

Getting Started

  1. New instance GodSerialPort.
GodSerialPort serial = new GodSerialPort("COM1", 9600);
  1. Initialize the GodSerialPort instance with received data action: Action<byte[]>.
serial.Init((bytes)=>{});
  1. Open SerialPort object.
serial.Open();
  1. Write/Send data.
byte[] bytes = new byte[]{31,32,33,34};
serial.Write(bytes);
serial.WriteAsciiString("ascii string");
serial.WriteHexString("7E 48 53 44");

Sample

class Program
{
    static void Main(string[] args)
    {
        Console.Write("input serialport number(only 0-9):");
        string read = Console.ReadLine();
        bool flag = uint.TryParse(read, out uint num);
        if (!flag)
        {
            Exit();
        }

        GodSerialPort gsp = new GodSerialPort("COM"+num, 9600);
        gsp.Init((bytes) => {
             string buffer = string.Join(" ", bytes);
             Console.WriteLine("receive data:" + buffer);
        });
        flag = gsp.Open();

        if (!flag)
        {
            Exit();
        }

        Console.WriteLine("serialport opend");

        Console.WriteLine("press any thing as data to send,press key 'q' to quit.");

        string data = null;
        while (data == null || data.ToLower()!="q")
        {
            if (!string.IsNullOrEmpty(data))
            {
                Console.WriteLine("send data:"+data);
                gsp.WriteAsciiString(data);
            }
            data = Console.ReadLine();
        }
    }

    static void Exit()
    {
        Console.WriteLine("press any key to quit.");
        Console.ReadKey();
        Environment.Exit(0);
    }
}

About

An easy-to-use .NET SerialPort class.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages