Showing posts with label SPI. Show all posts
Showing posts with label SPI. Show all posts

Monday, August 3, 2026

DAC on the same bus as DCO. Also, DCO nightmare...

As I'm preparing to put a 12bit DAC on the SPI bus shared with DCOs and the bit crusher, I had to make some changes to how to communicate with the DCO. 

 EDIT: I've written the code in a way that supports 3 bytes per DAC update so even 16bit DACs are supported in theory. For 12bit DACs, only two bytes are needed)

The DCO expected to receive three bytes with a 9us delay between sends and the CS line toggled only at the end of the last byte.

First I rewrote that, to accept single bytes. Then I changed the format so the first byte started with 1 and then had a fire bit command. The two last bits + 2 x 7 bits from the next made up the 16 bit frequency for example. That way, we can sync on the first byte instead, as it's the only one with a 1 as MSB.

Anyway, the bus can at best run at 4MHz when communicating with the DCO, or else each bit length becomes too short for the PIC16F. At 4MHz each bit is 0.25us long.

I want to run the DAC at 2ch * 48kHz = 96kHz. But if the DCO sends all its bytes in one go, it would take up too much time in a single period, preventing a stable DAC update frequency.

At the same time, I want to run the CV updater and DCO updates at 6kHz (well, ideally I wanted to update the CVs at 12kHz, but I can't seem to get a stable 192kHz interval (CV updating is split into 16 updates, 16 * 12kHz = 192kHz) so I think I have to settle for 96kHz. This fits well with the DCO which cannot be updated faster than 8kHz anyway, so 6kHz it is.

So, I came up with a system of 16 slots (96kHz/16 = 6kHz), each 1s/96000 or 10.4us long. The DAC can send its 3 bytes (with no delay between) in any slot, it would take slightly more than 6us. 

That leaves around 4us. Sending a single byte will take around 2us, so we can let any other peripheral send on the second half of the slot. Also, since DAC and DCO will be mutually exclusive (per channel), the DAC may send at the start and any other device (e.g. BC) in the second half. Also, by separating DCO frequency updates and DCO commands (sync, range etc) into separate slots, we can send both within a single 16slot cycle.

Anyway, I implemented this - and then the nightmare started.

The DCO had massive errors to the slope - every cycle overflowed, the saw was no longer a saw.

I spent almost two hole days debugging. Was it the protocol change, some previously untested code changes to the DCO or something in my controller code? 

Turns out, it's likely a problem with the MikroC compiler (again). When writing two chunks to the PIC internal FLASH rom, one with DAC values and one with DAC slopes, the values one got written to both positions! I am not sure if this started to happen now, but it would be weird if it has been that way for a long time.

The solution is to calculate the slope on the fly (it's simply a subtraction). But when I removed the code for writing the slope to FLASH, everything failed. So now I still calculate and write slopes during calibration, I just don't use it. 

I truly hate the MikroC compiler. I really need to port everything to MLabs.

In the process of figuring out what was going on, a few other things happened. First of all, one of the DCOs got stuck at a single frequency. Turns out, one of the SPI pins got pushed in/up through the board (cold solder joint probably). Then, another DCO simply didn't want to calibrate properly. It took a long time to realize that this only happens at the bottom end of the frequency spectre, around 40Hz and lower. At the moment, I think the DAC simply cannot supply a low enough voltage, so every cycle overshoots.

Then disaster struck. I put the DCO in the programmer backwards, sending +12V into one of the SPI  pins. The MCU still works, but SPI has stopped working so it's trash.

So right now I'm two DCOs short, and I have only one that can be calibrated down to the lowest frequency. Not sure what to do about that, but the others work down to around 40Hz which is good enough I guess. We'll see what the rest end up with.

Oh, and I managed to fix a long lasting bug - when changing to a lower frequency, the first cycle would end early because the previous interval's timer wasn't stopped. It seems to work fine now. 

BTW: I had another weird issue that I didn't get to the bottom of. One of the DCOs managed to reach all the way down to 4-5Hz, while the others only managed 8. I think 8 is right. Maybe the first one ran at half the expected speed (16Mhz instead of 32MHz)? 

BTW2: I first suspected that the overflowing waveform was caused by the interpolation between calibrated points being wrong. It did have something to it, the interpolation will be off by a few percent, bulging towards the end. But not as much as I saw. However, this lead me to try without any interpolation at all, just using the calibrated value for the start. That worked pretty well, it only sags by a few 10s of a volt at the end. Pretty interesting, by doubling the number of measured points we could maybe get away without the interpolation. 

BTW3: There is something strange at the startup of the DCO, when hammering the synth with midi, it feels like the DCO lags/hangs, before suddenly doing all the changes. This has not been investigated further.

Tuesday, July 26, 2022

Itsy bitsy Teensy trouble - with Slave SPI

This is another one of those posts mostly meant for myself.

I've been hitting my head against the wall for four days, trying to get Slave SPI working on a Teensy 4.0, with a Teensy 4.1 as the master.

I started out with the https://github.com/tonton81/SPISlave_T4 library (and https://forum.pjrc.com/threads/66389-SPISlave_T4) , but could not make it work, so I stripped it down to the minimum. After a while (after removing a while-loop from the ISR) I got some response. However, it was not stable and it seemed like it would only receive every second byte.

After a lot more troubleshooting I got it working on every transfer, but only if writing 0 to the TX buffer. Any other values would give different troubles.

In the end, it turned out to most likely be a combination of things - mixing up MOSI and MISO pins as well as wrong impedance settings on the pins. Removing and attaching probes to the pins also made stuff fail.

Anyway, next time I would check the following:

- Make sure CFG1 is set to full duplex (00 or 11) 

- Check crossed vs straight connections between MISO and MOSI, matching CFG1

- Connect/disconnect logic probes on MISO/MOSI (works when bytes go missing)

- Make sure master deasserts PCS between frames, I wrote 16 bits without rising the PCS (or rather, rising for a too short time) between blocks of 8 bits when frame size was 8 bit.

- Make sure master speed is > 1MHz

I have yet to find a completely stable solution and I am worried that connecting multiple slaves to the same master may not work as intended. 

Learned

Anyway, here are some of the things I learned:

- The minimum SPI speed on the Teensy is 1MHz (without doing special stuff)

- To set SPI in slave mode: set bit 1 in CFG1 to 0 and update Clock gating register for the appropriate LPSPI, for example CCM_CCGR1 |= (3UL << 6); (lpspi4_clk_enable)

- When CFG1 bits 25-24 are 00, MOSI on the master connects to MISO on the slave and vice versa.

- When CFG1 bits 25-24 are 11, MOSI on the master connects to MOSI on the slave (and MISO to MISO).

- When communicating between two Teensy 4.x, the pin impedance must be changed on both slave and master. For example: 

IOMUXC_SW_PAD_CTL_PAD_GPIO_B0_01 = IOMUXC_PAD_DSE(3) | IOMUXC_PAD_SPEED(3) | IOMUXC_PAD_PKE;

- Even when changing the impedance, I needed to experiment with connecting/disconnecting the logic probes.

- TX buffer empty flag is set immediately after the last TXFIFO byte is shifted out, at the same time an RX interrupt is triggered (if RXWATER is 0).

- The SPI documentation talks about different size descriptions:

    - Transfer - when sending data - Transfer complete IR is triggered when all data in TXFIFO has been sent (FIFO is empty)

    - Word - Up to 32bits, 0-padded if less than 32 bits received. FIFOs are 16 words long.

    - Frame - Frame complete IR is triggered when PCS (chip select) goes high (deasserts). A Frame may be from 8bits long, length must be divisible by 2 and may be longer than 32bits (span multiple words). If word length is reached, the frame is split across multiple words in the RXFIFO.

- TDF and RDF - Transmit and Receive Data flags are set by the system and reset by reading from/writing to the TX and RXFIFOs, not by clearing interrupt flags.

- The SPI slave example sets IER bit 1 which is Transmit Data Interrupt. It will be triggered when the number of bytes in the TXFIFO is less than TXWATER. With TXWATER 0 this will be triggered at the same time a byte is received. I don't understand why this is chosen instead of for example FCF.

- The SPI slave library, and also the more elaborate example at https://github.com/tonton81/SPI_MSTransfer_T4, uses a lot of looping and waiting inside the ISR, which cannot be a good way of doing things...

- With an 8bit frame and a single byte in the TX buffer, the following are set on RX: Frame completed, Word completed, RX data ready, TX data ready. RXFIFO in FSR is incremented. If another byte is received before a new byte is written to TX, we get a TX underrun.

Symptoms

Here are some of the symptoms I experienced:

- Missing or erroneous slave sends when anything but 0 was written to TDR - i suspect that we tried writing and reading from the same pins and that messed up stuff, though not entirely sure WHAT was going on.

- TX buffer underruns even if I wrote to the output buffer every time a byte was received

- Elements in the TX buffer disappeared (even if length was correct) as verified by logic probes. 

- When writing the same bytes over and over to TX, the same bytes disappeared every time.

- Swapping master and slave made DIFFERENT bytes disappear.

- Missing RX, some of the received bytes never ended up in the RXFIFO

- All receives worked when I only wrote 0 to TX buffer.

- It looked like I needed to receive 16bits and/or only every second byte was received.

- When unplugging either the MISO or MOSI cable, sends started working perfectly

- Removing probes sometimes made stuff work - but only after powercycling the Teensys.



Test code

My slave test code can be found at

https://github.com/xonik/teensy-spislave-test

Master code is

#include <SPI.h>

SPISettings settings(10000000, MSBFIRST, SPI_MODE0);


void setup() {

  IOMUXC_SW_PAD_CTL_PAD_GPIO_B0_01 = IOMUXC_PAD_DSE(7) | IOMUXC_PAD_SPEED(3) | IOMUXC_PAD_PKE; 

  IOMUXC_SW_PAD_CTL_PAD_GPIO_B0_02 = IOMUXC_PAD_DSE(7) | IOMUXC_PAD_SPEED(3) | IOMUXC_PAD_PKE; 

  IOMUXC_SW_PAD_CTL_PAD_GPIO_B0_03 = IOMUXC_PAD_DSE(7) | IOMUXC_PAD_SPEED(3) | IOMUXC_PAD_PKE; 

  IOMUXC_SW_PAD_CTL_PAD_GPIO_B0_00 = IOMUXC_PAD_DSE(7) | IOMUXC_PAD_SPEED(3) | IOMUXC_PAD_PKE; 


  Serial.begin(1000000);

  pinMode (10, OUTPUT);

  digitalWriteFast(10,HIGH);

  Serial.println("SPI Starting");


  SPI.begin();   

  SPI.beginTransaction(settings);  

}


void loop() {

  digitalWriteFast(1,HIGH);

  digitalWriteFast(1,LOW); 

  delay(500);


  digitalWriteFast(10,LOW);

  Serial.println(SPI.transfer(0xAA));

  digitalWriteFast(10,HIGH);  

}


Wednesday, July 6, 2022

Teensy 4.x SPI

I did some testing of the hardware SPI support yesterday, to try to get async send working.

I thought that async sends were not implemented since all posts were discussions about how hard it was to use DMA etc etc. Turns out I've misunderstood. 8bit-per-byte is fully supported using the callback version of SPI.transfer!  When saying that 16bit (and more) transfers were not supported, they mean that 16bits per byte (or sending strings of 16bit ints) is not supported.

I only discovered this after trying to understand what was done in the example from Garug in this post: https://forum.pjrc.com/threads/67247-Teensy-4-0-DMA-SPI/page2

I deleted everything special and it still worked. Here are some outputs:


My main loop output without any SPI sends running, to see what speed I can get without anything else interfering.



Normal "one byte per transfer", blocking SPI makes the main loop output grind to a halt

SPI transfer using callbacks. Main loop speed is almost the same as with no load :-D (Spi transfers 0x00 and 0xFF which is shown as the slow output on line 2



Changed to transferring 8bytes at a time, to measure the delay between transfers.


8 byte transfers but with changing speeds between 2 and 8MHz. There is not much overhead doing the switch.

Retriggering send from callback

This seems to work fine:


Moving the start/end transaction so that it only happens when we need a speed change saves us a little time between blocks:


We still get a 1.5uS "penalty" here, which amount to 96uS per 64 blocks sent. In this time period, it looks like the SPI actually blocks the main thread too. That's not good. I have to look for ways to increase the speed here, but we're using attachImmediate which supposedly is the fastest callback.

Things to look at:
- There is a lot to save by writing a custom version of

 bool SPIClass::transfer(const void *buf, void *retbuf, size_t count, EventResponderRef event_responder) {

(found on line 1199 in SPI.cpp), one that does not use an EventResponder callback and that skips a lot of the checking the library version does. 

The best thing would be to make a version that does not require an interrupt for every three bytes sent, which controls the chip select/sync pin by itself. 

Update:
I've managed to do async SPI with 24bit transfers and automatic CS switching. This probably means I can update all 4 channels of the DAC in one go, I just need to make it async. Since I was only sending 3 bytes, doing DMA transfers were costly and unnecessary.

As for Teensy 4.0 vs 4.1: The 4.1 has three CS pins connected to the default SPI port, meaning I can switch between them. 4.0 on the other hand has only one. BUT - If I can manage to turn OFF CS handling after writing to DAC, I can do DCO CS manually. I will only write one 24bit block to DCOs so I would have had to do config changes between sends anyway.

Also, I discovered that the Teensy 4.0 actually exposes all four SPI1 pins after all (MISO1 and CS1 as pin 0 and 1) so I can use any of the two ports for either slave or master functionality.

Update:

From top: SPI Clock, Data out, CS for fast moving data (50MHz), CS for slow data (4MHz, a few glitches that probably are just from the probes), Interrupt indication (yellow) and main loop indication (blue).

The image above shows that background SPI transfers are working as they should, with speed and CS switching. Main loop speed is 20MHz approx. 

Updating 4 DAC channels, including time spent in ISR, takes 3uS. Updating two DCOs take 13,7. In total, 61.7uS for 64 channels + 2 DCOs. 

The max update speed is thus 1 000 000 / 61.7 = 16.2kHz when the DAC bus runs at 50MHz. 

Reducing speed to 25MHz makes the total time 93,7uS and the throughput drops to 10.6kHz which is a bit too slow.

Moving the DCO updates to a separate bus would mean DAC transfers at 25MHz would take 80uS giving us a throughput of 12.5kHz. That would be sufficient. 

If we choose to upgrade to an 8 channel DAC running at 50MHz we would get a total of 53,7uS for a speed of 18.6kHz.

Monday, July 4, 2022

Teensy 4.x and communication

The voice controller card needs to communicate both with the master controller and with its peripherials.

Master controller should use the voice card as slave and needs a hardware SPI to do so properly. Hopefully, one master may control multiple voice cards simultaneously if we just buffer the SPI output.

The voice card controller needs to control these three:

The CV DAC

Currently, this is done in software, at 50MHz. This eats up a lot of clock cycles. Instead, we should look into using DMA backed SPI - that would let us send 24bit in the background without blocking the controller:

 https://forum.pjrc.com/threads/67247-Teensy-4-0-DMA-SPI

Update: 

Using SPI.transfer((void *)txBuffer, nullptr, 8, callbackHandlerFast); sends a whole buffer in the background and may be exactly what we need.

The DCOs

These are connected to the hardware SPI today, but runs at max 4MHz, which means moving them to software would block for even longer periods than the DACs. Not entirely sure what to do here, perhaps some timer based scheme, or perhaps we can change the SPI speed and use the same SPI as for DAC?

I should really look into SPI transactions for this.

https://forum.pjrc.com/threads/57754-Teensy-4-0-SPI-Clock-Speed

Update: 

Switching transfer speed is painless and costs next to nothing. Using 

SPI.beginTransaction(fastSettings);

where fastSettings sets speed etc: 

SPISettings     fastSettings(8000000, MSBFIRST, SPI_MODE0);

This means that DAC and DCOs can share SPI bus.

Port expanders

Right now I use SPI for this, but I will move these to PCA95xx, I2C chips. We don't need high speed here so freeing up SPI from this task is good. Port expander changes will always (?) be on-demand so it doesn't matter that much if they block for a tiny amount of time.

Audio daughterboard

I have yet to try this, but it runs from a combo of I2S and I2C. Both are available and there is a separate I2C that can be used if I don't want to combine it with the port expanders even though the bus is just that, a bus.

Hardware

My current voice card uses a Teensy 4.1. It has SPI (SPI0) and SPI1 exposed as pins, and two I2C-busses readily available. SPI2 is used for SD card and memory on the teensy itself. I may be able to solder stuff directly to the pads but not sure how easy it will be to use them. 

The Teensy 4.0 only exposes SPI (0) as a pin, but adding SPI1 is not too hard. SPI2 is also available but requires soldering wires. It can be done but I would prefer not to.

Going with the Teensy 4.0 would save significant physical space on the voice card, and it is also about 50% cheaper than the 4.1 (with ethernet). I would however lose the posibility of using on board PSRAM and extra flash memory which MAY be nice if using an audio daughterboard?


Friday, January 22, 2021

SPI error handling on the PIC16F

Various stuff happens in the SPI module that indicate errors. Here is a short description of what is going on.

Double buffering

SPI on the PIC16F uses a double buffer consisting of SSPxSR and SSPxBUF. 

SSPxSR is the shift register directly connected to the input, it receives bits when the clock runs. Once 8 bytes have been received, it transfers its content to SSPxBUF, sets the SSPxSTAT.BF (buffer full) bit and raises the SSPxIF interrupt. The BF bit is cleared automatically when reading SSPxBUF.

Data to be transferred is written to SSPxBUF and shifted out either immediately (for master) or the next time the other device runs the clock (for slave).

The following two bits indicate errors in transmission:


SSPxCON1.WCOL

Write Collision. Is set if the user tries to write a new byte to SSPxBUF before the current one has been shifted out/transferred. The data written to SSPxBUF is ignored, and all future writes are also ignored until the WCOL is cleared by the user.


SSPxCON1.SSPOV

Receive overflow. Is set if a new byte is received before the old one is read. Only used when device is an SPI slave. Slave must read SPPxBUF even before transfers to prevent the setting of this bit. On overflow, the current byte in SSPxSR is lost. 

In my DCO I check this when SS is driven high, before copying received data to where the user program expects to find it.


SSPxCON3.BOEN

Buffer overwrite enable. If set to high, data is written to the SSPxBUF even if the current byte has not been read. The datasheet does not say explicitly that it does or does not set the SSPOV bit, but it can safely be ignored. BOEN is used if we want to chain SPI slaves as one long shift register - data written to the slave will automatically be transferred to the SSPxBUF and shifted out once the next byte is received, without being touched by the user code. This way, one can keep the slave select pin low, transfer any number of bytes corresponding to the number of slaves connected, and then raise the slave select pin once all data has been transferred.

This is NOT used for my DCO as it will receive three bytes for each slave before the SS is driven high and thus has its own logic for shifting data internally.


SS pin 

The slave select pin synchronises reception. When in use it will be held high until the master is ready to communicate. The master will lower the pin, then transfer data and finally rise it. Using the SS pin makes sure data does not become out of sync and allows multiple slaves on the same SPI bus.

When the SS pin is driven high, the SPI bit counter is reset to 0, even if less than 8 bits have been received, meaning we will never get out of sync as long as SS is used.


SPI Initialisation

I can't find it right now, but I read that SPI must be initialised only when the clock is in the idle state. It may be that this is just because if not we risk getting incomplete/corrupt data, but it still seems like a good practice.

The way I've achieved this in the DCO is to initialise the SPI when the SS pin goes high the first time. That means that the master can either drive the SS pin low and high again, or it will happen automatically if data is transferred (but the data transferred will be lost) if the slave has restarted for some reason, or starts after the master has sent its first byte. This may not be the solution for everyone but it is sufficient for me. A different option would be to use some other scheme where an additional pin on the slave signals its status as "ready to receive" or similar.

To be able to do this, I had to both set use of SS to true and map a pin as SS, and add an edge trigger interrupt to the same pin. The edge bit should be set to 1 (rising edge).

Another PS for the use of SPI: The TRIS bits for the pins in use must be set manually upon initialisation;

SDI (TRIS set = input)

SDO (TRIS cleared = output)

SS (TRIS set = input)

SCK (TRIS cleared = output for master and TRIS set = input for slave)

Any function not desired may be disabled by setting the opposite data direction/TRIS value.

Sunday, March 26, 2017

SPI Daisy chaining

Just  a quick tip from the PIC18F datasheet: SPI interfaces on multiple MCUs may be daisy chained, connecting the output of one to the input of the next. They will then function as a long shift register, shifted 8 bits for every SPI send. NB: Chip select must be connected to all MCUs if used.

DCO: SPI and DAC accuracy

A few compromises have to be made when making the DCO. There are however a few things that must be done right.

First of all, we cannot afford to lose any input commands. This will put the SPI input buffer in an unknown state, possibly locking up the DCO.

With this in mind, we can do a few calculations.

First of all - each frequency update is based on a 16bit integer. The SPI buffer is only 8 bits long, so two bytes must be transferred. Each transfer triggers an interrupt, and that interrupt must copy the transferred byte from the SPI buffer to somewhere else before the next byte arrives.

Fortunately, the SPI buffer is, as it says, buffered. This means that it is not written until the last bit of the byte is received. In addition, there is a short delay between bytes.

As an example, when running the SPI bus at 200kHz, a byte is 40uS long. The delay between two bytes is 7.5uS (when output from node.js on a Raspberry PI).

Running the MCU at 20MHz we have an instruction clock of 5MHz, and each instruction takes 0.2uS. This means that with a 200kHz SPI bus and 20MHz clock, we have 237 instruction cycles to handle a received byte.

This is of course much more than we need - as long as the interrupt handler triggers immediately. But for the DCO to be as accurate as possible, we have given priority to the timer that sets the output wave period. The SPI interrupt will be blocked if a timer interrupt has been received and will not be treated until the timer interrupt handler returns. Thus, we have to make sure the time it takes to enter the timer interrupt handler, do whatever it needs to do, return from the handler and then enter the SPI (low priority) interrupt handler, takes less than 237 instructions - if not, we may be inside the timer interrupt handler when the next SPI byte arrives and we'll lose the previous byte.

This sounds all good, right? The time it takes to reset the timer is not that long. Well, we do actually have a problem. If we are to both reset the timer AND change the DAC value (that controls the current that charges the integrator capacitor making the saw wave), we run into trouble. The DAC is written to using SPI, and we have to write three bytes to set it. Unless the DAC SPI runs at several MHz, we do not have time to write to it within the 47uS we have available. In simple terms, we cannot write to the DAC inside the interrupt handler.

So what is the consequence of this? 

The only other place to write to the DAC is inside the main program loop. As we will be at an arbitrary place in the code when a timer interrupt triggers, we will get a delay from when the timer triggers to where the DAC update call is found (+ the time spent writing to the DAC).

To reduce the maximum delay, we may check if a DAC update has been requested and update the DAC at several spots in the main loop.

But how big is the consequence of delaying the DAC?

At 200kHz, updating the DAC takes approximately 135uS = 675 instruction cycles. This delay is unavoidable.

The longest single method within the main loop, recalculating the frequency, takes 723 cycles. If we break this up into 5 intervals, we'll add around 150cycles to the maximum delay, which will then be around 825 cycles or 165uS.

What does this mean?

It means that for 165uS, the DAC will output the wrong voltage, and the capacitor will charge too fast or too slow. If it charges too slow, the capacitor will be at less than 5V when the charging is reset by the period timer. If it charges too fast, it will be at more than 5V. But how much?

Let's look at the two extremes:

Going from 16.5Hz to 20kHz

Here, the DAC will have a very low charge current. The period at 20kHz is 50uS. This means that for a little more than three periods, the charging will be way too low, in fact probably so low that the wave will look completely flat. However, this is only for 3 of 20.000 cycles within a second. Question is if it is audible.

Going from 20kHz to 16.5Hz

The DAC will have a very high charge current. It charges at the same level as when the frequency is 20kHz, which means that after 50uS, the output value is 5V and after 150uS it has reached 15V (but the buffer opamp or other parts of the circuit probably saturates, keeping the maximum at around 14.3V. The cap stays at this level for one full charging cycle, around 61mS. This is not a very ideal situation.

This is of course in the extreme cases. Most often the change in pitch will be small, but a few octaves are still likely.

What can be done to remedy this?

1) Increased DAC SPI speed - pushing the speed to 2MHz will reduce the write delay to 13.5uS, with a total of 43.5uS including the delay before we reach the reset DAC code. This is if the MCU and DAC can handle the increased SPI speed

2) Increase the MCU speed from 20MHz to 32MHz - this will reduce the maximum time before the DAC write is started from 30uS to 18.75uS (as each instruction now takes 0.125uS instead of 0.2uS.

3) Check more often if we need to update the DAC, further reducing the maximum time before the DAC is written to

4) If the DAC SPI speed is sufficiently high, put the write back into the interrupt routine, removing the delay before a write altogether.

If 1) is possible, and the rest of the timer interrupt handler takes less than 47.5uS - 13.5uS = 34uS, 4) is certainly the best option.


