在使用Arduino MEGA 2560 R3进行RS485通信时,您需要使用RS485转换模块将Arduino的TTL信号转换为RS485的差分信号。通常,为了实现完整的双向通信,需要在每个通信节点上安装一个RS485转换模块。所以,如果您有两个设备需要互相通信(例如,一个Arduino和一个RS485设备),每个设备都需要一个RS485转换模块。以下是连接示意:
import serial
import time
# 设置串口
ser = serial.Serial('COM3', 9600, timeout=1) # 根据具体的COM端口设置
try:
while True:
command = input("Enter ON/OFF to control the light: ").strip()
if command in ["ON", "OFF"]:
ser.write((command + '\n').encode()) # 发送命令
time.sleep(1)
else:
print("Invalid command. Please use ON or OFF.")
except KeyboardInterrupt:
ser.close()
print("Program terminated.")
import serial
import time
# 设置串口配置
ser = serial.Serial('COM3', 9600) # 请根据实际情况更改 COM 端口
try:
while True:
command = input("Enter ON/OFF to control the light: ").strip()
if command in ["ON", "OFF"]:
ser.write((command + '\n').encode()) # 发送命令
print("Command sent:", command)
else:
print("Invalid command. Please type ON or OFF.")
time.sleep(1)
except KeyboardInterrupt:
ser.close()
print("Connection closed.")