Click here to Skip to main content
15,896,063 members

Serial Port Programming in Linux

Edem Kofi asked:

Open original thread
Hi,
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);
	if(fd){
		//fcntl(fd,F_SETFL,0);
		printf("port opening successful %d .file description is\n",fd);
	}else{
		perror("Open port failded");
	}

	//serial configure
	/*tcgetattr(fd,&options);	

	cfsetispeed(&options,B9600);
	cfsetospeed(&options,B9600);
	options.c_cflag &= _CSIZE;
	options.c_cflag &= _CS8;
	options.c_cflag &= _PARENB; */

	int rr,r,w;
	char buf[255];

	printf("Writing\r\n");
	w = write(fd,"AT\n",16);
	printf("unsleeping\r\n");
	usleep(100000);
	printf("Reading\r\n");
	r=read(fd,buf,6);
	printf("Read\r\n");
	if(r>0){
		printf("Data: %s \r\n",buf);
	}
	close(fd);
	printf("Hello world \n");
	return 0;
}</time.h></unistd.h></stdlib.h></termios.h></fcntl.h></string.h></stdio.h>


I would like to know if I am doing anything wrong, and if so what is the best way to go about it.
Tags: C, Linux

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900