Thank you for your response:
According to the datasheet of the MCP41010, the write operation for both bytes must last 16 clock cycles. Forcing each WriteSPI() to last 8 cyles is an attempt at making the whole write operation last 16 clock cycles. Here is the relevant extract from the datasheet:
"Executing any command is accomplished by setting CS low and then clocking-in a command byte followed by a data byte into the 16-bit shift register. The command is executed when CS is raised. Data is clocked in on the rising edge of clock and out the SO pin on the falling edge of the clock (see Figure 5-1). The device will track the number of clocks (rising edges) while CS is low and will abort all commands if the number of clocks is not a multiple of 16."
Also, it seems only one flag is available to use as you suggested; it is the Buffer Full flag (BF). The problem is it can't be used in the first WriteSPI() since the SSPBUF won't be full yet.
Your code does not work because you call WriteSPI() a second time, without checking if the first transaction has completed beforehand. The second transaction clobbers the first. You also de-assert CS (set to 1) immediately upon returning from WriteSPI(), long before the byte has finished transferring.
You are also confused about what kind of "clock cycles" that are referred to in the data sheet. It means that each SPI transaction must contains 16
SPI clock transitions. This has nothing to do with the CPU clock per se. A fixed CPU clock delay is not useful.
What you need to do is:
1. assert CS,
2: send one byte (8 bits) over SPI,
3: wait for it to finish,
4: send the second byte (8 bits) over SPI,
5: WAIT for it to finish!!,
6: de-assert CS. Done.
Sending two bytes means 16 SPI clocks, and that fills the datasheet requirement you are looking at. It doesn't matter how much time elapses, as long as there are exactly 16 SPI clock transitions.