晶体存取串行p

2024-04-16 19:31:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Crystal lang访问串行端口

我用python编写了以下代码。我想为一个pet项目编写等价的crystallang代码。在

import serial

def readSerData():

    s = ser.readline()
    if s:
        print(s)
        result = something(s) #do other stuff
        return result

if __name__ == '__main__':

    ser = serial.Serial("/dev/ttyUSB0", 9600)
    while True:
        data = readSerData()
        #do something with data

我找不到任何可以访问串行端口的库。在

在crystal lang中访问串行端口的正确方法是什么?在

提前谢谢。在


Tags: 项目端口代码langdataifserialresult
1条回答
网友
1楼 · 发布于 2024-04-16 19:31:57

更容易从多个部分回答这个问题,以便真正涵盖所有问题:

Q:如何访问linux/bsd上的串行端口?

A:以文件的形式打开它。在linux/bsd上,当一个设备被插入时,串行连接就被建立起来,然后被列在/dev/下(现在通常是/dev/ttyUSB0)。为了访问这个连接,你只需像打开普通文件一样打开它。有时这已经足够好了,可以开始与设备通信,因为现代硬件通常使用所有波特率和默认标志。在

Q:如何在linux/bsd上配置串行/tty设备?

A:在文件上设置termios标志。如果您确实需要配置连接来设置波特率、IXON/IXOFF等,您甚至可以在运行程序之前使用stty(如果可用的话)。要设置波特率,可以运行:stty -F /dev/ttyUSB0 9600。设置好后,你可以把它作为一个文件打开,然后开始使用它。在

如果您希望从应用程序配置设备,可以使用^{}从crystal生成stty。在下一个解决方案中,我可能会推荐这种方法。。在

Q:如何在不使用stty的情况下从crystal设置termios标志?

A:直接使用termios posix函数。 Crystal实际上为FileDescriptor句柄提供了一些常见的termios设置,比如^{},这意味着它已经有了最小的termios bindings。我们可以从现有的代码中获得灵感:

require "termios" # See above link for contents

#Open the file
serial_file = File.open("/dev/ttyACM0")
raise "Oh no, not a TTY" unless serial_file.tty?

# Fetch the unix FD. It's just a number.
fd = serial_file.fd

# Fetch the file's existing TTY flags
raise "Can't access TTY?" unless LibC.tcgetattr(fd, out mode) == 0

# `mode` now contains a termios struct. Let's enable, umm.. ISTRIP and IXON
mode.c_iflag |= (Termios::InputMode::ISTRIP | Termios::InputMode::IXON).value
# Let's turn off IXOFF too.
mode.c_iflag &= ~Termios::InputMode::IXOFF.value

# Unfun discovery: Termios doesn't have cfset[io]speed available
# Let's add them so changing baud isn't so difficult.
lib LibC
  fun cfsetispeed(termios_p : Termios*, speed : SpeedT) : Int
  fun cfsetospeed(termios_p : Termios*, speed : SpeedT) : Int
end

# Use the above funcs to set the ispeed and ospeed to your nominated baud rate.
LibC.cfsetispeed(pointerof(mode), Termios::BaudRate::B9600)
LibC.cfsetospeed(pointerof(mode), Termios::BaudRate::B9600)
# Write your changes to the FD.
LibC.tcsetattr(fd, Termios::LineControl::TCSANOW, pointerof(mode))

# Done! Your serial_file handle is ready to use.

要设置其他标志,请参考termios manual,或者我刚刚找到的这个漂亮的serial guide。在

问:有没有图书馆可以帮我做这些?

不:(.我看不出来,但如果有人能做到那就太好了。如果一个人有既得利益的话,制造一个这样的产品可能不太容易:)

相关问题 更多 >