Input SPI speed

We chose 200kHz as the SPI speed at the start of this post. At this speed, 16 bytes will take 47.5uS to transfer (inc delay between bytes), giving an effective transfer rate of 21kB/s.  The Xonik M8 voice controller runs at less than 4k updates/second, so this is sufficient for updating tree DCOs at that rate. The PIC32 has a multi-byte SPI buffer, so we may actually write all bytes to the SPI buffer and forget about them, leaving the voice card MCU to do other duties while the buffer is written (though we have to write to the separate DCOs one at the time as the chip select lines must be changed between the DCO writes.

To further improve the performance of the main MCU (and reduce the delay between when a frequency update is requested and a new frequency is visible on the output), we should calculate the maximum time spent in the period timer interrupt handler and optimize the SPI speed such that the time spent transferring a byte is just barely longer than this.


Maximum delay

The maximum delay from a byte request has been received at the main voice controller to it is visible at the DCO input may be calculated as follows:

2 x matrix calculation time
+ 2 x byte transfer time
+ 1 x transfer delay
+ 1 x time spent calculating new frequency params
+ 1 x delay writing to timer registers
+ 1 x time that must be left for an update
+ 1 x longest cycle time
+ 1 x time within period interrupt handler
+ 1 x maximum delay before DAC write starts
+ 1 x DAC write time.

2 x matrix calc time because the command may arrive just after a calc has started and be written at the end of a calc update


Update: SPI and DAC speeds

The MAX5216 SPI can run at 50Mhz. The PIC SPI runs at maximum Fosc/4, which equals 5MHz with a 20MHz crystal, 8MHz with a 32Mhz. In any case, transferring 24 bits takes approx 27 instruction cycles, so setting the DAC in the interrupt routine is well within what is feasible. Thus, the delay from period start to the DAC is set is 27 * 0.125uS = 3.4uS + any cycles between the timer reset and the call to set the DAC - 7 cycles + the time it takes to call the SPI function - an estimate may be 40 cycles = 5uS in total (at 32MHz).

This means that in the case of a too-high charging current, the cap will be charged at max for about 1/10th of the charge time at 20kHz, contributing about 0.5V too much to the end result (5.5V instead of 5V). This is probably tolerable.

Similarly, the whole interrupt function will take 33 cycles (timer) + 40 cycles (DAC). Add 10 cycles to enter and store the SPI byte and the total is 83 cycles or 10.4uS. Transmission speed will then have to be more than 1.3uS per bit, which gives a max SPI speed of 769kHz (at 32MHz)

Update 2:

The only times we should have to update the charging current will be right after we have calculated and set a new frequency. For most frequencies, this update will happen right after an SPI write (for low frequencies we will get a delay, though). If we keep the DAC update outside of the interrupt handler, we will still normally not be inside the calculation routine for a new frequency when the interrupt returns, so the delay between timer update and DAC update will be minimal. We may still encounter a large delay as it may take up to one period from frequency calculation to the frequency has been set. If SPI bytes arrive faster than this (as they most likely will if the main controller runs at 2-4kHz), we may still be inside the calculation routine.

By moving the DAC update we'll shorten the delay to 43 cycles = 5.38uS, giving us a bit time of 0.673uS and a max SPI speed of 1.49MHz (at 32MHz clock speed)

Ultimately it all comes down to what is most important - a high SPI speed to minimize the time the master spends writing or a short delay before the DAC is set to assure a high max voltage accuracy.

As mentioned previously, we may use the multi-byte SPI buffer on the PIC32 based voice controller, so the exact write speed is not all that important (as we do writes as fire-and-forget) but faster is still better - we will have to write some special code that writes to the DCOs at regular intervals through one matrix recalculation cycle as we cannot afford wasting calculation time waiting for a write to complete before filling the SPI buffer with the next DCO values (Though perhaps it would be possible to come up with a chaining scheme where six bytes are clocked through the three DCOs before they are "commited" and the values read - perhaps by a chip select line going low or similar. The PIC32 is capable of generating an interrupt once the SPI buffer is empty, so it's easy to add a single line change when transmission is complete).

Wednesday, March 22, 2017

SPI from raspberry PI to PIC18F

This is mostly for my own reference later:

The following is confirmed to work:

I've connected the raspberry PI as an SPI master. Only output and clock from the PI must be connected, not the PIC18F SPI out, as the PI is not 5V tolerant.

In my special PI-to-xonik m8 voice controller cable, the following pins are used:

PIN0: Signal (Master out/slave in, PI is master)
PIN2: Clock
PIN7: GND - NB - NOT PIN9!

These must be connected to the following on the EasyPIC 3 card:
RC3: Clock
RC4: Signal (SPI in)
RC9: GND

With this connection, the following settings work:

PIC18F:
SPI1_Init_Advanced(
SPI_SLAVE_SS_DIS,
SPI_DATA_SAMPLE_MIDDLE,
SPI_CLK_IDLE_LOW,
SPI_HIGH_TO_LOW
);

(incidentally the same as in my libstock example)

Raspberry PI:
let mode = 'MODE_1';     // clock idle low, clock phase active to idle.

function initSPI(){

  var spiConfig = {
    'mode': SPI.MODE[mode],   
    'chipSelect': SPI.CS['none'], 
    'maxSpeed': 200000
  };

  spi = new SPI.Spi(
    config.spi.device, 
    spiConfig, 
    function(s){
      s.open();
    }
  );

}

Sunday, December 20, 2015

Working node.js SPI code connecting a Raspberry PI with a PIC32MX

var SPI = require('spi');

var spi = new SPI.Spi('/dev/spidev0.0', {
    'mode': SPI.MODE['MODE_1'],   // clock idle low, clock phase active to idle.
    'chipSelect': SPI.CS['none'], // 'none', 'high' - defaults to low
    'maxSpeed': 8000000
  }, function(s){s.open();});

var rxbuf = new Buffer([ 0x00 ]);

var state = 0;

function writeToSpi(){
    var txbuf = new Buffer([ state ]);
    spi.transfer(txbuf, rxbuf, function(device, buf) {
        console.log("Wrote " + state + " to SPI");
        console.log("Received " + buf[0] + " from slave");
    });

    state++;
    setTimeout(writeToSpi, 100);
}

writeToSpi();

SPI gotchas

I am working on SPI communication between the Raspberry PI and a PIC32MX microcontroller for use in the Xonik M8 polysynth.

SPI is a very easy protocol once you get the hang of it, but it has a few gotchas:

1) Setup - SPI mode

There are two important parameters that control transmission. It is not essential to understand exactly what they do, but it IS important that they are set up the same way on the master and the slave. The parameters are:

CPOL - clock polarity
This defines when the clock is "idle" and when it is "active".  The clock stays in idle mode whenever data is not transferred and goes active once per bit that should be transferred. The two possible states are:

CPOL=0 - clock is idle low, e.g. it is 0 when it is not running
CPOL=1 - clock is idle high, e.g. it is 1 when it is not running

CPHA - clock phase
This defines when new data should be read from and written to the bus. The two modes are "Idle to Active" and "Active to Idle". When the mode is "Idle to Active", data is READ (captured) when the clock changes from idle to active. Data must be WRITTEN to the bus when the clock changes from active to idle.

It is important to remember that CPHA is in relation to CPOL. Idle to Active does NOT always mean when the clock changes from 0 to 1 - if CPOL is 1, Idle to Active happens when the clock changes from 1 to 0.

The two possible states are:

CPHA=0 - Idle to Active, data is read when the clock changes from idle to active
CPHA=1 - Active to Idle, data is read when the clock changes from active to idle

This may sound a bit complex, but unless you are writing your own SPI slave/master code on a device without hardware support, all is taken care of for you. You just have to select the same config on the master and the slave.

The four common modes are:

0 - CPOL=0, CPHA=0 - clock is idle low, data is read on the rising edge
1 - CPOL=0, CPHA=1 - clock is idle low, data is read on the falling edge
2 - CPOL=1, CPHA=0 - clock is idle high, data is read on the falling edge
3 - CPOL=1, CHPA=1 - clock is idle low, data is read on the rising edge

2) Data transfer

