How to set baud rate to 307200 on Linux?

后端 未结 6 2032
走了就别回头了
走了就别回头了 2020-11-28 10:36

Basically I\'m using the following code to set the baud rate of a serial port:

struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options,         


        
6条回答
  •  难免孤独
    2020-11-28 11:18

    Try the ioctl call - you can specify an arbitrary baud rate. That is,

    ioctl(serialFileDescriptor, IOSSIOSPEED, &baudRate);

    To open the serial port:

    // Open the serial like POSIX C
    serialFileDescriptor = open(
        "/dev/tty.usbserial-A6008cD3",
        O_RDWR |
        O_NOCTTY |
        O_NONBLOCK );
    
    // Block non-root users from using this port
    ioctl(serialFileDescriptor, TIOCEXCL);
    
    // Clear the O_NONBLOCK flag, so that read() will
    //   block and wait for data.
    fcntl(serialFileDescriptor, F_SETFL, 0);
    
    // Grab the options for the serial port
    tcgetattr(serialFileDescriptor, &options);
    
    // Setting raw-mode allows the use of tcsetattr() and ioctl()
    cfmakeraw(&options);
    
    // Specify any arbitrary baud rate
    ioctl(serialFileDescriptor, IOSSIOSPEED, &baudRate);
    

    To read from the serial port:

    // This selector will be called as another thread
    - (void)incomingTextUpdateThread: (NSThread *) parentThread {
        char byte_buffer[100]; // Buffer for holding incoming data
        int numBytes=1; // Number of bytes read during read
    
        // Create a pool so we can use regular Cocoa stuff.
        //   Child threads can't re-use the parent's autorelease pool
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        // This will loop until the serial port closes
        while(numBytes>0) {
            // read() blocks until data is read or the port is closed
            numBytes = read(serialFileDescriptor, byte_buffer, 100);
    
            // You would want to do something useful here
            NSLog([NSString stringWithCString:byte_buffer length:numBytes]);
        }
    }
    

    To write to the serial port:

    uint8_t val = 'A';
    write(serialFileDescriptor, val, 1);
    

    To list availble serial ports:

    io_object_t serialPort;
    io_iterator_t serialPortIterator;
    
    // Ask for all the serial ports
    IOServiceGetMatchingServices(
        kIOMasterPortDefault,
        IOServiceMatching(kIOSerialBSDServiceValue),
        &serialPortIterator);
    
    // Loop through all the serial ports
    while (serialPort = IOIteratorNext(serialPortIterator)) {
        // You want to do something useful here
        NSLog(
            (NSString*)IORegistryEntryCreateCFProperty(
                serialPort, CFSTR(kIOCalloutDeviceKey),
                kCFAllocatorDefault, 0));
        IOObjectRelease(serialPort);
    }
    
    IOObjectRelease(serialPortIterator);
    

提交回复
热议问题