1     void sdthread()
2     {
3        os_thread *thread, *temp_thread, *next_thread;
4        char c;
5        UCHAR *buffer;
6        //FILE* file;
7        //DIR* dir;
8        register UINT progSize, i;
9        //UCHAR filename[22] = "test.txt";
10       thread = g_currthread;
11
12       DDRB |= 0b00000100;
13
14       while (1)
15       {
16          c = MmcInit();
17          if (c == 0)
18          {
19             PORTB.2 = 1;
20          }
21          else
22          {
23             PORTB.2 = 0;
24          }
25          if (c == 0 && PINB.1 == 0)
26          {
27             PORTB.2 = 0;
28             // we want to load a new program
29             temp_thread = g_usedthreads;
30             while (temp_thread != NULL)
31             {
32                // kill any thread but the null/sd thread
33                if (temp_thread != thread)
34                {
35                   next_thread = temp_thread->next;
36                   TerminateThread(temp_thread);
37                   temp_thread = next_thread;
38                }
39                else
40                {
41                   temp_thread = temp_thread->next;
42                }
43             }
44             os_reset_stack();
45
46             // grab some stack space
47             //file = (FILE*)os_alloc_stack(sizeof(FILE));
48
49             //dir = (DIR*)os_alloc_stack(sizeof(DIR));
50
51             //dir->directoryID = 0;
52
53             //fopen(dir, file, filename, FOPEN_CREATE);
54             //dread(dir,file);
55             buffer = (UCHAR*)os_alloc_stack(512);
56
57             // read in the first sector. The first 2 bytes are the size of the program
58             mmc_read_sector(0, buffer);
59             progSize = (((int)buffer[0]) << 8) | buffer[1];
60
61             // just write 0x00 and jmp to 0x01
62             buffer[0] = buffer[1] = 0;
63
64             // write the first sector
65             WriteSector(0, (UINT*)buffer);
66
67             for (i = 512; i < progSize; i += 512)
68             {
69                mmc_read_sector(i, buffer);
70                   WriteSector(i, (UINT*)buffer);
71             }
72             os_reset_stack();
73             #asm("cli");
74             temp_thread = CreateThread(1, 255, 150, 150);
75             #asm("sei");
76          }
77       }
78    }