Part of my C journal -- Writing an LPC1114 bootloader
Setting Up the GCC Compiler
I setup a C environment as basic I could. There may be easier ways to go about this, but I wanted to use GCC to compile.
To setup the environment:
1. I downloaded and setup MinGW32.
2. I then downloaded FTD2XX libraries. This included the ftd2xx.h file and ftd2xx.lib.
3. I then stole the test code from Hack-a-Day's article on bitbanging with the FTDI.
4. I modified the code as they suggested by including, in this order, the Windows compatibility files:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <windows.h> #include <windef.h> #include <winnt.h> #include <winbase.h> #include <string.h> #include <math.h> #include <stdbool.h> #include <stdint.h> #include "ftd2xx.h" #include <sys/time.h> |
I used this line to build it:
$ gcc -o main main.c -L./ -lftd2xx
You must have both the ftd2xx.h and ftd2xx.lib in the same directory as you attempt to build.
As for editing, I've really grown to love Sublime Text 2.
If you have issues, make sure directory containing your files is in your PATH environment variable (I go over how to add the directory to your environment variables in this post).
D2XX -- FTDI Support
The FTDI chips are highly controversial chips in the embedded world. I will not begin the debate on their efficacy. I chose this particular serializer since I felt most roboticist would have at least one, making software released using the chips reach a greater range of people on the spectrum of hobbyist to professional.
Also, the supporting tools went well with one of the design goals for this project: Simplicity. I wanted to keep the code as near to machine code as I could easily write. Bdk6 described C to me as, "A high-level assembly language."
There are two basic interfaces for the FTDI chips
- Virtual COM port.
- FTD2XX.DLL
I will be using the DLL. This is what the "-L./ -lftd2xx" part of our compile command is referring. It is including the ftd2xx library found in working directory.
The D2XX library is pretty nifty. It provides a collections of C++ functions to interact with the FTDI chip, and thereby, anything speaking UART.
A full list of the commands and C code examples may be found in the,
One last caveat regarding the reason I selected using the D2XX libraries instead of using the chip as a virtual COM port. I wanted as much control over the metal of the chip is possible. Originally, I had set out to write a downloader that'd use the already existing Sparkfun FTDI breakout, meant to program the Arduino Pro Mini and LilyPad, as no-need-to-modify programmer for my LPC1114 board. To accomplish this, I needed bit level control over all of the pins of the FTDI chip, which the D2XX has, but the COM port does not. Therefore, it was the deciding factor for using the D2XX library. Plus, I didn't know the difference when I started, so that whole explanation was baloney. But, even if I realized it post-fact, it was the reason I didn't switch to COM port.
Setup Menu
I found the easiest way to work with the D2XX is to setup a menu.
YOUR_CODE.C
I'm writing this article as if someone were importing my FTDI_HELPER module to use in their code. A few important notes: First, the variables we will use are actually declared in YOUR_CODE.C. They are global variables. We then redeclare them as extern variables in the FTDI_HELPER.H. This tells the compiler it's going to be using several global variables, but they were actually declared in the YOUR_CODE.C. This allows the FTDI_HELPER module to setup the FTDI device, but your code will be able to act on all the major variables, such as the RxBuffer, ftHandle, etc.
I hope this makes sense. If not, go with it and shoot me whatever questions arise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
YOUR_CODE.C FT_DEVICE_LIST_INFO_NODE *devInfo; bool FTDI_open_flag; uint8_t RawRxBuffer[2048]; FT_STATUS ftSvtatus; DWORD EventDWord; DWORD TxBytes; DWORD BytesWritten; DWORD RxBytes; DWORD BytesReceived; |
- 3: A pointer variable which will store all the connected device information.
- 4: A flag set whenever we actually connect to an FTDI device. This allows your program to detect the connection.
- 7: An RX buffer. It will fill automatically when we receive data. You may adjust the size if needed; I think the FTDI chip only sends 20 bytes at time, but I was lazy.
- 10: Variable to store boolean flag for whether an D2XX command was successful.
- 12: Used to store bytes to be sent.
- 13: BytesWritten is used to store how many bytes were actually written by the FT_Write command.
- 14: RxBytes stores how many bytes are waiting to be read.
- 15: BytesReceived is used by FT_Read to store how many bytes have been read out of the RX buffer.
FTDI_HELPER.H
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 |
FTDI_HELPER.H #ifndef FTDI_HELPER #define FTDI_HELPER #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <windows.h> #include <windef.h> #include <winnt.h> #include <winbase.h> #include <string.h> #include <math.h> #include <stdbool.h> #include <stdint.h> #include "ftd2xx.h" #include <sys/time.h> extern uint8_t ParsedRxBuffer[2048]; extern uint8_t RawRxBuffer[2048]; extern FT_HANDLE handle; extern FT_Status ftStatus; extern DWORD EventDWord; extern DWORD TxBytes; extern DWORD BytesWritten; extern DWORD RxBytes; extern DWORD BytesReceived; int connected_device_num; // Lists FTDI commands. void ftdi_menu(); void quick_connect(); // Lists FTDI devices connected. bool get_device_list(); bool connect_device(int * local_baud_rate); bool close_device(int * local_baud_rate); bool reset_device(int * local_baud_rate); bool set_baud_rate(int * local_baud_rate); bool set_baud_rate_auto(int * local_baud_rate); #endif /* FTDI_helper.h */ |
Again, the extern variables are to let the compiler know we will be using the variables of the same name found in YOUR_CODE.C.
Main Menu
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 |
FTDI_HELPER.C void ftdi_menu() { int baud_rate = 0; char char_choice[3]; int int_choice = 0; bool got_list = false; bool connected_flag = false; bool close_device_flag = false; bool set_baud_flag = false; // FTDI Menu do { system("cls"); printf("FTDI Menu: "); if (connected_flag == true) { printf(" Connected: %lu, N, 1 \n\n", baud_rate); } else { printf(" Not Connected: \n\n"); } printf("1. Quick Connect\n"); printf("2. Device List\n"); if (got_list == true) // Only display option if devices list. { printf("3. Connect Device\n"); } if (connected_flag == true) // Only give display if connected. { printf("4. Close Device\n"); } if (connected_flag == true) // Only give display if connected. { printf("5. Change baud-rate\n"); } printf("9. Main Menu\n"); // If connected, display the connected device info. if (connected_flag == true) { printf("\n"); printf("Connected Device: %d:\n", connected_device_num); printf(" Flags: 0x%02X\n",devInfo[connected_device_num].Flags); printf(" Type: 0x%02X\n",devInfo[connected_device_num].Type); printf(" ID: 0x%02X\n",devInfo[connected_device_num].ID); printf(" Local ID: 0x%02X\n",devInfo[connected_device_num].LocId); printf(" Serial Number: %s\n",devInfo[connected_device_num].SerialNumber); printf(" Description: %s\n",devInfo[connected_device_num].Description); printf(" ftHandle = 0x%02X\n",devInfo[connected_device_num].ftHandle); } // Get user choice. scanf("%s", char_choice); // Convert string to int for switch statement. int_choice = atoi(char_choice); switch (int_choice) { case 1: quick_connect(); baud_rate = 115200; connected_flag = true; case 2: got_list = get_device_list(); break; case 3: if (got_list == true) // Only display option if devices listed. { connected_flag = connect_device(&baud_rate); } break; case 4: if (connected_flag == true) // Only give display if connected. { close_device_flag = close_device(); if(close_device_flag == true){connected_flag = false;} close_device_flag = false; } break; case 5: if (connected_flag == true) // Only give display if connected. { set_baud_flag = set_baud_rate(&baud_rate); // set_baud_flag is not used, yet. } break; case 9: main_menu(); break; default:printf("""Bad choice. Hot glue!"""); break; } }while(int_choice !=99); } |
I found the easiest way to setup a FTDI device in C is using a menu. I've provided five options: (1) Quick Connect, (2) Device List, (3) Connect Device, (4) Close Device, (5) and Set Baud Rate. Several options require running the other options first. For example, before "Connect Device" is displayed you must run "Device List." Let's walk through the code,
- 5-7: Variables for the scanf and switch-statement deriving the menu.
- 9-12: Boolean flags for controlling the flow of the menu.
- 15: We want a menu which is persistent, therefore, we use the do-while loop.
- 19-22: Let's display the connection information, but only if we have a device connected.
- 27-42: We print the rest of the menu. Some items only print if boolean flags are set to true.
- 44-56: Prints out the device details, if connected.
- 58-64: Gets a users input, converts it to an int, store it, then selects a switch-case based upon input.
- 67: The quick_connect() function creates an FTDI connection based upon default attributes.
- 68: Sets the local baud_rate variable to the quick_connect() baud rate.
- 71: We get run the get_list() function, which lists all FTDI devices currently connected to the USB ports.
- 74: We check to see if get_list() has already been run, before we allow the user to connect to a device.
- 76: Connect_device() takes a pointer to the holding the value of the baud-rate the user has selected. It then attempts to connect to the device. If successful, the function returns true.
- 80: Only allow a device to be closed, if one is connected.
- 82: Close_device() attempts to shut-down the currently connected FTDI device. If it is successful, it returns true.
- 83-84: If the close_device() function was a success, the connected_flag is set to false, to show there is no device connected. Then, the close_device flag is reset to false to prepare for the next close_device() call.
- 90: The set_baud() takes a pointer to a value for the desired baud rate. The function attempts to set the baud rate and returns true if successful.
Quick Connect
This function is meant for the lazy user. He or she does not want to select the device, or the baud rate, they'll simply take whatever your program gives you. In my case, I wrote my quick connect to open device '0' and set the baud rate to 115,200.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
FTDI_HELPER.C void quick_connect() { int local_baud_rate = 115200; // Create the device information list ftStatus = FT_CreateDeviceInfoList(&numDevs); // get the device information list ftStatus = FT_GetDeviceInfoList(devInfo,&numDevs); // Open user's selection. // Allocate storage for list based on numDevs. devInfo = (FT_DEVICE_LIST_INFO_NODE*)malloc(sizeof(FT_DEVICE_LIST_INFO_NODE)*numDevs); FT_Open(0, &devInfo[0].ftHandle); FT_SetBaudRate(devInfo[0].ftHandle, local_baud_rate); } |
- 5: Place the baud rate into a variable to be set.
- 7: We create a list of devices, placing them in our global InfoList variable.
- 9: We get the device info on the created device list.
- 12-13: We allocate enough space for info on each device enumerated.
- 14: Opens the device at '0' in the device list.
- 15: Sets the baud rate to 115,200.
Device List
The get_device_list() function is for the more cautious user. First, a list of FTDI devices is generated. After, enough space is allocated in an array for each device's info. Lastly, the device details gathered are placed in this list. If the process of generating and storing the device details was successful the function returns true.
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 |
FTDI_HELPER.C bool get_device_list() { // Create the device information list. ftStatus = FT_CreateDeviceInfoList(&numDevs); if (ftStatus == FT_OK) { printf("Number of devices is %d\n",numDevs); } else { printf("Failed to get FTDI device list.\n"); } if (numDevs > 0) { // Allocate storage for list based on numDevs. devInfo = (FT_DEVICE_LIST_INFO_NODE*)malloc(sizeof(FT_DEVICE_LIST_INFO_NODE)*numDevs); // Get the device information list. ftStatus = FT_GetDeviceInfoList(devInfo,&numDevs); if (ftStatus == FT_OK) { printf("Got Devices\n"); } else { printf("Failed to get device list.\n"); Sleep(3000); } // Set flag if we got at least on device. return true; } return false; } |
- 6: Creates a device list.
- 8-13: If the attempt to create a device list fails, we tell the user. Otherwise, we list the number of FTDI devices currently connected.
- 15: If at least one device was detected, we proceed with listing the devices.
- 18-19: We allocate enough memory space to store the device info of each connected device.
- 22: We read each device, get the info, and put the info in the list respectively.
- 23-30: If we got the device info, we tell the user, "We got devices." Otherwise, we tell the user we failed. Failed, failed, failed!
- 32: Since we gathered some device info, the function returns true.
- 34: If no device info was gathered, the function returns false.
Connect Device from List
Once the get_device_list() function is run, then we are free to connect to one of the listed devices. The connect_device() function takes a pointer to the desired baud-rate value for the connection. This function requires the user enter a number 0-8, which is correlated to the devices gathered from the get_device_list() function. The connect_device() function then connects to the respective FTDI device at the baud-rate passed to it.