Thread: Reading from serial port inside a method yields different results than from main

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    23

    Reading from serial port inside a method yields different results than from main

    Hello,

    I am developing an application that reads data from a serial port (on Ubuntu), and below is the relevant code used.

    Code:
    int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
    fcntl(fd, F_SETFL, 0);
    int value[2];
    read(fd, value, 2);
    printf("%x %x", value[0], value[1];
    When I put this inside my main, it works just fine. However, if I put the exact same code inside a method, it will output weird data. I have no idea why that's so, if anyone has any guidance it would be greatly appreciated.

    Thanks

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    I can tell you that without a shadow of a doubt, the problem is not from putting the code into a function. It is from doing something else wrong, like returning the address of a variable that goes out of scope.

    To spot the exact error you made, we need to see the entire function as you had it, and how you call it from main.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  3. #3
    Registered User
    Join Date
    Nov 2007
    Posts
    23
    Stupid me. I was reading a different number of bytes inside the function (on the read() call), once I changed it I got the right result.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. serial port reading
    By pavan_85 in forum Linux Programming
    Replies: 1
    Last Post: 08-11-2010, 08:46 PM
  2. Read from serial port only works in main... ??
    By chris24300 in forum Linux Programming
    Replies: 6
    Last Post: 06-19-2009, 01:22 PM
  3. Serial port reading
    By gargamel in forum C# Programming
    Replies: 1
    Last Post: 05-18-2005, 08:19 PM
  4. Same seed for srand yields different results
    By codegirl in forum C++ Programming
    Replies: 3
    Last Post: 06-23-2003, 02:39 PM
  5. serial port, reading from
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 06-01-2002, 09:37 AM