-
Notifications
You must be signed in to change notification settings - Fork 1
/
ice40prog.c
executable file
·111 lines (91 loc) · 2.39 KB
/
ice40prog.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/** Very simple bitstream programmer for Lattice iCE40 FPGAs
* using plain FTDI C232HM cable
*
* david.siorpaes@st.com
*
* Pinout
* CLK Orange
* MOSI Yellow
* CS White
* RESET Blue
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <mpsse.h>
int main(int argc, char** argv)
{
int filefd;
struct stat in_stat;
void* fileaddr;
struct mpsse_context* context = NULL;
int err;
uint32_t sync = 0x7eaa997e;
uint8_t trailer[4];
if(argc < 2){
fprintf(stderr, "Usage: %s <file> [file] ...\n", argv[0]);
exit(1);
}
/* Open and mmap file */
if((filefd = open(argv[1], O_RDONLY)) < 0) {
fprintf(stderr, "Failed to open %s: %s\n", argv[1], strerror(errno));
return errno;
}
fstat(filefd, &in_stat);
printf("File length: %u\n", (int)in_stat.st_size);
fileaddr = mmap(NULL, in_stat.st_size, PROT_READ, MAP_SHARED, filefd, 0);
if(fileaddr == MAP_FAILED){
fprintf(stderr, "Failed to mmap %s: %s\n", argv[1], strerror(errno));
return errno;
}
/* Open FTDI device for SPI */
context = Open(0x0403, 0x6014, SPI0, SIX_MHZ, MSB, IFACE_A, NULL, NULL);
if(context == NULL || context->open == 0){
fprintf(stderr, "MPSSE context not valid!\nMake sure winUSB drivers are installed with Zadig\n");
exit(1);
}
else
printf("Context ok\n");
/* Set iCE40 to SPI slave */
PinLow(context, GPIOL2); //spi slave, White wire
PinLow(context, GPIOL3); //reset, Blue wire
usleep(200000);
/* Leave reset */
PinHigh(context, GPIOL3);
usleep(100000);
/* Start SPI communication */
err = Start(context);
if(err != MPSSE_OK){
fprintf(stderr, "Error on Start condition: %i\n", err);
return -1;
}
/* First, send Synchronization Pattern. Cfr TN1248 */
err = FastWrite(context, (char*)&sync, sizeof(sync));
if(err != MPSSE_OK){
fprintf(stderr, "Error writing SPI: %i\n", err);
return -1;
}
/* Send bitstream */
err = FastWrite(context, fileaddr, in_stat.st_size);
if(err != MPSSE_OK){
fprintf(stderr, "Error writing SPI: %i\n", err);
return -1;
}
/* Send dummy bits */
err = FastWrite(context, (char*)trailer, sizeof(trailer));
if(err != MPSSE_OK){
fprintf(stderr, "Error writing SPI: %i\n", err);
return -1;
}
/* Clean up */
Stop(context);
Close(context);
munmap(fileaddr, in_stat.st_size);
return 0;
}