【问题标题】:Writing to linux tty (/dev/) files in c#在 C# 中写入 linux tty (/dev/) 文件
【发布时间】:2015-07-22 18:13:11
【问题描述】:

我需要我的程序执行一个在 Bash 中看起来像这样的命令: “回声 P1-12=175 > /dev/servoblaster”。如何在 Linux 上的 Mono/C# 中执行此操作?我写了以下课程:

public static class ServoBlasterPWM
{
    private static FileStream devFile;

    public static bool IsRunning
    {
        get;
        private set;
    }

    public static bool Initialize()
    {
        try
        {
            devFile = File.Open("/dev/servoblaster", FileMode.Open);
        }
        catch (Exception e)
        {
            Log.Error("Error while setting up port for Servo Blaster: " + e.Message);
            return false;
        }

        Log.Success("ServoBlaster is set up.");
        IsRunning = true;

        return true;
    }

    public static void SetPWMOutput(int pin, int valueSteps)
    {
        //byte[] bytes = Encoding.ASCII.GetBytes("P1-" + pin.ToString() + "=" + valueSteps.ToString());

        byte[] bytes = Encoding.ASCII.GetBytes("P1-12=175");
        devFile.Write(bytes, 0, bytes.Length);
        devFile.Flush();

        Console.WriteLine("Wrote to file");
    }

    public static void Shutdown()
    {
        devFile.Close();
        IsRunning = false;

        Log.Info("Servo Blaster has been shut down.");
    }
}

此代码不起作用。我也尝试了 StreamWriter 而不是 FileStream,但它崩溃了,异常说流不支持查找。我不知道该怎么做。请帮忙。

【问题讨论】:

标签: c# linux file mono tty


【解决方案1】:

尝试将字符串替换为数组代码:

byte[] bytes = ASCIIEncoding.UTF8.GetBytes("P1-12=175") ;

或:

byte[] bytes = ASCIIEncoding.Default.GetBytes("P1-12=175") ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多