I want to access my mobile phone,connected through its USB cable, from a C program to send AT commands to it.Can sumbody pls help me

Recommended Answers

All 27 Replies

Well your first handicap is that Turbo C will know nothing about USB.

I'm going to make a guess that your operating system is XP - am I right?

sry but im on windows 2000...as fr Turbo C not knowing abt USB wat shud i do abt it...is it evn possible to use Turbo C for my application.also I have read abt windows api for serial comm purposes...is it possible to use that wid Turbo C or will i require a different compiler.
Hope im not asking fr a lot :)

http://www.catb.org/~esr/faqs/smart-questions.html#writewell

Nice one...so here's what i want to do
I have a mobile phone connected to my PC thorugh its USB cable. I want to develop a C application that will send AT commands(hope ur aware of em) to the phone. The phone will be required to make calls, send SMSs,etc and it has to send an acknowledgement once it finishes its task so that the next one can be performed(Note: I dont want to use polling, instead I want an interrupt to be sent once a task is over). I am working on Windows 2000 & presently using Turbo C.
Q.1 Is the above task possible wid Turbo C?
Q.2 If so, how to send a long string of AT command(eg. ATD"12345678"<;>) using outportb,etc?
Q.3 How do i get the response codes of the AT command to generate an interrupt?
Hopin fr a longer & more helpful response this time :)

No it isn't possible using USB because your compiler was obsolete long before USB was invented.

Get a compiler for this millennium, say Visual Studio Express or code::blocks
http://www.thefreecountry.com/compilers/cpp.shtml
http://www.compilers.net/Dir/Free/Compilers/CCpp.htm
http://www.codeblocks.org/

When you've got a compiler compatible with your OS and technologies, take a look here
http://www.lvr.com/usb.htm

Wait, when you say "USB", do you mean USB to serial ?
Not that it matters much, upgrading your compiler should be done anyway.

AT commands are serial

so you will have to first deal with USB-Serial conversion.

but yeah, throw that Turbo C trash away real quick before it makes you a completely worthless programmer.

(an aside to Salem, or anyone else: where are all these Turbo-C people coming from? how does Borland keep perpetuating their shi**y compiler?? )

I hv been tryin 2 dwnld visual c++2005 but i keep gettin an error in the dwnld. also the latest borland compiler is 400mb(2 huge fr me 2 dwnld)...can u pls suggest an appropriate compiler fr windows 2000 which is ANSI C compliant

code::blocks would be my suggestion.
http://www.codeblocks.org/
Be sure you get the IDE and the compiler (the larger of the two downloads) the first time you get it. The IDE itself is under current development.

^ what he said.

the version you want is the one that has "MinGW" in the name. that's the GCC compiler.

i think you'll like the IDE, too.

Which header files hv to be included to access serial ports using the codebloscks compiler? is dere a tutorial fr d same????

Sorry, but I'm not going to tolerate you mashing of the English language, so I'm going to ignore you instead.

commented: word. +3

Sorry, but I'm not going to tolerate you mashing of the English language, so I'm going to ignore you instead.

I thought this was a forum for C & not the "English language".All I'm asking for is a little help regarding how to access serial ports using the Codeblocks compiler that you have recommended.

LOL, come on, dude. just look at this

Which header files hv to be included to access serial ports using the codebloscks compiler? is dere a tutorial fr d same????

hv?
dere?
fr?
d?

are you serious???

you sound like a complete tard. if you cant be bothered to "talk" correctly, what matter is it to us whether or not you ever get your code right?

you know, i cant speak for anyone else here, but this... hardware, C code ... it's my industry. it's how i make a living. i spend 45 hours a week at a job, and i have to deal with many co-workers, from different areas. and the simple fact is, i don't want to work with idiots.

i just don't. Life is too short, and i don't have the patience for them. So it's in my interest to dissuade people who i think are idiots from entering my industry. While I can't actively *stop* them, I certainly don't have to *help* them.


.

LOL, come on, dude. just look at this

hv?
dere?
fr?
d?

are you serious???

you sound like a complete tard. if you cant be bothered to "talk" correctly, what matter is it to us whether or not you ever get your code right?

you know, i cant speak for anyone else here, but this... hardware, C code ... it's my industry. it's how i make a living. i spend 45 hours a week at a job, and i have to deal with many co-workers, from different areas. and the simple fact is, i don't want to work with idiots.

i just don't. Life is too short, and i don't have the patience for them. So it's in my interest to dissuade people who i think are idiots from entering my industry. While I can't actively *stop* them, I certainly don't have to *help* them.


.

Well let me assure you I have enough command over the English language but its just that my generation is probably more used to converse in the "SMS lingo". If you have a problem understanding my language there is a more gracious way of saying so rather than adopting a condescending tone like you just did(or the guy before you). I appreciate the fact that you are trying to help me but please understand that I am just an amateur & not an expert like you all.

Well let me assure you I have enough command over the English language but its just that my generation is probably more used to converse in the "SMS lingo". If you have a problem understanding my language there is a more gracious way of saying so rather than adopting a condescending tone like you just did(or the guy before you). I appreciate the fact that you are trying to help me but please understand that I am just an amateur & not an expert like you all.

