May 01, 2024, 04:38:14 PM

News:

Own IWBasic 2.x ? -----> Get your free upgrade to 3.x now.........


Serial port interrupt ?

Started by paja, January 26, 2011, 02:23:58 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

paja

January 26, 2011, 02:23:58 AM Last Edit: January 26, 2011, 04:02:11 AM by paja
Hi,

Does anybody know how read interrupt for serial port COMn ?

Paja

sapero

You can wait for an interrupt by calling WaitCommEvent function. Before you call it, execute SetCommMask to specify what events you want to monitor:

Example for 2-wire i2c interface (SDA, SCL)
SetCommMask(hPort, EV_CTS | EV_DSR)

' nonoverlapped (blocking)
int flags
WaitCommEvent(hPort, &flags, 0)
if (flags & EV_CTS) then OnCtsChanged()
if (flags & EV_DSR) then OnDsrChanged()



' overlapped (nonblocking)
$include "windowssdk.inc"

OVERLAPPED g_comOv' global variable
DWORD g_comEvents ' global variable
HANDLE g_comWait  ' global variable
HANDLE g_hDevice  ' the COM port

' the COM port must be opened in asynchronous mode: g_hDevice = CreateFile(..., FILE_FLAG_OVERLAPPED, 0)

' initiate events reception
SetCommMask(g_hDevice, EV_CTS | EV_DSR)
ReceiveInterrupts()
' return to your main loop

' before terminating, or to cancel pending WaitCommEvent, execute CancelInterrupts
sub CancelInterrupts()
CancelIo(g_hDevice)
MyCloseComWaitHandle()
if (g_comOv.hEvent) then CloseHandle(g_comOv.hEvent)
g_comOv.hEvent = 0
endsub


sub ReceiveInterrupts()
if (!g_comOv.hEvent) then g_comOv.hEvent = CreateEvent(0,1,0,0)

while (WaitCommEvent(g_hDevice, &g_comEvents, &g_comOv))
' wait completed
OnComStateChanged(0)
' call WaitCommEvent again
endwhile

if (GetLastError() = ERROR_IO_PENDING)
' WaitCommEvent will complete later. Register a callback function
RegisterWaitForSingleObject(&g_comWait, g_comOv.hEvent, &OnComStateChanged, 0, INFINITE, WT_EXECUTEONLYONCE)
else
' error
endif
endsub


sub OnComStateChanged(BOOLEAN TimerOrWaitFired) ' RegisterWaitForSingleObject callback
if (!TimerOrWaitFired)
' com port state changed (interrupt)
MyCloseComWaitHandle()
' check what has changed and execute user callbacks
if (g_comEvents & EV_CTS) then OnCtsChanged()
if (g_comEvents & EV_DSR) then OnDsrChanged()
' wait for next change
ReceiveInterrupts()
endif
endsub


' additional callbacks
sub OnCtsChanged()
' TODO
endsub


sub OnDsrChanged()
' TODO
endsub


' helper function
sub MyCloseComWaitHandle()
if (g_comWait) then UnregisterWait(g_comWait)
g_comWait = 0
endsub