Whenever I take data from the MCP3008, my sample rate keeps changing. Sometimes it’s 24ksps, sometimes 200sps. I want to keep this fixed. Python Code for SPI communication on raspberry pi:
import time import sys import spidev spi = spidev.SpiDev() spi.open(0,0) spi.max_speed_hz=(3600000) def readadc(adcnum): if ((adcnum > 7) or (adcnum < 0)): return -1 r = spi.xfer2([1, (8+adcnum) <<4, 0]) adcout = ((r&3) << 8) +r return adcout ch0 = 0 seconds = time.time() while (time.time() < seconds+1): pc_value = readadc(ch0) print pc_value output_file.write("%s \n" %(pc_value))
Thanks for your help!
bumped to the homepage by Community♦ yesterday
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
Can I fix the MCP3008 sample rate?
Yes, you can. You make one conversion by doing one SPI writing/reading. In other words, more frequent SPI write/read means higher sample/conversion rate.
I would suggest you to skim through the datasheet quickly once, and read very slowly Section 5.0, Fig 5.1, and 5.2 a couple of times. I have made a summary picture below to refresh your memory.
I suggest you to stare at my picture for a couple of minutes, then I will explain.
Section 5 and Figs 5.1, 5.2 are complicated, considering a couple of cases. Let us study case by case, beginning the simplest.
Case 1 – How to sample/convert, and get the 10 bits results
(a) You SPI write/read two bytes. Your command is in first part of your first byte, the Signal/Differential bit, D0, D1, D2 bits.
(b) MCP3008 reads and only cares about these couple of bits, and doesn’t bother what you write afterwards.
(c) After reading the S/D, D0 ~ D2 bits, MCP3008 gets busy to sample and do the conversion, in almost “no time”, well, two cycles.
(d) MCP3008 then returns the 10 bit results, 2 bits in the last part of the first byte you are still reading (remember SPI writing and reading go hand in hand, at the same time), and 8 more bits in the second byte you read. You add up the two parts to get 10 bits results, and day is done, …
In the above short answer, I said that you can do ADC in a fixed rate. For example, if you would like to do 200 samples per second, then you use the following loop:
loop do one conversion (write read two bytes, and convert binary results to decimal if necessary) sleep 1/200 second end of loop
There is one constraint though. If your SPI speed is 4MHz, then you can at most do about 200ksps. And if you don’t need to use 4Mhz SPI, if your sample rate is lower. For example, if your sample rate is 20ksps, then your SPI speed can be roughly 400kHz. The following post and picture show the relation between SPI speed and max sample rate.