There are many people here from non-English speaking countries and leek speak is difficult if not impossible for them to read. Hell, I even have trouble reading your posts. Please read DaniWeb Rules -- the link is at the top of every page. And any further posts about this matter will get this thread closed.

CHAMPNIM

check out this example:

http://www.captain.at/howto-simple-serial-port-test-example.php

and just to clarify, your C code is not dependent on CodeBlocks ... CodeBlocks is just the development environment (IDE) ... your C code is dependent upon being compatible with the "GCC compiler" ... this is standard ANSI C, and will serve you well to learn to do the majority of your coding on.

MSVC is another widely-used compiler. you could, at some point, download the free MSVC compiler and use it from CodeBlocks... but worry about that later.


.

Im trying to send "AT\r" to my phone but writefile is giving an error(error no 87)...please tell me what is wrong.

#include <iostream>
#include <windows.h>
#include <string.h>

int main()
{
    DCB dcb;
	HANDLE hCom;
	BOOL fSuccess;
	OVERLAPPED o;
	DWORD dwEvtMask;
	char buffer[2048];
	char *pcCommPort = "COM4";

	hCom = CreateFile( pcCommPort,
                     GENERIC_READ | GENERIC_WRITE,
                     0,    // comm devices must be opened w/exclusive-access
                     NULL, // no security attributes
                     OPEN_EXISTING, // comm devices must use OPEN_EXISTING
					 FILE_FLAG_OVERLAPPED,
                     NULL  // hTemplate must be NULL for comm devices
                     );

	if (hCom == INVALID_HANDLE_VALUE)
	{
      // Handle the error.
      printf ("CreateFile failed with error %d.\n", GetLastError());
      return (1);
	}
		fSuccess = GetCommState(hCom, &dcb);

 	if (!fSuccess)
 	{
      // Handle the error.
       printf ("GetCommState failed with error %d.\n", GetLastError());
       return (2);
     }

 	// Fill in the DCB: baud=9600 bps, 8 data bits, no parity, and 1 stop bit.

 	dcb.BaudRate = CBR_9600;     // set the baud rate
 	dcb.ByteSize = 8;             // data size, xmit, and rcv
 	dcb.Parity = NOPARITY;        // no parity bit
 	dcb.StopBits = ONESTOPBIT;    // one stop bit

 	fSuccess = SetCommState(hCom, &dcb);

 	if (!fSuccess)
 	{
 		// Handle the error.
 		printf ("SetCommState failed with error %d.\n", GetLastError());
 		return (3);
     }

 	printf ("Serial port %s is successfully reconfigured.\n", pcCommPort);

    //char *command="A";
    unsigned long byteswritten;
    if(!WriteFile(hCom,"AT\r",3,&byteswritten,NULL))
    {
        printf("WriteFile failed with error %d.\n", GetLastError());
        return (4);
    }
    //printf("String %s successfully written to %s port",command,pcCommPort);
}

You open the port specifying FILE_FLAG_OVERLAPPED, but the WriteFile() call is missing the required pointer to an OVERLAPPED structure.
(87 == ERROR_INVALID_PARAMETER)

Thanks for pointing out that silly mistake.:)
However now I'm stuck with an even bigger problem. The thing is that my application is supposed to call a no & once that conversation ends it is supposed to notify the program so that the next call can be made. How should I do this? I have read about stuff like overlapped I/O, asynchronous I/O,etc but none of it is making much sense. Can somebody explain in simpler terms whether it is possible for me to do so & what commands/logic need to be used for that?

How about something like this:

void Dial(char* number)
{
   // the code you had in main goes here
}

int main()
{
    char phone[16];
    char answer[2];
    while(true)
    {
        printf("Dial a number (Y/N)\n");
        fgets(answer,sizeof(answer),stdin);
        if( answer[0] == 'n' || answer[0] == 'N')
             break;
        printf("Enter phone number\n");
        fgets(phone,sizeof(phone),stdin);
        Dial(phone);
   }
   return 0;
        
}

Will this work...what I mean to say is that once a no. has been dialled the program would remain in the loop for as long as the call proceeds.Isn't that going to consume a lot of resources? If so, is there a 'cheaper' way out?

>>program would remain in the loop for as long as the call proceeds
Do you mean that while loop that I posted? If not, then what loop do you mean

>>is there a 'cheaper' way out?
Probably not. I assume there is a lot of other code that you have not posted so I don't know how much resources you mean. Hardware today is cheap -- if the computer needs more ram then just toss it another memory card (assuming that is even possible). If you mean something like file handles then don't worry about that either as long as you close all handles correctly.

Yes I was talking about that while loop. My basic contention is that suppose the call goes on for 20mins or so, then the program should only come into action once it is notified that the call has ended...it should be in some kind of a 'sleep' state...something like where it can do some other job & only once it is notified that the previous call is over should the next call be made. Hope you understand my problem :)

