' ASYIO ' This is a sample showing how to do non-blocking serial i/o ' using ScriptBasic. ' ' The program prompts for data lines on a specified serial ' port, and waits for response lines. The program terminates ' if no data is received for 10 secs, or the response line ' is the string "bye". ' ' This function uses waitevents to read a ' line from the serial port or timeout. ' The return value is the received line. ' An empty string is returned if we timed out. ' function waitforline(timeout, fileno) local ch, myline myline = "" ' The loop waits for each character on the ' input stream specifed by fileno. ' Each character is added to our line buffer. ' When we see CR we return our line buffer. ' If we have to wait for more than the timeout ' then we exit the loop and return an empty ' string ' while waitevents(timeout) = fileno ch = input(1, fileno) if asc(ch) <> 10 then if asc(ch) = 13 then waitforline = myline exit sub endif myline = myline & ch endif wend waitforline = "" end function ' ' Main program starts here ' ' We use the built-in command() function to get the command ' arguments. The program should be given the serial port name ' as an argument, for example: ' ' bas asyio.bas asy0 ' if command() = "" then print "\nPlease specify the port name on the command line, eg asy0\n" exit sub endif ' This causes execution to jump to our error ' handling label if any statement causes an ' error to be raised ' on error goto errorlabel ' Open the serial port. ' We need two file numbers: one for input and one for output. ' We set these variables to zero so that they ' are automatically assigned useable file numbers by the ' open calls. ' ifileno = 0 ofileno = 0 open command() for input as ifileno open command() for output as ofileno print "successfully opened port: ifileno = ", ifileno, ", ofileno = ", ofileno, "\n" ' We use the setevent function to specify the input ' file number on which we want to wait for received data. ' This will be done using the waitevents function. ' First clear the event list using an argument of zero dummy = setevent(0) ' We want to be able to wait for received data on the input file number dummy = setevent(ifileno) ' The main loop sends a prompt message to the serial port ' and waits 10 secs for a response. We jump out of the loop ' if the response is an empty string, or starts with "bye" while TRUE print #ofileno, "hello, please type a line:\r\n" a = waitforline(10000, ifileno) if a <> "" then print "received line: ", a, "\n" else goto finished endif if a = "bye" or a like "bye*" then goto finished endif wend finished: close ifileno close ofileno print "Finished\n" stop ' Our error handling code just prints a message and terminates. ' The built-in string error$ contains a description of the error ' errorlabel: print "encountered an error\n" print error$, "\n"