#include <stdio.h>
#include <time.h>
#include <wiringPi.h>
//This a simple "bit bang" spi example.
#define CLK 10 // Map Clock to pin 10
#define SI 8 // Map Slave In to pin 8
#define SO 7 // Map Slave Out to pin 7
#define CS 16 // Map Chip Select to pin 16
#define RST 12 // Map Reset to pin 12
//setup the gpio
void setalts(){
//set SO as input
pinMode(SO,INPUT);
//set CLK as input
pinMode(CLK,OUTPUT);
//set CLK low
digitalWrite(CLK,0);
//set SI as input
pinMode(SI,OUTPUT);
//set SI low
digitalWrite(SI,0);
//set CS as input
pinMode(CS,OUTPUT);
//set CS high
digitalWrite(CS,1);
//set RST as input
pinMode(RST,OUTPUT);
//set RST low
digitalWrite(RST,0);
}
//this writes one byte of data to the spi
static void spi_write_data(char data)
{
int x = 0;
for(x = 7;x != 0;x--){
//write bit x of data to SI
digitalWrite(SI,(data >> x) & 0x01);
//set CLK high
digitalWrite(CLK,1);
usleep(10);
//set CLK low
digitalWrite(CLK,0);
usleep(10);
}
}
//this reads one byte of data from the spi
static char spi_read_data()
{
char in = 0x00;
int x = 0;
for(x = 7;x != 0;x--){
//Read SO to bit x of in;
in |= (digitalRead(SO) << x);
//set CLK high
digitalWrite(CLK,1);
usleep(10);
//set CLK low
digitalWrite(CLK,0);
usleep(10);
}
return in;
}
int main (void)
{
printf ("Raspberry Pi SPI test\n") ;
//setup wiringpi
wiringPiSetupPhys();
//setup gpio
setalts();
//set RST high
digitalWrite(RST,1);
//set CS high
digitalWrite(CS,0);
//Read all flash contents on some chips
spi_write_data(0x68);
//Starting at address 0x000000
spi_write_data(0x00);
spi_write_data(0x00);
spi_write_data(0x00);
//and one dummy byte
spi_write_data(0x00);
//Open the file we dump the raw flash data
FILE* f = fopen("/home/pi/dump.raw","w+");
int x,y = 0;
//how many Kilo Bytes to read
int kbits = 16000;
for(y = 0;y < kbits ;y++){
for(x = 0;x < 1024;x++){
//read one byte and write to file
putc(spi_read_data(),f);
}
printf("Dumped %dKiB\n",y + 1);
}
//close file
fclose(f);
//set CS low
digitalWrite(CS,1);
return 0 ;
}