PIC16 serial bootloader in C language and PC serial communication program with bootloader in C# language

Publisher:以泉换泉Latest update time:2017-01-20 Source: eefocus Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

  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.


Reference address:PIC16 serial bootloader in C language and PC serial communication program with bootloader in C# language

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

Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号