The code I posted is a single threaded program meaning that the code in main() stops while the code in Dial() is executed. The concerns you expressed are only relevent in multi-thread programs. If your program is not multi-threaded then don't worry about it.

I am trying to make my program multi-threaded. But I'm unable to proceed with the WriteFile part itself. Can somebody explain how to make use of the Overlapped structure?

Please ignore the above post & clarify my doubts regarding the following code...

int main()
{
    DCB dcb;
	HANDLE hCom;
	BOOL fSuccess;
	OVERLAPPED o;
	COMMTIMEOUTS timeouts;
	DWORD dwEvtMask;
	char buffer[2048];
	char *pcCommPort = "COM4";  //specify the port to be opened

	hCom = CreateFile( pcCommPort,
                     GENERIC_READ | GENERIC_WRITE, //read & write
                     0,    // comm devices must be opened w/exclusive-access
                     NULL, // no security attributes
                     OPEN_EXISTING, // comm devices must use OPEN_EXISTING
					 FILE_FLAG_OVERLAPPED, //Overlapped I/O enabled
                     NULL  // hTemplate must be NULL for comm devices
                     );

	if (hCom == INVALID_HANDLE_VALUE)
	{
      // Handle the error.
      printf ("CreateFile failed with error %d.\n", GetLastError());
      return (1);
	}

    fSuccess = GetCommState(hCom, &dcb);

 	if (!fSuccess)
 	{
      // Handle the error.
       printf ("GetCommState failed with error %d.\n", GetLastError());
       return (2);
     }

 	// Fill in the DCB: baud=9600 bps, 8 data bits, no parity, and 1 stop bit.

 	dcb.BaudRate = CBR_9600;     // set the baud rate
 	dcb.ByteSize = 8;             // data size, xmit, and rcv
 	dcb.Parity = NOPARITY;        // no parity bit
 	dcb.StopBits = ONESTOPBIT;    // one stop bit

 	fSuccess = SetCommState(hCom, &dcb);

 	if (!fSuccess)
 	{
 		// Handle the error.
 		printf ("SetCommState failed with error %d.\n", GetLastError());
 		return (3);
     }

 	printf ("Serial port %s is successfully reconfigured.\n", pcCommPort);

    //Set port timeout values
    timeouts.ReadIntervalTimeout         = MAXDWORD; //These values ensure that the read operation
    timeouts.ReadTotalTimeoutMultiplier  = 0;        //returns immediately with the characters that have
    timeouts.ReadTotalTimeoutConstant    = 0;        //already been received, even if none are received
    timeouts.WriteTotalTimeoutMultiplier = 0;        //Time-outs not used
    timeouts.WriteTotalTimeoutConstant   = 0;        //for write operation


    if (!SetCommTimeouts(hCom, &timeouts))
    {
        //assert(0);
        printf("Error setting time-outs. %d\n",GetLastError());
        return (1);
    }

    // Set the event mask.

    fSuccess = SetCommMask(hCom, EV_RXCHAR | EV_TXEMPTY);

    if (!fSuccess)
    {
        // Handle the error.
        printf("SetCommMask failed with error %d.\n", GetLastError());
        return(5);
    }

    // Create an event object for use by WaitCommEvent.

    o.hEvent = CreateEvent(
        NULL,   // default security attributes
        TRUE,   // manual-reset event
        FALSE,  // not signaled
        NULL    // no name
		);


    // Initialize the rest of the OVERLAPPED structure to zero.
    o.Internal = 0;
    o.InternalHigh = 0;
    o.Offset = 0;
    o.OffsetHigh = 0;

    //assert(o.hEvent);
    DWORD dwBytesRead;

    if (WaitCommEvent(hCom, &dwEvtMask, &o))
    {
        if (dwEvtMask & EV_RXCHAR)
        {
             // To do.
             if ( WaitForSingleObject(o.hEvent,INFINITE) == WAIT_OBJECT_0)
            {
                char szBuf[100];
                do
                {
                    ReadFile( hCom,szBuf,strlen(szBuf),&dwBytesRead,&o);
                    printf("%s\n",szBuf);
                }while (dwBytesRead > 0 );
                ResetEvent(o.hEvent);
            }
        }

        if (dwEvtMask & EV_TXEMPTY)
        {
            // To do.
        }
    }
    else
    {
        DWORD dwRet = GetLastError();
        if( ERROR_IO_PENDING == dwRet)
        {
            printf("I/O is pending...\n");

            // To do.
        }
        else
            printf("Wait failed with error %d.\n", GetLastError());
    }

    char *command="AT\r\n";
    DWORD byteswritten;
    if(!WriteFile(hCom,command,strlen(command),&byteswritten,&o))
    {
        printf("WriteFile failed with error %d.\n", GetLastError());
        return (4);
    }
    printf("String %s\n successfully written to %s port",command,pcCommPort);

}

Here I'm getting a writefile error no 997. Is the writefile part correct? Here I first want to send a command to my phone & then read its response. Also how do I check for a particular response, which will then trigger the next writefile command?

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.