New PIC16 Bootloader
After completing HyperBootloader (see my previous essay for details), I decided to rewrite the PIC bootloader. Why? HyperBootloader uses the PC serial communication software - HyperTerminal to transmit Hex data, one line at a time, and each line is delayed by 20ms to wait for the Hyperbootloader to finish burning. Because this is a bit inefficient, I decided to write the PC serial communication program and PIC bootloader myself. In order to improve efficiency, I also defined the communication protocol between the PC serial communication program and the PIC microcontroller bootloader. First, I rewrote the PIC16 bootloader. I had to complete the PIC16 microcontroller bootloader program - I named it PhsBoot_v1.0; I also had to complete the PC serial communication program that worked with it - I named it PhsLoader_v1.0. For this, I spent three months of free time to teach myself C#.
Communication Protocol
The communication data packets between PhsBoot_v1.0 on the PIC16 microcontroller side and PhsLoader_v1.0 on the PC side adopt the following protocol
The definitions are as follows:
STX - Start of packet indicator
ETX - End of packet indicator
LEN - The length of true data
DATA - General data 16 bytes, only first LEN of datas are true
CMD - Base command
ADDR - Address up to 24 bits ( ADDRL , ADDRH , ADDRH )
There are the following Base commands:
RD-VER: 0x00 -- Read Version Information (This command was deleted in the final version)
RD_MEM: 0x01 -- Read Program Memory (This command was deleted in the final version)
ER_MEM: 0x03 -- Erase Program Memory (This command was deleted in the final version)
WR_MEM: 0x02 -- Write Program Memory
WR_CFG: 0x04 -- Write Configuration Registers
PhsLoader_v1.0 Features
After defining the communication protocol, we will implement PhsLoader_v1.0 according to the protocol. The specific functions of PhsLoader_v1.0 include selecting COM port and BAUD RATE, connecting to COM, loading application Hex file, parsing application Hex file, parsing Hex file line by line, and then sending Hex record to MCU through serial port according to the communication protocol, receiving Response sent back by MCU, disconnecting COM connection after sending, and ending sending immediately if there is any problem during sending.
PhsLoader_v1.0 main code snippet
PhsLoader_v1.0 is implemented in C#. Since I wrote it after learning C# in my spare time, all the functions mentioned above are implemented, but there are definitely areas that can be improved. Welcome to give me some advice. The following is the main code snippet.
private void btnDownload_Click(object sender, EventArgs e) { btnDownload.Enabled = false; pBarLoading.Visible = false; if (!this.connect()) { btnDownload.Enabled = true; return; } try { loaderReader = new StreamReader(textBoxFile.Text); } catch (Exception ex) { Debug.WriteLine("Error: " + ex.Message); textBoxStatus.ForeColor = Color.Red; textBoxStatus.AppendText("Read hex file unsuccessfully\r\n"); textBoxStatus.ForeColor = Color.Black; loaderReader.Close(); loaderSerial.Close(); btnDownload.Enabled = true; return; } loaderFrame = new SerialFrame(); //if (!erase()) //{ // textBoxStatus.ForeColor = Color.Red; // textBoxStatus.AppendText("Erase unsuccessfully\r\n"); // textBoxStatus.ForeColor = Color.Black; // loaderReader.Close(); // loaderSerial.Close(); // btnDownload.Enabled = true; // return; //} pBarLoading.Refresh(); pBarLoading.Visible = true; pBarLoading.Value = 0; pBarLoading.Maximum = loaderLines; pBarLoading.Step = 1; string recordLine; Address_U = 0; bool isNextLineUserID = false; bool isNextLineConfigBits = false; textBoxStatus.AppendText("\r\nDownloading hex file ...\r\n"); try { while (loaderReader.Peek() >= 0) { pBarLoading.PerformStep(); recordLine = loaderReader.ReadLine(); //if (recordLine.Contains(USER_ID_TOKEN) == true) //{ // isNextLineUserID = true; // continue; //} //else if (recordLine.Contains(CONFIG_BITS_TOKEN) = = true) //{ // isNextLineConfigBits = true; // continue; //} if (recordLine.Contains(EXTEND_TOKEN) == true) { if (recordLine.Contains(USER_ID_TOKEN) == true) { isNextLineUserID = true; continue; } else if (recordLine.Contains(CONFIG_BITS_TOKEN) == true) { isNextLineConfigBits = true; continue; } else { const int ADDR_U_START_INDEX = 9; const int ADDR_U_LENGTH = 4; string addrU = recordLine.Substring(ADDR_U_START_INDEX, ADDR_U_LENGTH); Address_U = Convert.ToInt32(addrU, 16) << 16; continue; } } else if (recordLine.Contains(END_OF_HEX_FILE_TOKEN) == true) { break; } if (isNextLineUserID) { isNextLineUserID = false; // do nothing; } else if (isNextLineConfigBits) { if (!DownloadConfigLine(recordLine)) { Debug.WriteLine("Error found during configuration bits programming"); loaderReader.Close(); loaderSerial.Close(); btnDownload.Enabled = true; return; } isNextLineConfigBits = false; } else { //if (recordLine.Contains(J_TYPE_CONFIG_BITS_TOKEN) == true && Address_U == 0x10000) //{ // continue; //} /*else*/ if (!DownloadDataLine(recordLine)) { Debug.WriteLine("Error found during data programming"); loaderReader.Close(); loaderSerial.Close(); btnDownload.Enabled = true; return; } } } } catch (Exception ex) { Debug.WriteLine("Error: " + ex.Message); textBoxStatus.ForeColor = Color.Red; textBoxStatus.AppendText("Downloading failed\r\n"); textBoxStatus.ForeColor = Color.Black; loaderSerial.Close(); loaderReader.Close(); btnDownload.Enabled = true; return; } textBoxStatus.AppendText("Downloading completed\r\n"); if (!run()) { textBoxStatus.ForeColor = Color.Red; textBoxStatus.AppendText("Jump to Application unsuccessfully\r\n"); textBoxStatus.ForeColor = Color.Black; loaderReader.Close(); loaderSerial.Close(); btnDownload.Enabled = true; return; } loaderSerial.Close(); loaderReader.Close(); btnDownload.Enabled = true; }
PhsLoader_v1.0 User Interface
PhsBoot_v1.0 Features
After PhsLoader_v1.0 is completed, PhsBoot_v1.0 is completed next. The main function of PhsBoot_v1.0 is to receive the Hex record sent by PhsLoader_v1.0. It interprets the start bit, name, address, data and end bit in the Hex record, burns the data to the specified program memory location, and then returns the Response message to the PC-side PhsLoader_v1.0 through the serial port.
PhsBoot_v1.0 Location
PhsBoot_v1.0 is placed at the bottom of the program memory, with a size of 0x100 program words. When compiling, the Code offset parameter needs to be set to ROM_SIZE - 0x100. For example, if the ROM SIZE is 0x2000 for a PIC16 microcontroller, the Code offset needs to be set to 0x1F00 (0x2000 - 0x100).
PhsBoot_v1.0 main code snippet
PhsBoot_v1.0 is written in C language and compiled by Microchip 8-bit C Compiler--XC8.
while (1) { if (PIR1bits.RCIF == 1) { RecivedByte = RCREG; PIR1bits.RCIF == 0; m_buffer[m_buffer_Index++] = RecivedByte; //receive data if (m_buffer_Index >= BUFFER_MAX) { if (m_buffer[0] == STX && RecivedByte == ETX) { //get complete cmd switch (m_buffer[CMD_INDEX]) { case WR_MEM: EECON1 = PGM_WRITE; WriteMem(); break; case RUN_APP: sendResponse(); //TXSTA = 0x02; // reset TXSTA RCSTA before jumping to application //RCSTA = 0x00; #asm ljmp BOOT_START #endasm break; default: //sendResponse(); break; } } else { //Send data error back TXREG = '?'; while (TXSTAbits.TRMT == 0); //wait empty } m_buffer_Index=0; } } }
how to use
1. Use XC8 to compile PhsBoot_v1.0. Since PhsBoot_v1.0 will be placed at the bottom of the program memory, occupying 0x100 program words, the Code Offset compilation parameter needs to be set to the correct value before compiling. For example, the program memory space of a PIC16 microcontroller is 0x2000 program words, Code Offset = 0x2000 - 0x100 = 0x1F00, so just set the Code offset to 1F00 and then compile.
2. Use pickit3 to burn the Hex file of PhsBoot_v1.0 into the target board.
3. Unplug the pickit3 programmer
4. Connect the target board to the serial port of the PC, open the PhsLoader_v1.0 user interface, select the COM port, BAUD RATE.
5. Click the “..” button on the PhsLoader_v1.0 user interface to load the application Hex file to be burned.
6. Restart the target board, and then immediately click the Download button on the PhsLoader_v1.0 interface. If you do not click the Download button within the timeout period, the target board will automatically jump to the last application program that was burned.
7. After the burning is completed, restart the target board again. After 2 seconds, the target board starts to run the application normally.
Each time you update the app, just repeat steps 4 to 7.
Key Features
The new PIC16 serial bootloader has the following main features
1. Written in C, compiled by XC8 (only a little bit of assembly in it).
2. Very easy to transplant.
3. Support FLASH burning, fast and small space occupation.
4. Support EEPROM burning.
5. CONFIG BITS/IDLOC burning is not supported. Keep the Configuration Bits of the application consistent with the Bootloader.
Previous article:PIC18 serial bootloader in C language and PC serial communication program with bootloader in C# language
Next article:PIC IDE compiler variable problem
- Popular Resources
- Popular amplifiers
Professor at Beihang University, dedicated to promoting microcontrollers and embedded systems for over 20 years.
- LED chemical incompatibility test to see which chemicals LEDs can be used with
- Application of ARM9 hardware coprocessor on WinCE embedded motherboard
- What are the key points for selecting rotor flowmeter?
- LM317 high power charger circuit
- A brief analysis of Embest's application and development of embedded medical devices
- Single-phase RC protection circuit
- stm32 PVD programmable voltage monitor
- Introduction and measurement of edge trigger and level trigger of 51 single chip microcomputer
- Improved design of Linux system software shell protection technology
- What to do if the ABB robot protection device stops
- Allegro MicroSystems Introduces Advanced Magnetic and Inductive Position Sensing Solutions at Electronica 2024
- Car key in the left hand, liveness detection radar in the right hand, UWB is imperative for cars!
- After a decade of rapid development, domestic CIS has entered the market
- Aegis Dagger Battery + Thor EM-i Super Hybrid, Geely New Energy has thrown out two "king bombs"
- A brief discussion on functional safety - fault, error, and failure
- In the smart car 2.0 cycle, these core industry chains are facing major opportunities!
- The United States and Japan are developing new batteries. CATL faces challenges? How should China's new energy battery industry respond?
- Murata launches high-precision 6-axis inertial sensor for automobiles
- Ford patents pre-charge alarm to help save costs and respond to emergencies
- New real-time microcontroller system from Texas Instruments enables smarter processing in automotive and industrial applications
- How do you calculate the maximum power of a transistor?
- How to use TINA-TI to complete the stability design of transimpedance amplifier circuit
- How to choose DC-DC converters and LED drivers to eliminate PCB space constraints
- MicroPython Hands-on (21) - Magnetic Field Sensor on Control Board
- 【IoT Graduation Project】STM32 Development Board + Gizwits IoT + Realize Smart Air Conditioning Control
- Why do different simulation results appear when the parameters of this simulation routine are set the same?
- Improving the efficiency of wireless sensor nodes using voltage control
- Principles and requirements for the 2021 National Undergraduate Electronic Design Competition
- Keil strange compilation problem
- Watch Shuige's video for a chance to win prizes | USB3.0 Device Tx physical layer consistency test