At first, i tried to communicate with MCP3008 with raspberry using wiring Pi library and as it communicates through the spi driver, the data retrival of it is quite slow. Then, i opt for the next option that is to access the register of the BCM2835 Arm cortex chip and by using bcm2835.h, i communicate with MCP3008 and it successfully communicates. The code for communication is provided below.
#include <stdio.h>
#include <stdint.h>
#include <bcm2835.h>
#include <sched.h>
#include <string.h>
#include <sys/mman.h>
#include <inttypes.h>
static uint8_t buff[3] = {0};
char value[] = {0x01, 0x80, 0x00};
int readadc(adcnum)
{
char one[] = {'2', '2','3'};
buff[0] = 1;
buff[1] = (8+adcnum)<<4;
buff[2] = 0;
value[0] = buff[0];
value[1] = buff[1];
value[2] = buff[2];
//send the value into function and declare the size of it inside
bcm2835_spi_transfern(value, sizeof(value));
buff[0] = value[0];
buff[1] = value[1];
buff[2] = value[2];
//converting into output value upto 1024 supported by 10 bit resolution
adcnum = ((buff[1]&3) << 8) + buff[2];
return adcnum;
}
int main(int argc, char **argv)
{
uint64_t a,b ;
// If you call this, it will not actually access the GPIO
// Use for testing
// bcm2835_set_debug(1);
if (!bcm2835_init())
{
printf("bcm2835_init failed. Are you running as root??\n");
return 1;
}
if (!bcm2835_spi_begin())
{
printf("bcm2835_spi_begin failed. Are you running as root??\n");
return 1;
}
bcm2835_spi_begin();
bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);
bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);
bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_32);
bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);
int i = 0;
while(1)
{
a = bcm2835_st_read();
printf("The value read as %d \n", readadc(0));
printf("The value read as %d \n", readadc(1));
printf("The value read as %d \n", readadc(2));
printf("The value read as %d \n", readadc(3));
printf("The value read as %d \n", readadc(4));
printf("The value read as %d \n", readadc(5));
printf("The value read as %d \n", readadc(6));
printf("The value read as %d \n", readadc(7));
printf("The value read as %d \n", readadc(4));
printf("The value read as %d \n", readadc(5));
printf("The value read as %d \n", readadc(6));
printf("The value read as %d \n", readadc(7));
}
bcm2835_spi_end();
bcm2835_close();
return 0;
}
Using this piece of code, the clk of spi fluctuates a lot from 10khz to 20 khz. Then, i added this piece of line into above mentioned code to prevent process swapping and dramtically, speed increased from 10 to 20 khz to around 60 khz and best part of it is that the frequency value nearly remains constant.
struct sched_param sp;
memset(&sp, 0, sizeof(sp));
sp.sched_priority = sched_get_priority_max(SCHED_FIFO);
sched_setscheduler(0, SCHED_FIFO, &sp);
mlockall(MCL_CURRENT | MCL_FUTURE);
Can u provide me suggestion about more ways for increasing the speed of the clk of spi or u can optimize my code where it is required. Thank u.