Data transfer is full duplex, meaning that data is sent and received at the same time. One bit of data is transfered every clock cycle - in both directions.

If any data exists in the output buffer, it will be sent when the clock ticks once. Similarly, any data on the wire will be put into the input buffer when the clock ticks once. In other words, anything found in the output buffer on the master AND slave will be put on the wire once the clock starts running.

But what does this really mean?
First of all it means that in order to receive bits, the master has to pulse the clock the same number of times as the number of bits it wants to receive.

To do this, many SPI libraries including those on the Raspberry PI and the Microchip microcontrollers require you to actually send a byte. The byte may be zero as we are often only interested in the received data (this, of course, means that the transfer is only half duplex), but it can also be data usefull to the slave such as the next command/address to retrieve.

Secondly, to retrieve data from a slave you first need to transfer a command from the slave to the master. This could be a memory address, an action or similar, telling the slave to fill its output buffer. After the initial command/once the output buffer has been filled, you have to send a second byte to run the clock in order to transfer the data from the slave to the master. As mentioned above, this byte could either be bogus data or a new command, it all depends on how the slave is implemented. (As a side note, it is not strictly necessary to send a command before receiving data. For example, a ADC SPI slave could continously put its latest sampled value into its output buffer, which the master will read whenever it needs a new value from the ADC).


More info about the SPI bus can be found on wikipedia.

SPI and the Microchip PIC using Mikroelektronika's MikroC

There is another gotcha in the naming of SPI states in MikroC. For the 8 bit microcontrollers, CPHA modes are "high to low" and "low to high". These are NOT describing 0 and 1. Instead they are the same as "Active to Idle" and "Idle to Active".