will this work? just a quick test needed

This is a discussion on will this work? just a quick test needed within the C Programming forums, part of the General Programming Boards category; i made this code to log an input from the serial port (COM2) and store it in a buffer. the ...

  1. #1
    Registered User
    Join Date
    Jun 2005
    Posts
    108

    will this work? just a quick test needed

    i made this code to log an input from the serial port (COM2) and store it in a buffer.

    the problem is that while it compiles fine, i have to take and test it 50km away in a different office and wanted to know if it works fine before i use it? itll be a pain to bring it back to debug.

    could anyone try and compile it and if they have a serial device, test it to tell me if it works ( i dont have a serial device here)?

    you help would be very much appreciated.

    Code:
    #include <windows.h>
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    
    {
    
    {
       DCB dcb;
       HANDLE hSerial;
       BOOL fSuccess;
       char *pcCommPort = "COM2";  //Set at com 2 for moment
    
       hSerial = CreateFile( pcCommPort,
                        GENERIC_READ | GENERIC_WRITE,
                        0,    // must be opened with exclusive-access
                        NULL, // no security attributes
                        OPEN_EXISTING, // must use OPEN_EXISTING
                        0,    // not overlapped I/O
                        NULL  // hTemplate must be NULL for comm devices
                        );
    
       if (hSerial == INVALID_HANDLE_VALUE) 
       {
           // Handle the error.
           printf ("CreateFile failed with error %d.\n", GetLastError());
           return (1);
       }
    
       // Build on the current configuration, and skip setting the size
       // of the input and output buffers with SetupComm.
    
       fSuccess = GetCommState(hSerial, &dcb);
    
       if (!fSuccess) 
       {
          // Handle the error.
          printf ("GetCommState failed with error %d.\n", GetLastError());
          return (2);
       }
    
       // Fill in DCB: 9,600 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(hSerial, &dcb);
    
       if (!fSuccess) 
       {
          // Handle the error.
          printf ("SetCommState failed with error %d.\n", GetLastError());
          return (3);
       }
    
       printf ("Serial port %s successfully reconfigured.\n", pcCommPort);
    }
    
    HANDLE hSerial;
    char szBuff[250 + 1] = {0};
    DWORD dwBytesRead = 0;
    if(!ReadFile(hSerial, szBuff, 250, &dwBytesRead, NULL)){
    
    char lastError[1024];
    FormatMessage(
    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL,
    GetLastError(),
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
    lastError,
    1024,
    NULL);
    printf("\nno bytes read!!\n\n");
    
    }else{printf("bytes have been read!!\n\n");
          printf("contents of buffer: %s\n\n", szBuff);
    
    }
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Well for starters, pay attention to your compiler. It has warnings for a reason. Next, you have an ugly style of programming with those extra braces in there. What ever happened to just declaring your variables at the top of the program? Oh, and your indentation is horrible. Here's a cleaned up version:
    Code:
    #include <windows.h>
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
       DCB dcb;
       HANDLE hSerial;
       BOOL fSuccess;
       char *pcCommPort = "COM2";  //Set at com 2 for moment
       HANDLE hSerial;
       char szBuff[250 + 1] = {0};  // What's wrong with just 251?
       DWORD dwBytesRead = 0;
       char lastError[1024];
    
       hSerial = CreateFile( pcCommPort,
          GENERIC_READ | GENERIC_WRITE,
          0,    // must be opened with exclusive-access
          NULL, // no security attributes
          OPEN_EXISTING, // must use OPEN_EXISTING
          0,    // not overlapped I/O
          NULL  // hTemplate must be NULL for comm devices
       );
    
       if (hSerial == INVALID_HANDLE_VALUE) 
       {
          // Handle the error.
          printf ("CreateFile failed with error %d.\n", GetLastError());
          return (1);
       }
    
       // Build on the current configuration, and skip setting the size
       // of the input and output buffers with SetupComm.
    
       fSuccess = GetCommState(hSerial, &dcb);
    
       if (!fSuccess) 
       {
          // Handle the error.
          printf ("GetCommState failed with error %d.\n", GetLastError());
          return (2);
       }
    
       // Fill in DCB: 9,600 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(hSerial, &dcb);
    
       if (!fSuccess) 
       {
          // Handle the error.
          printf ("SetCommState failed with error %d.\n", GetLastError());
          return (3);
       }
    
       printf ("Serial port %s successfully reconfigured.\n", pcCommPort);
    
       if(!ReadFile(hSerial, szBuff, 250, &dwBytesRead, NULL))
       {
          FormatMessage(
             FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
             NULL,
             GetLastError(),
             MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
             lastError,
             1024,
             NULL
          );
    
          printf("\nno bytes read!!\n\n");
       }
       else
       {
          printf("bytes have been read!!\n\n");
          printf("contents of buffer: %s\n\n", szBuff);
       }
    
       return 0;
    }
    What I suspect your question really was is: "Hey, I found this code some place and hope it does what I need it to. Does it?" Because I wouldn't lay claim to it. At any rate, I cleaned it up, some one else can play with it. (There's more you can do to make this look / be better, but I'll leave that to you or whoever else is bored.)


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    108
    Quote Originally Posted by quzah
    Well for starters, pay attention to your compiler. It has warnings for a reason. Next, you have an ugly style of programming with those extra braces in there. What ever happened to just declaring your variables at the top of the program? Oh, and your indentation is horrible.
    if i wanted clean and astheticly pleasing products, id have become an interior designer.

    Quote Originally Posted by quzah
    What I suspect your question really was is: "Hey, I found this code some place and hope it does what I need it to. Does it?" Because I wouldn't lay claim to it.
    i got the code from msdn and other websites and changed it to suit me. is there a problem with that? i suspect you werent born a computer geek so you must have started off somewhere.

    Quote Originally Posted by quzah
    At any rate, I cleaned it up, some one else can play with it. (There's more you can do to make this look / be better, but I'll leave that to you or whoever else is bored.

    i could have put my code through a C beautifier too, you didnt help or do much at all.........

    in future, if you dont like a post, dont bother reading or replying to it. (just a suggestion)

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    if i wanted clean and astheticly pleasing products, id have become an interior designer.
    Good idea. Let's make all of our code look like ........ so no one will want to read it. Job security.
    i could have put my code through a C beautifier too, you didnt help or do much at all.........
    While you're pondering that, ponder listening to your compiler.
    in future, if you dont like a post, dont bother reading or replying to it. (just a suggestion)
    In the future, don't post code that looks like someone typed it with their nose.
    [edit]
    Oh, and let's get this clear: I didn't clean it up for your sake. If you want to read ugly code, go ahead. I cleaned it up for the next person who takes the time to look over your code. It's a kindness. I figured my eyes were already bleeding from it, why should I make some one else suffer the same fate?
    [/edit]


    Quzah.
    Last edited by quzah; 07-07-2005 at 05:11 AM.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    108
    Quote Originally Posted by quzah
    In the future, don't post code that looks like someone typed it with their nose

    Quzah.

    who the hell died and made you moderator!?

    so if you dont post good looking code, you cant post at all?

    my ego wont extend to replying to everything you say from now......as i dont want you to look any more foolish, you are doing a good job of it yourself...

  6. #6
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,812
    You have to look at quzah's posts with the view of learning something and with a sense of humor. What he is saying in his quzahness is that it will make your life and anyone elses life who looks at your code alot better if you indent and use a good style so just relax and take what he says with a grain of salt he is here to help.
    Woop?

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    No one made me moderator. However, I have been here longer than 90% of them, and I'll still be here when 90% of them are gone. I've been here for years, looking at ugly ass code that people dump here hoping some one will do their work for them, debug their code for them, and generally just be thoughtless.

    You want us to debug some code. Fine. You want us to pull out a serial device for you and test your code for your job, or your school or whatever. Fine. But did you ever stop to consider the fact that you're not the only one having to actually read your ugly ........ing code? Nah, I didn't think so.

    I mean seriously, why make what you're requesting any easier for anyone? After all, what do you care? You just want someone to do your ........ for you. ........'m if they don't like how it looks.

    Yeah, I'm the idiot.


    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,851
    > if i wanted clean and astheticly pleasing products, id have become an interior designer.
    Well-formatted code is one of those signs which tells you whether the programmer is actually any good. You can simply eliminate a whole raft of bug types by decent formatting, and quickly see that its doing the right thing.
    Poorly indented rubbish like you posted is much to hard to visually inspect and as a result, all of the people who might otherwise help you simply skip onto other posts.

    Scale that up to several thousand lines in any commercial operation, and if you don't get fired, you'll get laughed at.

    > char szBuff[250 + 1] = {0}; // What's wrong with just 251?
    Probably that they used the same magic number (250) later on in the code.
    A simple #define BUFFERSIZE 250
    would sure improve things.
    As would a sizeof(lastError) to replace the 1024 in the FormatMessage call

    > char *pcCommPort = "COM2"; //Set at com 2 for moment
    Yeah, and you get to your other machine and it only has COM1

    Consider
    Code:
    int main(int argc, char *argv[]) {
      if ( argc > 1 ) {
        pcCommPort = argv[1];
      } else {
        pcCommPort = "COM2"; 
      }
    At least then you can choose a com port on the command line.
    Consider other stuff like baud rate as being suitable for parameterisation.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    108
    thanks salem,

    ill try that. thats all i was looking for. i dont want someone to write the code for me. just a little tip.

    oh, and ive only been coding for 16 days. i didnt know C before that so i hope everyone takes it easy with me from now on

  10. #10
    Registered User
    Join Date
    Jun 2005
    Posts
    108
    ok guys, i have this right now. and it still doesnt work!

    p.s. i ran it through a beautifier, hope you like it!!

    Code:
    #include <windows.h>
    #include <stdio.h>
    #include <string.h>
    
    int main( int argc, char *argv [] )
    {
    	char character;
        char *pcCommPort;
    
        if (argc > 1)
            {
            pcCommPort = argv[1];
            }
        else
            {
            pcCommPort = "COM2";
            }
    
        DCB dcb;
        HANDLE hSerial;
        BOOL fSuccess;
        //   char *pcCommPort = "COM2";  //Set at com 2 for moment
        char szBuff[250 + 1] = { 0 }; // What's wrong with just 251?
        DWORD dwBytesRead = 0;
        char string[BUFSIZ];
    
        hSerial = CreateFile(pcCommPort, GENERIC_READ |GENERIC_WRITE, 0, // must be opened with exclusive-access
                             NULL,                                       // no security attributes
                             OPEN_EXISTING,                              // must use OPEN_EXISTING
                             0,                                          // not overlapped I/O
                             NULL                                        // hTemplate must be NULL for comm devices
    												);
    
        if (hSerial == INVALID_HANDLE_VALUE)
            {
            // Handle the error.
            printf("CreateFile failed with error %d.\n", GetLastError());
            return (1);
            }
    
        // Build on the current configuration, and skip setting the size
        // of the input and output buffers with SetupComm.
    
        fSuccess = GetCommState(hSerial, &dcb);
    
        if (!fSuccess)
            {
            // Handle the error.
            printf("GetCommState failed with error %d.\n", GetLastError());
            return (2);
            }
    
        // Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit.
    
           dcb.BaudRate = CBR_57600;     // 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(hSerial, &dcb);
    
        if (!fSuccess)
            {
            printf("could not implement port settings");
            return (3);
            }
    
        printf("Serial port %s successfully reconfigured.\n", pcCommPort);
    
    COMMTIMEOUTS timeouts={0};
    timeouts.ReadIntervalTimeout=1000;
    timeouts.ReadTotalTimeoutConstant=1000;
    timeouts.ReadTotalTimeoutMultiplier=10;
    timeouts.WriteTotalTimeoutConstant=50;
    timeouts.WriteTotalTimeoutMultiplier=10;
    if(!SetCommTimeouts(hSerial, &timeouts)){
    //error occureed. Inform user
    }
    
        //ReadFile(hSerial, szBuff, 250, &dwBytesRead, NULL);
    
     ReadFile(hSerial, szBuff, 250, &dwBytesRead, NULL);
            printf("\nthis many bytes have been read: %s\n\n", dwBytesRead);
            sprintf(string, szBuff);
    
        FILE *fp = fopen("bufferdata.txt", "a+b");
    
        {
    
        //*****************Writes contents of decoded final data to the appropriate hour file********
    
        fprintf(fp, "\n"); // write to a new line	
        fputs(string, fp);
        printf("String Written in file\n\n");
    
        //******************Closes the file, flushes all buffers and waits for next cycle*************************
    
        fclose(fp);
        fflush(NULL);
    
        printf("All processes successful\n\n");
    	printf("data obtained : %s", string);
    	scanf("%c", &character);
        }
    
        return 0;
    }
    Last edited by shoobsie; 07-07-2005 at 10:24 AM.

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,851
    Well your beautifier sucks as well.
    COMMTIMEOUTS is as badly indented as ever.

    And you need a C++ compiler to compile this code - what with all those mixed declarations and statements.

    And you didn't create a #define for that 250 I mentioned previously.

    > sprintf(string, szBuff);
    Readfile doesn't magically append a \0 for you.
    Trying to sprintf it doesn't magically append one either.

    Try something like
    strncpy( string, szBuff, dwBytesRead );
    string[dwBytesRead] = '\0';

    Perhaps calling it sz is abuse of the naming convention if it really isn't \0 terminated.
    Not that I agree at all with Hungarian notation - but that's another story.




    > and it still doesnt work!
    Really helpful - try being more specific.
    Does it compile?
    Does it run?
    How far does it run?
    Does it crash - if so, what error messages do you get.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  12. #12
    Registered User
    Join Date
    Jun 2005
    Posts
    108
    Quote Originally Posted by Salem
    Well your beautifier sucks as well.

    > and it still doesnt work!
    Really helpful - try being more specific.
    Does it compile?
    Does it run?
    How far does it run?
    Does it crash - if so, what error messages do you get.
    i cant do anything about the beautifier...........

    it compiles
    it runs
    doesnt crash
    runs fully
    produces file
    file is empty

    hope that helps

  13. #13
    Pursuing knowledge confuted's Avatar
    Join Date
    Jun 2002
    Posts
    1,916
    About your beautifier .... man invented the Tab key for a reason. It's right next to Q on your keyboard. Use it and a bit of common sense, rather than some program to indent your code for you.

    What is it reading into "string" from the file? For debugging purposes, try copying a hard coded string into "string" just before writing it to the file.
    Away.

  14. #14
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    file is empty
    Do you mean completely empty, as in zero bytes?
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  15. #15
    C maniac
    Join Date
    Aug 2004
    Location
    Cyberwarping to Middle Earth
    Posts
    154
    confuted,

    Don't use tabs. See that thing, wide and short, at the bottom of the keyboard, called the space bar? Use that four times. Second of all, how about someone using a danish or french keyboard? HOW ABOUT NOT USING A QWERTY KEYBOARD? Or, even better, how about that on my machine, tabs are between 1-128 spaces, depending on my application? How about that? Try this:

    - type '#include <stdio.h>'
    - type 'int main() {'
    - type four spaces, then 'return 0;'
    - type '}'

    Compile.
    Run.
    It looks better then that old, tabbed code, doesn't it? DOESN'T IT??

    KAWK

    P.S. A reminder: Don't use tabs

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My C++ test is COMING!!...
    By [Z-D] in forum C++ Programming
    Replies: 52
    Last Post: 12-01-2006, 08:02 PM
  2. undefined reference
    By 3saul in forum Linux Programming
    Replies: 12
    Last Post: 08-23-2006, 06:28 PM
  3. Replies: 4
    Last Post: 03-21-2006, 10:21 PM
  4. Taking a Programming Test and need help with something.
    By 1BadRbt in forum C++ Programming
    Replies: 2
    Last Post: 03-21-2006, 06:19 AM
  5. "break" - quick response needed
    By luke in forum C Programming
    Replies: 4
    Last Post: 04-23-2002, 09:57 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21