You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派5基于.NET实现SPI通信的故障排查求助

树莓派5上.NET SPI通信问题求助

.NET 4.8阶段问题

在树莓派5上使用Visual Studio 2022/.NET 4.8+C#开发SPI通信程序,通过Mono运行时,SPI始终无时钟信号(持续为0V)。查阅微软文档得知需调用SpiDevice.FromIdAsync()切换GPIO引脚功能,但无法确定BusId的正确取值,输入任何内容都会触发IntelliSense报错。已安装对应NuGet包并引入using Windows.Devices.SPI。

原.NET 4.8代码:

// Use chip select line CS0

var settings = new SpiConnectionSettings(0);
String bus;
object spi_bus0 = null;
SpiDevice device = SpiDevice.FromIdAsync(spi_bus0, settings);

// Set clock to 10M
settings.ClockFrequency = 500000;
//....

切换到.NET 6后的问题

听从建议更换为.NET 6后,出现两类错误:

  • System.IO.IOException: Error 22. "Can not set SPI mode to Mode0"
  • System.IO.IOException: Error 2. Can not open SPI device file '/dev/spidev1.0'

检查树莓派系统/dev目录,仅存在spidev0.1和spidev10,未找到spidev1.0。但本人的Python版本SPI代码可正常运行。

Python正常运行代码:

import spidev
import os
import sys
import termios
import pygame  
spiPort0 = spidev.SpiDev()
spiPort0.open(0,0)
spiPort0.max_speed_hz = 100000
screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)

def spiSendRecvOneByte(spiPort, sendByte):
    sendByteArray = [sendByte]
    recvByteArray = spiPort.xfer(sendByteArray)    
    return recvByteArray

def repeatSendOneByte(spiPort, sendByte,    
    print('\nBegin repeatSendByte(),....')
    #for event in pygame.event.get():
     # if event.type == pygame.KEYDOWN:
      #  if event.key == pygame.K_q:
       #  sys.exit()
    for i in range(repeatCount):
        spiSendRecvOneByte(spiPort, sendByte)
        for event in pygame.event.get():
         if event.type == pygame.KEYDOWN:
          if event.key == pygame.K_q:
           sys.exit()

当前.NET 6代码:

using System.Device.Gpio;
using System.Device.Spi;
namespace Spi
{
    public class Pmc1 
    {
        static void Main(string[] args)
        {
            SpiDevice spi = SpiDevice.Create(new SpiConnectionSettings(0)); 
            spi.WriteByte(0x42);
            var incoming = spi.ReadByte();
            //var settings = new SpiConnectionSettings(0);
            //spi.ClockFrequency = 50000;
        }
    }
}

运行报错信息:

root@raspberrypi:/home/pi/SPI1# dotnet run
Unhandled exception. System.IO.IOException: Error 2. Can not open SPI device file '/dev/spidev1.0'.
   at System.Device.Spi.UnixSpiDevice.Initialize()
   at System.Device.Spi.UnixSpiDevice.WriteByte(Byte value)
   at Spi.Pmc1.Main(String[] args) in /home/pi    /SPI1/Program.cs:line 12
root@raspberrypi:/home/pi/SPI1# nano Program.cs
root@raspberrypi:/home/pi/SPI1# dotnet run
Unhandled exception. System.IO.IOException: Error 22. Can not set SPI mode to Mode0.
   at System.Device.Spi.UnixSpiDevice.Initialize()
   at System.Device.Spi.UnixSpiDevice.WriteByte(Byte value)
   at Spi.Pmc1.Main(String[].... 

恳请有相关经验的开发者提供解决方案,万分感谢!

内容的提问来源于stack exchange,提问作者Paul Clements

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 15:34:52