在進入嵌入式系統之前,必須要懂得如何將裝置與電腦連線,一般來說,大部分都會透過RS232來與裝置建立連線,透過RS232傳送資料並做程式碼的偵錯。利用C撰寫出從RS232讀取到資料並不是一件太困難的事,透過CreateFile()這個函數能讓我們很快的與裝置建立連線,下面列出簡單的程式碼供大家參考。
 
你可以利用微軟的visual c++來進行編譯,參考資料 (1)
 
#include <stdlib.h>
#include <stdio.h>
#include <Windows.h>
 
#define READ_BUF_SIZE 512
#define READ_TIMEOUT 500
 
int main()
{
    HANDLE hFile;
    DWORD dwRead;
    BOOL fWaitingOnRead = FALSE;
    OVERLAPPED osReader = {0};
    char lpBuf[READ_BUF_SIZE];
 
    hFile=CreateFile(TEXT(\\\\.\\com), GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        printf("Could not open file (error %d)\n", GetLastError());
        return 0;
    }
 
    osReader.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (osReader.hEvent == NULL)
    {
        printf("event error");
        return 0;
    } 
 
    while(1)
    {
        Sleep(50);
        if (!fWaitingOnRead)
        {
           // Issue read operation.
           if (!ReadFile(hFile, lpBuf, READ_BUF_SIZE, &dwRead, &osReader)) {
               if (GetLastError() != ERROR_IO_PENDING)
               {
                   printf("error");
                   break;
               }   
               else
                   fWaitingOnRead = TRUE;
        }
 
        if (fWaitingOnRead) {
            DWORD dwRes = WaitForSingleObject(osReader.hEvent, READ_TIMEOUT);
            switch(dwRes)
           {
                // Read completed.
                case WAIT_OBJECT_0:
                    if (!GetOverlappedResult(hFile, &osReader, &dwRead, FALSE))
                        break;
                    else
                    { 
                       // Read completed successfully.
                       for(int i=0; i<dwRead;i++)
                           printf("%c",lpBuf[i]);
                    }
                    //  Reset flag so that another opertion can be issued.
                    fWaitingOnRead = FALSE;
                    break;
                 
                case WAIT_TIMEOUT:
                    break;                      
                default:
                    break;
            }
        }
    }
 
 
    CloseHandle(hFile);
    return 0;
}
 
另一個方法可以使用Python這個程式語言來達成目的,先去下在serial library並將該函式庫安裝在你的電腦中,然後打開python直譯器,參考下面的範例,你應該可以很快的與裝置搭上線。
 
>>> import serial
>>> device=serial.Serial()
>>> device.timeout=500
>>> device.baudrate=115200
>>> device.port=1
>>> device.open()
>>>
>>> while(1):
>>>     x=device.read(1)
>>>     print ord(x[0])
>>>
>>> device.close()
 
 
 
arrow
arrow
    全站熱搜

    CJY0503 發表在 痞客邦 留言(1) 人氣()