樹莓派串列埠/RS485通訊
樹莓派原生串列埠預設用於控制檯輸出,如果想在自己程式裡使用需要先關閉系統佔用此串列埠。
方法為rasp-config 裡配置,或直接修改/boot/cmdline.txt
#dwc_otg.lpm_enable=0 console=tty1 console=serial0,115200 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwai
dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwai
修改後就會多出一個串列埠裝置檔案/dev/ttyAMA0, 可以用命令stty -F /dev/ttyAMA0 9600設定串列埠引數等
可以安裝命令列下除錯軟體minicom進行串列埠設定及資料收發
sudo apt-get install minicom
如果裝了桌面系統就更多圖形化除錯工具瞭如cutecom
系統自帶的串列埠是TTL電平,如果要和RS485裝置通訊,需要接一塊485轉換晶片,現成的可以直接插在板子上用的見連結
可以買空板自己買元件焊接或買焊好現成的。板子上的晶片為ADM2587 ,晶片級電源和訊號都隔離的485晶片,成本不低,但對於電機等干擾大及走室外的對安全要求高的建議用隔離的。以免系統不穩定或燒壞主機板
也可以直接用USB轉485小模組,適合於除錯等不是24小時用的場合。USB經常不穩定,同時模組也沒有做訊號隔離
接上去不用裝驅動,自動會多出一個串列埠裝置檔案 /dev/ttyUSB0
用法和程式設計與前文一樣
由於最兩款模組都自帶收發控制自動切換,如果不用改程式控制一個DI/RI引腳,當然如果波特率很高,最好還是手動控制。GPIO的控制可以使用wringpi 庫,同時串列埠程式也可以使用wringpi 這個庫來寫
各種語言的串列埠通訊:
C語言,使用wringpi庫,呼叫 LINUX api的網上大量程式碼就不介紹了
#include <wiringSerial.h>
int main(void)
{
int fd;
if((fd = serialOpen ("/dev/ttyAMA0",9600))<0)
{
printf("serial err\n");
}
while(1)
{
UartBuff[0]=serialGetchar(fd);
if(UartBuff[0]=='a')
{
serialPutchar(fd,UartBuff[0]);
}
sleep(0.5);
}
return EXIT_SUCCESS;
}
PYTHON 安裝pyserial 模組
>>> ser = serial.Serial('/dev/ttyS1', 19200, timeout=1) >>> x = ser.read() # read one byte >>> s = ser.read(10) # read up to ten bytes (timeout) >>> line = ser.readline() # read a '\n' terminated line >>> ser.close()
shell:
echo "123" > /dev/ttyAMA0
cat /dev/ttyAMA0
PHP: 安裝擴充套件
<?php
use PHPMake\SerialPort;
// $device = 'COM4'; // on Windows
$device = '/dev/ttyUSB0'; // on Linux
/*
* create new instance
*/
$port = new SerialPort();
try {
/*
* open the port
*/
$port->open($device);
/*
* configure baud rate
*
* you can specify baud rate as integer,
* or other class constants like SerialPort::BAUD_RATE_*
*/
$port->setBaudRate(SerialPort::BAUD_RATE_9600);
/*
* configure flow control
*
* any other options are below.
* SerialPort::FLOW_CONTROL_SOFT is software flow control.
* SerialPort::FLOW_CONTROL_HARD is hardware flow control.
*/
$port->setFlowControl(SerialPort::FLOW_CONTROL_NONE);
/*
* configure canonical mode
*
* canonical mode is for text-based communication.
* non-canonical mode is binary-safe.
* more detail information about VMIN and VTIME,
* see http://www.unixwiz.net/techtips/termios-vmin-vtime.html
*/
$port->setCanonical(false)
->setVTime(1)->setVMin(0);
/*
* read data from port.
* you can get size of actual read data with strlen($data) .
*/
$data = $port->read(256);
/*
* send data.
*/
$port->write($data);
} catch (Exception $e) {
print $e->getMessage() . PHP_EOL;
}
if ($port->isOpen()) $port->close();