swharden / FtdiSharp

A .NET library for interfacing FTDI USB controller ICs
https://www.nuget.org/packages/FtdiSharp/
MIT License
27 stars 5 forks source link

ReadWrite(): Sending tx.length bytes will be off by 1 #10

Open sdunc opened 2 days ago

sdunc commented 2 days ago

https://github.com/swharden/FtdiSharp/blob/20b3dbf50a740b9bc6995ca20a79dbba0614b47b/src/FtdiSharp/Protocols/SPI.cs#L170-L171

What FTDI calls LengthL and LengthH are more like indices. A length of 0 contains a single byte. A length of 65535 contains 65536 bytes. using tx.length directly will cause an extra byte of clock pulses to appear on spi bus.

From FT_000109 document:

image (19)

image

I believe replacing tx.length with tx.length - 1 in both lines will fix the issue.

best S

swharden commented 1 day ago

Hi @sdunc, thanks for the follow-up! I made the change suggested 21058cdd920745b16d9a2f10be091c843bf338c8 and am deploying FtdiSharp 0.1.1 to NuGet and it should be live in about 20 minutes.

If you give it a go, I'd love to hear if it worked as expected!

Thanks again Scott

sdunc commented 1 day ago

Hey Scott,

0.1.0, note the extra byte on the right. image

0.1.1, same source code. Correct number of bytes sent. image

One thing you may want to improve would be chip select performance. Your current approach:

    public void CsHigh()
    {
        // bit3:CS, bit2:MISO, bit1:MOSI, bit0:SCK
        byte[] bytes = new byte[]
        {
            0x80, // GPIO command for ADBUS
            0b00001000, // value
            0b00001011, // direction
        };

        if (!ClockIdlesLow)
            bytes[1] |= 0b00000001;

        for (int i = 0; i < 5; i++)
            FtdiDevice.Write(bytes);
    }

Calling FtdiDevice.Write() inside the loop incurs 5 transmission delays. The approach used in the application note also sends the CS high and low commands 5x, but they fill a single buffer with all those bytes and .Write() only once with all the bytes. This change results in much much greater chip select performance.

With this change, note the improvement in how fast CS gets pulled back high: image