avr - 使用USBASP编程器进行SPI通信

我正在尝试通过 USBASP 编程器将一些数据从 PC 发送到 ATmega328P 芯片。

它能够通过 SPI 传输最多 4 个字节。这 4 个字节可以在 USB Setup Packet 中设置(2 个字节用于 wValue,2 个字节用于 wIndex)。为了在 ATmega328P 中启用 SPI,我将 USBASP Reset 引脚连接到 SS。在 PC 端,我使用 libusb 发送 USB 设置数据包。

ATmega328P代码:

int main()
{
    char spiData = 0;

    // Enable SPI
    SPCR |= 1 << SPE;
    DDRB |= 1 << 4;

    // Main cycle
    while(1)
    {
        while(!(SPSR & (1 << SPIF))); // Wait for transmission end
        spiData = SPDR; // Read SPI Data Register
        // Do something with first byte

        while(!(SPSR & (1 << SPIF)));
        spiData = SPDR;
        // Do something with second byte

        while(!(SPSR & (1 << SPIF)));
        spiData = SPDR;
        // Do something with third byte

        while(!(SPSR & (1 << SPIF)));
        spiData = SPDR;
        // Do something with fourth byte
    }
    return 0;
}

PC 代码(C#):

static void Main(string[] args)
{
    // Find USBASP
    var device = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(0x16C0, 0x05DC));

    // Set Clock and RESET pin to enable SPI
    int bytesTrasferred;
    var usbSetupPacket = new UsbSetupPacket(0xC0, 1, 0, 0, 0);
    device.ControlTransfer(ref usbSetupPacket, null, 0, out bytesTrasferred);

    // Send Setup Packets
    while (Console.ReadKey(true).Key == ConsoleKey.Enter)
    {
        byte[] buffer = new byte[4];
        usbSetupPacket = new UsbSetupPacket(0xC0, 3, 200, 200, 0);
        device.ControlTransfer(ref usbSetupPacket, buffer, 4, out bytesTrasferred);
        Console.WriteLine("Done. Return result: [{0}, {1}, {2}, {3}]", buffer[0], buffer[1], buffer[2], buffer[3]);
    }

    // Disable SPI
    usbSetupPacket = new UsbSetupPacket(0xC0, 2, 0, 0, 0);
    device.ControlTransfer(ref usbSetupPacket, null, 0, out bytesTrasferred);

    // Free resources
    device.Close();
    UsbDevice.Exit();
}

USBASP -> ATmega328P SPI 通信运行良好,但似乎设置数据包的 wValuewIndex 字段中的数据已损坏到 USBASP,因为我得到了这个输出(虽然它应该是常量 - [0, 200, 0, 200]):

[0, 153, 0, 128]
[0, 136, 0, 128]
[1, 209, 1, 217]
[1, 128, 0, 145]
[1, 153, 0, 128]
[0, 145, 1, 209]
[1, 217, 1, 136]
[0, 209, 1, 209]
[1, 217, 1, 136]
so on...

我还在连接到 ATmega328P 的 LED 数字显示器上看到这些数字。

谁能解释一下?

附言出于编程目的,此 USBASP 运行良好。

最佳答案

但问题出在 SPI 中。我的 ATmega328P 默认设置为带有 1/8 分频器的 8MHz 内部时钟,因此它的 1MHz 频率对于正确的 SPI 通信来说太小了。我通过将 ATmega328P 设置为外部 16mHz 晶体来解决这个问题。

https://stackoverflow.com/questions/16615640/

相关文章:

erlang - 如何使用 PEM key 文件在 Erlang 中通过 SSH 连接

apache - 将模块加载到 Apache

c - 在 C 中实现 hmac sha1

amazon-s3 - S3 如何在上传时分配时间戳?

regex - 正则表达式 : How to find dashes between words

c# - 页脚按钮的 Gridview colspan

Django - Python help_text 作为可点击的图标

python - 制作包含负值的对数标度彩色图

windows-installer - MSI 中的 "installation script"是什

perl - utf8 "\xFF"未映射到 tokenizer.perl 第 44 行