Serial Communication Script

Hello.

I have a device that has a custom protocol and it works with RS485. For now I am testing using a modbus device but im trying to send commands to the device then read the response. I am unable to find a way to send my serial command to the device. Here is my script:
#!/bin/bash

RS485_PORT=“/dev/ttyS1”
BAUD_RATE=9600
DATA_BITS=8
STOP_BITS=1
PARITY=“none”
TIMEOUT=5

stty -F $RS485_PORT $BAUD_RATE cs$DATA_BITS -cstopb -parenb -icanon -iexten -echo

send_byte() {
local byte=$1
printf “\x$(printf ‘%x’ $byte)” >> $RS485_PORT
}

MODBUS_REQUEST=“01 06 01 90 00 03 49 35”

echo “Sending Modbus request…”
for byte in $MODBUS_REQUEST; do
send_byte “0x$byte”
done

sleep 1

echo “Reading response from Modbus device…”
MODBUS_RESPONSE=$(dd if=$RS485_PORT bs=1 count=256 2>/dev/null | xxd -p -c 256)

if [ -n “$MODBUS_RESPONSE” ]; then
echo “Received Modbus response: $MODBUS_RESPONSE”
else
echo “No response received from Modbus device.”
fi

I know the MODBUS_RESPONSE command works because I tested that separately, but for the life of me I can’t send anything.

I managed to get it working. If anyone else is having this issue the solution was to leave the stty configuration and send a request using:
slave_address=01

function_code=03

start_register=0x0191

num_registers=0x0001

request=“${slave_address}$(printf “%02X” $function_code)$(printf “%04X” $start_register)$(printf “%04X” $num_registers)”

crc=$(crc16 “$request”)

request_with_crc=“$request$crc”

request_bytes=$(echo “$request_with_crc” | sed ‘s/…/\x&/g’)

echo -n -e “$request_bytes” > /dev/ttyS1

The crc16 is just a normal check sum function

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.