I am trying to send data using the serial port but the write command always returns -1.
This is the code for the write command.
int WriteComm( int Comid, void *buf, int nobtw )
{
unsigned long nobw;
nobw = write(Comid, buf, nobtw);
move(10,5);
perror("");
sleep(10);
return nobw;
}
and this is the code that calls it
gnobw = WriteComm(theApp.idComDev[Seg],&head[1],1); //send network address
I am getting invalid argument as the error but after looking on google I cant find anything explaning what this means or how to fix it. the closes thing I found was this but it uses st0 not ttyS0 so im not sure if its even the same thing.
can anyone explain what i am doing wrong to get this error and how to fix it ?
You should only be examining errno
(this includes calling perror()
) if the write
call failed, which it indicates by returning -1. If the write succeeds, it leaves errno
unchanged.
In order to test for this you should really be assigning the return value to a variable with a signed type - preferably ssize_t
- not an unsigned long
.
You're getting EINVAL back from write( ). That means one of your arguments to the function is invalid: EINVAL = * E *rror, * INVAL *id argument. There are three arguments to the function:
arg your variable
---------------------- -------------
int file descriptor: Comid
void *buf: buf
size_t size: nobtw
write( ) puked when it saw one of those three. So one of those three is wrong.
So put a printf( ) before the call to write( ) and see which one (or two; or three) is wrong.
Where is the actual code (not your memory of the code) that does the open( )? Is the file descriptor returned by open( ) the same one (Comid) you are trying to write( ) onto? If not, there's your problem.
That is the likely error in this mashup.
EINVAL from write(3) means:
The STREAM or multiplexer referenced by fildes is linked (directly or indirectly) downstream from a multiplexer.
What this basically means is that something else has your serial port open for writing at the same time -- at least intermittently. USB to serial converters seem to be particularly vulnerable to this. Other serial drivers will generally only allow you to open them once.
Source:
http://linux.die.net/man/3/write
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.