我正在尝试通过 USBASP 编程器将一些数据从 PC 发送到 ATmega328P 芯片。
它能够通过 SPI 传输多达 4 个字节。这 4 个字节可以在 USB 设置包中设置(2 个字节用于wValue
和 2 个字节用于wIndex
)。要在 ATmega328P 中启用 SPI,我已将 USBASPReset
引脚连接到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;
}
电脑代码(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 通信运行良好,但似乎设置数据包中的数据wValue
和wIndex
字段已损坏到 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 数字显示屏上看到这些数字。
谁能解释一下?
PS 出于编程目的,此 USBASP 运行良好。