串口还需要权限

写了个串口操作的程序,结果提示cannot open /dev/ttyS1: Permission denied

pi@NanoPi-NEO2:~$ ls /dev/ttyS* -l
crw------- 1 pi   tty     4, 64 Feb 13 16:11 /dev/ttyS0
crw-rw---- 1 root dialout 4, 65 Feb 12  2016 /dev/ttyS1
crw-rw---- 1 root dialout 4, 66 Feb 12  2016 /dev/ttyS2
crw-rw---- 1 root dialout 4, 67 Feb 12  2016 /dev/ttyS3

sudo cp /etc/udev/rules.d/50-mali.rules /etc/udev/rules.d/52-ttl.rules
sudo vi /etc/udev/rules.d/52-ttl.rules
KERNEL=="ttyS1", GROUP="pi", OWNER="pi"
sudo reboot now

pi@NanoPi-NEO2:~$ ls /dev/ttyS* -l
crw------- 1 pi   tty     4, 64 Feb 13  2020 /dev/ttyS0
crw-rw---- 1 pi   pi      4, 65 Feb 12  2016 /dev/ttyS1
crw-rw---- 1 root dialout 4, 66 Feb 12  2016 /dev/ttyS2
crw-rw---- 1 root dialout 4, 67 Feb 12  2016 /dev/ttyS3

另外mono串口还有一个bug,不能触发DataReceived事件,需要一个进程来观察BytesToRead

Thread spThread = new Thread(new ThreadStart(DataReceived));
spThread.Start();

object o = new object();
void DataReceived()
{
    while(sp!=null)
    {
        lock(o)
        {
            if (sp.IsOpen && sp.BytesToRead > 0)
                Sp_DataReceived();
        }
        Thread.Sleep(10);
    }
}
private void Sp_DataReceived()
{
    Thread.Sleep(100);
    string s = sp.ReadExisting();
    while ((s != null) && (s != ""))
    {
        msg("receive " + s);
        s = sp.ReadExisting();
    }
}

参考文献:
https://ubuntuqa.com/article/1982.html

标签: none

添加新评论