Reading/Writing Ports

Last post 11-06-2007 17:33 by Anonymous. 5 replies.
Page 1 of 1 (6 items)
Sort Posts: Previous Next
  • 07-10-2002 8:40

    • ctacke
    • OpenNETCF Staff
    • Top 10 Contributor
    • Joined on 07-27-2007
    • Indiana
    • Posts 1,890

    Reading/Writing Ports

    Credit: Chris Tacke

    This code was written for reading and writing 1 or 2 bytes to and from CE ports for analog and digital I/O, so it will require some massaging for larger streams like COM port transfer. Still, it's a start.


    using System;
    using System.Runtime.InteropServices;

    namespace ADSLibrary
    {
    public class CEPorts
    {
    public static bool PortIsValid(string PortName)
    {
    int hPort = CEAPI.INVALID_HANDLE_VALUE;

    // open port
    hPort = CEAPI.CreateFile(PortName, CEAPI.GENERIC_WRITE, 0, 0, CEAPI.OPEN_EXISTING, 0, 0);

    // check for success
    if(hPort == CEAPI.INVALID_HANDLE_VALUE)
    {
    if(CEAPI.GetLastError() == 55)
    return false;
    else
    {
    Exception e = new Exception("Failed to open port '" + PortName + "': " + Convert.ToString(CEAPI.GetLastError()));
    throw e;
    }
    }

    CEAPI.CloseHandle(hPort);

    return true;
    }

    public static bool WritePort(string PortName, byte Value)
    {
    int hPort = CEAPI.INVALID_HANDLE_VALUE;
    int dwSize = 1;
    byte[] buffer = {Value};

    // open port
    hPort = CEAPI.CreateFile(PortName, CEAPI.GENERIC_WRITE, 0, 0, CEAPI.OPEN_EXISTING, 0, 0);

    // check for success
    if(hPort == CEAPI.INVALID_HANDLE_VALUE)
    {
    Exception e = new Exception("Failed to open port '" + PortName + "': " + Convert.ToString(CEAPI.GetLastError()));
    throw e;
    }

    // write to port
    if(!CEAPI.WriteFile(hPort, buffer, 1, ref dwSize, 0))
    {
    Exception e = new Exception("Unable to write to port '" + PortName + "': " + Convert.ToString(CEAPI.GetLastError()));
    throw e;
    }

    // close port
    if(!CEAPI.CloseHandle(hPort))
    {
    Exception e = new Exception("Unable to close port '" + PortName + "': " + Convert.ToString(CEAPI.GetLastError()));
    throw e;
    }

    return true;
    }

    public static byte ReadPortByte(string PortName)
    {
    int hPort = CEAPI.INVALID_HANDLE_VALUE;
    int read = 0;
    byte[] buffer = new byte[1];


    // open port
    hPort = CEAPI.CreateFile(PortName, CEAPI.GENERIC_READ, 0, 0, CEAPI.OPEN_EXISTING, 0, 0);

    // check for success
    if(hPort == CEAPI.INVALID_HANDLE_VALUE)
    {
    Exception e = new Exception("Failed to open port '" + PortName + "': " + Convert.ToString(CEAPI.GetLastError()));
    throw e;
    }

    // read port value
    if(!CEAPI.ReadFile(hPort, buffer, 1, ref read, 0))
    {
    Exception e = new Exception("Failed to read port '" + PortName + "': " + Convert.ToString(CEAPI.GetLastError()));
    throw e;
    }

    if(read != 1)
    {
    Exception e;
    e = new Exception("BYTE block size specified but " + Convert.ToString(read) + " bytes returned");

    throw e;
    }

    // close port
    if(!CEAPI.CloseHandle(hPort))
    {
    Exception e = new Exception("Unable to close port '" + PortName + "': " + Convert.ToString(CEAPI.GetLastError()));
    throw e;
    }

    return buffer[0];
    }

    public static ushort ReadPortWord(string PortName)
    {
    int hPort = CEAPI.INVALID_HANDLE_VALUE;
    int read = 0;
    byte[] buffer = new byte[2];


    // open port
    hPort = CEAPI.CreateFile(PortName, CEAPI.GENERIC_READ, 0, 0, CEAPI.OPEN_EXISTING, 0, 0);

    // check for success
    if(hPort == CEAPI.INVALID_HANDLE_VALUE)
    {
    Exception e = new Exception("Failed to open port '" + PortName + "': " + Convert.ToString(CEAPI.GetLastError()));
    throw e;
    }

    // read port value
    if(!CEAPI.ReadFile(hPort, buffer, 2, ref read, 0))
    {
    Exception e = new Exception("Failed to read port '" + PortName + "': " + Convert.ToString(CEAPI.GetLastError()));
    throw e;
    }

    if(read != 2)
    {
    Exception e;
    e = new Exception("WORD block size specified but " + Convert.ToString(read) + " bytes returned");

    throw e;
    }

    // close port
    if(!CEAPI.CloseHandle(hPort))
    {
    Exception e = new Exception("Unable to close port '" + PortName + "': " + Convert.ToString(CEAPI.GetLastError()));
    throw e;
    }

    // convert the 2-byte array to a word
    return (ushort)((buffer[1] << 8) + buffer[0]);
    }
    }

    internal class CEAPI
    {
    public const uint GENERIC_READ = 0x80000000;
    public const uint GENERIC_WRITE = 0x40000000;
    public const int OPEN_EXISTING = 3;
    public const int INVALID_HANDLE_VALUE = -1;

    [DllImport("coredll.dll", EntryPoint="WriteFile")]
    public static extern bool WriteFile(
    int hFile,
    Byte[] lpBuffer,
    int nNumberOfBytesToWrite,
    ref int lpNumberOfBytesWritten,
    int lpOverlapped);

    [DllImport("coredll.dll", EntryPoint="ReadFile")]
    public static extern bool ReadFile(
    int hFile,
    byte[] lpBuffer,
    int nNumberOfBytesToRead,
    ref int lpNumberOfBytesRead,
    int lpOverlapped);

    [DllImport("coredll.dll", EntryPoint="CreateFile")]
    public static extern int CreateFile(
    string lpFileName,
    uint dwDesiredAccess,
    int dwShareMode,
    int lpSecurityAttributes,
    int dwCreationDisposition,
    int dwFlagsAndAttributes,
    int hTemplateFile);

    [DllImport("coredll.dll", EntryPoint="CloseHandle")]
    public static extern bool CloseHandle(int hObject);

    [DllImport("coredll.dll", EntryPoint="GetLastError")]
    public static extern int GetLastError();
    }

    }


  • 10-21-2002 23:37 In reply to

    Re: Reading/Writing Ports

    i have few questions:
    does c# have any comport class or IO to do that
    i thought no, otherwise,you don't wrapping api

    about import dll, the internal CEAPI(it is inner wrapper class & partly wrapped related api)
    doing that is very huge!
    1 i don't know which dll
    2 i don't know which methods
    3 i don't know which constants eg INVALID_HANDLE_VALUE = -1

    2ndly, using createfile(portname...) the portname is "COM1:"or etc
    can you give me some hints on pass the "hayes compatible on COM1:"
    instead of "COM1:"

    3rdly,i don't understand. (buffer[0] << 8) + buffer[1] intsead
    (ushort)((buffer[1] << 8) + buffer[0]);

    Thanks in advance,
    tang, sze yee (c2)




  • 07-06-2004 2:53 In reply to

    Re: Reading/Writing Ports

    Chris,

    code that you have posted has problems. it throws notsupportedexception when CreateFile is called. i am testing it on iPaq having win ce 4.XX

    Rizwan Ansari
  • 02-10-2005 1:20 In reply to

    Re: Reading/Writing Ports

    Please switch to IO.Serial namespace to program serial ports on your device.
  • 06-21-2005 0:44 In reply to

    Re: Reading/Writing Ports

    Hello Chris,

    Thanks for posting this code.

    I am using win ce 4.2 device, c#.net and smartdeviceapplication project type. I have to print to a mobile printer using a bluetooth adapter on a serial port.

    Using the class code you posted, i am able to Open the port(CreateFile) but when i write to the port(WriteFile) it throws 1359. I am not able to write to COM3 port.

    If i try to open any other port 1 to 2 and 4 to 11, it throws 55 (Failed to open port COM#)

    Please help me.

    With best regards,

    Gulame
  • 11-06-2007 17:33 In reply to

    Re: Reading/Writing Ports

    Hi sir,

    I use your code it perfect adn usefull. before anything.. Thank you very much.

    I use this code to read GPS from Com1 (It's Phsycal) then I have good response .But in this code I have some problem. I don't no it's problem on my device or other.

    This Code on read
    for (int i = 0; i < buffer_read.Length; i++)
    {
    if (buffer_read[i] != 0)
    {
    tmp = Convert.ToChar(buffer_read[i]);
    if (found_sign) {
    if (tmp == 'G') {
    start_read = true;
    }
    }
    if (tmp == '$')
    {
    found_sign = true;
    }
    else {
    found_sign = false;
    }
    if (start_read)
    {
    str_read += tmp;
    sum++;
    }
    }

    }

    *****str_read is reponse of this code

    My device COM1 data is
    ...
    ... (Some time it's have some line before this but some time it not I don't know why)

    $PSRFXTXTWK: 1452*4B
    $PSRFXTXTPOS: -1351940 593620 1893803*28
    $PSRFXTXTCLK: 96638*03
    $PSRFXTXTCHNL: 15*5F
    $PSRFXTXTBAUD RATE: 57600*51
    $GPGGA,011042.724,,,,,0,00,,,,M,0.0,,M,,0000*51 // line 6
    $GPGSA,A,1,,,,,,,,,,,,,,,*1E //line 7
    $GPRMC,011042.72,V,,,,,,,071107,,,N*4A //line 8

    I know last 3 line is GPS data but. I thing it not have Lat,Long (On line 6). but why some program can read it. And am not?

    Now I thing
    1. My GPS that I get it not all data.
    2. My code is Decode for ture way.
    3. I can't Synchronize i use beginInvoke for read data and Thread(because I don't know how can I syn it). I do event for 1 secound and I get this data

    If you or other people on this board want to do see my project please POST your mail or send mail to cosciisoft@hotmail.com

    Sory for my bad english

    Thank you for all code
    Wanchai ,
    Open Source developer on Thailand







Page 1 of 1 (6 items)