Thread: Reading and writing to serial port.

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    68

    Reading and writing to serial port.

    Hi all!
    I send some data to serial port:

    Code:
        
    int main(int argc, char *argv[]) 
    { 
       
        int pointer=0;
        unsigned char chr;
           
         FILE* portfp ; 
         //set system to connect to com port
         system("mode com1: baud=9600 parity=n data=8 stop=1 to=off xon=off"); 
         //open port for write-read mode
         portfp = fopen(config.port, "r+" ); 
         //send to port first packet
        //till now everything ok
         fprintf( portfp, ini_val[pointer].data);  
        while(pointer<packet)
         {
              //get char from com port
              chr = fgetc(portfp);
              if(chr=='s')
             {        
               pointer++;
               fprintf( portfp,ini_val[pointer].data);
               printf("pass");
            }        
            if(chr=='f')  
            {
                printf("fail");
               exit(0);
            }             
         }
        
          printf("close");  
         fclose(portfp); 
         
         system("PAUSE");
         return EXIT_SUCCESS;
    }
    It sends first packet (green) and then it hangs and I get no response from the program.
    Where is my mistake?

  2. #2
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Check fprintf documentation.
    Don't assume what the function does. RTFM.

  3. #3
    Registered User
    Join Date
    May 2011
    Posts
    68
    I've read some articles, but didn't find something controversial in my code. That's the reason i came for help.
    Otherwise why would i?

  4. #4
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    Code:
        //till now everything ok
         fprintf( portfp, ini_val[pointer].data);  
        while(pointer<packet)
         {
              //get char from com port
              chr = fgetc(portfp);
    I'm not quite sure what the packet is really there. Is it global variable? As far as ini_val[pointer].data is a string then there is no problem with the fprintf until that stage. Clearly it seems like the while hasn' t got a porper exit condition right and ending up in an infinite loop.

    ssharish
    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

  5. #5
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    fprintf(3): formatted output conversion - Linux man page
    If you still don't get it, back to hello world!
    Even if ini_val[pointer].data is C string, it's very poor practice to do so.
    search format string attack.

  6. #6
    Registered User
    Join Date
    May 2011
    Posts
    68
    Well i've got it working:

    Code:
    unsigned char chr;
        //pointer to file    
         FILE* portfp ; 
         //set system to connect to com port
         system(comsettings); 
         
         //open port for write-read mode
          portfp = fopen(config.port, "wb+" ); //r+
         //send first packet to com port 
         fprintf(portfp, ini_val[pointer].data);
         fclose(portfp);
         //open port for read
         portfp = fopen(config.port, "rb" );
        // portfp = fopen(config.port, "rb" );
         //chr = 's';
          printf("[%c]\n",chr);
         while(pointer<packet) //(chr = fgetc(portfp)) != 'a'
         {
            chr = fgetc(portfp);
             printf("[%c]\n",chr);
            if(chr=='S')
            {
        
                pointer++;
                fclose(portfp);
                portfp = fopen(config.port, "wb+" );
                fprintf(portfp, ini_val[pointer].data);
                fclose(portfp);
                portfp = fopen(config.port, "rb" );        
            } 
            if(chr=='F')
            {
               append_logfile("FAIL");
               exit(0);       
            }                   
          }
         append_logfile("SUCCESS");
         fclose(portfp); 
         
         system("PAUSE");
         return EXIT_SUCCESS;
    But i don't like it. Please help me to optimize the code.

  7. #7
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    What don't you like about your program? You probably should provide a complete program if you want assistance optimizing your program.

    Relying on the system to configure your serial port can cause problems, you probably should use your operating system API calls to initialize the port. Opening and closing the port to switch between read and write should not be necessary, just open the port for read/write.

    Jim

  8. #8
    Registered User
    Join Date
    May 2011
    Posts
    68
    Opening and closing the port to switch between read and write should not be necessary, just open the port for read/write.
    That's the problem! When i open the port for read/write it stops and i can't get any respons. I don't like to close - open - close the port but only this way it works.
    Actually the programm communicates with controller, it sends three data packets , gets response and writes
    "success" in log file. But i have to set delay 100ms after each packet otherwise pc side misses data.
    All settings like port, baud rate, data to send , packets, and so on - user defined and located in ini file.
    Last edited by john7; 05-26-2011 at 03:55 PM.

  9. #9
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    It appears that you are on Windows, Windows has API calls to open and control the serial port, and using the buffered input and output functions is usually not advised when dealing with the serial port. You may want to take a look at this link for Windows serial port communication.

    Jim

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by jimblumberg View Post
    It appears that you are on Windows, Windows has API calls to open and control the serial port, and using the buffered input and output functions is usually not advised when dealing with the serial port. You may want to take a look at this link for Windows serial port communication.

    Jim
    Yep... trusty old CreateFile(), ReadFile() and WriteFile()... still the best way to go.

  11. #11
    Registered User
    Join Date
    May 2011
    Posts
    68
    Yep... trusty old CreateFile(), ReadFile() and WriteFile()... still the best way to go.
    Thank you guys. I'll try this approach.One more thing, my application runs on Win 98 - will it work on such system?
    Last edited by john7; 05-26-2011 at 11:02 PM.

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by john7 View Post
    Thank you guys. I'll try this approach.One more thing, my application runs on Win 98 - will it work on such system?
    Yeah... Win98 had the Windows API functions you need... and, since they are unchanged in modern systems updating your OS should cause no problems.

    ( Forgive my amazement but I really didn't think there are any Win98 systems left... Most everyone is on XP or newer...)

  13. #13
    Registered User
    Join Date
    May 2011
    Posts
    68
    ( Forgive my amazement but I really didn't think there are any Win98 systems left... Most everyone is on XP or newer...)
    It came by surprise to me too! On XP I'd did it in a blink of eye with C#.

  14. #14
    Registered User
    Join Date
    May 2011
    Posts
    68
    Well..This way it works pretty well. But...
    Code:
      DWORD dwBytesRead = 0;
       n=sizeof(ini_val[pointer].data);
       if(!WriteFile(hSerial, ini_val[pointer].data, n, &dwBytesRead, NULL))
       {
          printf("Error sending file.");
       }
    I get on terminal: some_data <00><00><00> <00><00><00> <00><00><00> <00><00><00>
    where some_data is my actual data and after it - trailing zeros. How can i get rid of trailing zeros.

  15. #15
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by john7 View Post
    Well..This way it works pretty well. But...
    Code:
      DWORD dwBytesRead = 0;
       n=sizeof(ini_val[pointer].data);
       if(!WriteFile(hSerial, ini_val[pointer].data, n, &dwBytesRead, NULL))
       {
          printf("Error sending file.");
       }
    I get on terminal: some_data <00><00><00> <00><00><00> <00><00><00> <00><00><00>
    where some_data is my actual data and after it - trailing zeros. How can i get rid of trailing zeros.
    Try using strlen() instead of sizeof() There's no reason to send the whole buffer if it's only half full...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reading and writing-serial port.
    By xenanovich in forum Networking/Device Communication
    Replies: 4
    Last Post: 05-31-2010, 10:39 PM
  2. Writing data to serial port
    By HAssan in forum C Programming
    Replies: 4
    Last Post: 10-16-2006, 12:07 PM
  3. Reading and writing to a serial port
    By SwarfEye in forum C Programming
    Replies: 2
    Last Post: 08-18-2006, 12:28 AM
  4. Serial port reading
    By gargamel in forum C# Programming
    Replies: 1
    Last Post: 05-18-2005, 08:19 PM
  5. serial port, reading from
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 06-01-2002, 09:37 AM