#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int main()
{
int fd;
int wd=0;
unsigned char buff[] = { 0x02, 0xFA, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x23, 0x01, 0x21, 0x03};

fd = open("/dev/ttyS0", O_RDONLY | O_NOCTTY | O_NDELAY );
if (fd == -1)
{printf("error opening");}
else
{
printf("hi1");
fcntl(fd, F_SETFL, 0);


wd=write(fd, buff, 13 );
printf("hi");
}
printf("%d", wd);
//i get fd to be 3 and wd to be -1 so what is the problem??
close(fd);
}

Dani AI

Generated

’s symptom (fd == 3 but write() returns -1) is exactly the kind of failure that needs an errno check first. As already noted, a file descriptor opened read‑only will fail on write() — but other causes exist, so the concrete next step is to print the error (for example with perror() or strerror(errno)) and use that code to guide debugging (EBADF = bad file descriptor / not writable, EAGAIN = non‑blocking would block, EIO/ENXIO = driver/hardware problem, etc.).

Practical checklist to resolve the problem:

  • Open the serial device with write capability (not read‑only). Avoid O_NDELAY/non‑blocking during initial testing unless non‑blocking semantics are required.
  • Ensure the process has permission to open the device node (group membership like dialout or root), and confirm the correct node (/dev/ttyS0 vs /dev/ttyUSB0) with dmesg/ls -l.
  • Configure the port with termios after opening: set baud rate (cfset*), enable receiver and local mode (CLOCAL | CREAD), set 8N1 (CS8, no parity), put the port in raw mode (or use cfmakeraw), set VMIN/VTIME for blocking/timeout behavior, and apply with tcsetattr. Flush output (tcflush) before the first write if needed. Disable hardware flow control unless the device expects it.

Useful quick tests and tools: stty -F /dev/ttyS0 -a to inspect settings, minicom/screen/socat to verify the link from the shell, strace to see failing syscalls, and dmesg for kernel/device messages. Following that sequence (open for write → set termios → flush → write → check errno) will isolate whether the failure is a flag/permission mistake or a lower‑level device/driver issue.

Recommended Answers

All 2 Replies

.

fd = open("/dev/ttyS0", O_RDONLY | O_NOCTTY | O_NDELAY );

it not gonna work if you use O_RDONLY tag,
because you tell the fd that I can use to read stuff, not to write into it.

so try this

fd = open("/dev/ttyS0", O_NOCTTY | O_NDELAY );
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.