Click here to Skip to main content
11,706,732 members (32,682 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C Linux
I am trying to write AT commands to a serial port to which a Huawei GSM modem is connected and read the result back. E.g read all SMS messages on the sim card.

Below is my code. When it gets to the read part of the code it remains at that point forever, unless I terminate the program.

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <stdlib.h>
#include <unistd.h> 
#include <time.h>

int main(){
	FILE *fd;
	struct termios options;
	fd = open("/dev/ttyUSB0",O_RDWR | O_NOCTTY);
		printf("port opening successful %d .file description is\n",fd);
		perror("Open port failded");
	//serial configure
	options.c_cflag &= _CSIZE;
	options.c_cflag &= _CS8;
	options.c_cflag &= _PARENB; */
	int rr,r,w;
	char buf[255];
	w = write(fd,"AT\n",16);
		printf("Data: %s \r\n",buf);
	printf("Hello world \n");
	return 0;

I would like to know if I am doing anything wrong, and if so what is the best way to go about it.
Posted 30-Jun-11 1:06am
Edited 30-Jun-11 1:30am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Reading from the serial port is blocking operation. Your calling thread will remain in wait state and waken up if timeout expired (if you use timeout) or a device on the other end of the cable writes something using matching communication parameters. How do you know your device actually rights some data?

As the problem of the blocking call always exists, that said, you need to implement read operations in a separate thread, read all what comes in your input buffer, interpret incoming data on the fly and communication with other thread(s) using thread synchronization primitives. Every platform supporting threads also support their synchronization methods.


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 146
1 Sergey Alexandrovich Kryukov 140
2 chainerlt 110
3 Mika Wendelius 80
4 ppolymorphe 71
0 OriginalGriff 9,190
1 Sergey Alexandrovich Kryukov 8,407
2 CPallini 5,189
3 Maciej Los 4,756
4 Mika Wendelius 3,686

Advertise | Privacy | Mobile
Web03 | 2.8.150819.1 | Last Updated 30 Jun 2011
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100