How to do handshaking mechanism in serial communication

hello, I am new to rust, and I am trying to do handshaking in serial communication. so how can i do this,
i try to send RTS/CTS signals but i am unable to do.

use std::io::{self, Write, Read};
use std::thread::sleep;
use std::time::Duration;
use serialport::{DataBits, FlowControl, Parity, SerialPort, StopBits};

fn open_serial_port(port_name: &str, baud_rate: u32) -> Box {
serialport::new(port_name, baud_rate)
.flow_control(FlowControl::None) // Hardware flow control handled manually
.expect("Failed to open port")

fn main() -> io::Result<()> {
// Replace with the actual serial port names on your system
let sender_port_name = "/dev/ttyUSB0";
let receiver_port_name = "/dev/ttyUSB1";
let baud_rate = 9600;

 // Sender Code
 let mut sender_port = open_serial_port(sender_port_name, baud_rate);

 // Manually simulate CTS (Clear To Send) signal
 let mut cts_simulated = false;
 while !cts_simulated {
     // Simulate RTS (Request To Send) signal
     let _ = sender_port.write_request_to_send(true);
     //sleep(Duration::from_millis(100)); // Adjust the sleep duration as needed
     // Attempt to read a byte to check for CTS
     let mut buf = [0u8; 1];
     match buf) {
         Ok(_) => {
             println!("Sender: CTS received. Handshake successful.");
             cts_simulated = true;
         Err(_) => {
             println!(" CTS not received yet, continue looping");

 // Send "Hello, World!" to the receiver
 let data_to_send = b"Hello, World!";

println!("Sender: Data sent successfully.");

// Receiver Code
let mut receiver_port = open_serial_port(receiver_port_name, baud_rate);
// Manually simulate RTS (Request To Send) signal
let _ = receiver_port.write_request_to_send(true);
// Wait for data from the sender
let mut received_data = Vec::new();
receiver_port.read_to_end(&mut received_data)?;

println!("Receiver: Received data: {:?}", String::from_utf8_lossy(&received_data));



Can you elaborate on how you are doing this? It'd be useful if you can show some of the code you are using and explain how you've set up your serial device. It might be that one end isn't configured to send/receive RTS and CTS.

1 Like

i have updated with code

i am using usb to serial connector is is possible to perform handshaking with usb to serial connector because it have only 4 pins to 9 pins and for handshaking i need 9 to 9 connector

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.