C语言dsPIC / PIC24 serial bootloader和C#语言bootloader PC端串口通信程序

         了解更多关于bootloader 的C语言实现,请加我QQ: 1273623966 (验证信息请填 bootloader),欢迎咨询或定制bootloader(在线升级程序)。

  新dsPIC/PIC24 Bootloader

  PhsBoot_v4.0是我最新用C语言实现的PIC bootloader, 采用串口通信,适用于dsPIC30, dsPIC33和PIC24, 并为其用C#写了PC端通信程序PhsLoader_v4.0。PhsLoader_v4.0通过串口按照自定义的通信协定发送数据PhsBoot_v4.0, PhsBoot_v4.0接收数据,按照通信协定解读数据,解读出其中Hex数据,并将其烧录到正确的位置。

  通信协定

  dsPIC/PIC24单片机端PhsBoot_v4.0和PC端PhsLoader_v4.0之间的通信数据包采用以下协定

<STX><CMD><ADDRL><ADDRH><ADDRU><ADDRM><LEN><DATA>...<DATA><ETX>

  定义如下:

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 32 bits  ( ADDRL , ADDRH , ADDRH, ADDRM)

  具体有以下Base command:

RD-VER:  0x00 -- Read Version Information (最终版本删除了此命令)
RD_MEM: 0x01 -- Read Program Memory (最终版本删除了此命令)
ER_MEM: 0x03 -- Erase Program Memory
WR_MEM: 0x02 -- Write Program Memory
WR_CFG: 0x04 -- Write Configuration Registers

  PhsLoader_v4.0 功能

  定义好了通讯协定, 接着就按照协定去实现PhsLoader_v4.0。 PhsLoader_v4.0的具体功能包括选择COM端口和BAUD RATE, 连接COM, 加载应用程序Hex文件,Parse 应用程序的Hex文件,一行一行解读Hex文件,然后按照通讯协定通过串口发送Hex记录到单片机,接收单片机发送回来的Response,发送完毕后断开COM连接,发送期间出现问题就立马结束发送。

  PhsLoader_v4.0 主要代码段

  PhsLoader_v4.0是用C#实现的,是我在利用空余时间自学C#后写的,上面提到的功能都实现了。

        private void btnDownload_Click(object sender, EventArgs e)
        {
            btnDownload.Enabled = 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
");
                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
");
                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;
            loaderUpperAddr = 0;
            bool isNextLineUserID = false;
            bool isNextLineConfigBits = false;
            textBoxStatus.AppendText("
Downloading hex file ...
");
            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)
                        {
                            const int ADDR_U_START_INDEX = 9;
                            const int ADDR_U_LENGTH = 4;
                            string addrU = recordLine.Substring(ADDR_U_START_INDEX, ADDR_U_LENGTH);
                            loaderUpperAddr = Convert.ToInt32(addrU, 16) << 16;
                            isNextLineConfigBits = true;
                            continue;
                        }
                        else if (recordLine.Contains(DSPIC_CONFIG_BITS_TOKEN) == true)
                        {
                            const int ADDR_U_START_INDEX = 9;
                            const int ADDR_U_LENGTH = 4;
                            string addrU = recordLine.Substring(ADDR_U_START_INDEX, ADDR_U_LENGTH);
                            loaderUpperAddr = Convert.ToInt32(addrU, 16) << 16;
                            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);
                            loaderUpperAddr = 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;
                        //}
                        DownloadConfigLine(recordLine);
                        isNextLineConfigBits = false;
                    }
                    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
");
                textBoxStatus.ForeColor = Color.Black;
                loaderSerial.Close();
                loaderReader.Close();
                btnDownload.Enabled = true;
                return;
            }
            textBoxStatus.AppendText("Downloading completed
");

            if (!run())
            {
                textBoxStatus.ForeColor = Color.Red;
                textBoxStatus.AppendText("Jump to Application unsuccessfully
");
                textBoxStatus.ForeColor = Color.Black;
                loaderReader.Close();
                loaderSerial.Close();
                btnDownload.Enabled = true;
                return;
            }
            loaderSerial.Close();
            loaderReader.Close();
            btnDownload.Enabled = true;
        }        
View Code

  PhsLoader_vr4.0 用户界面

  

  PhsBoot_v4.0 功能

  在PhsLoader_v4.0完成后,接着就是完成PhsBoot_v4.0。 PhsBoot_v4.0主要功能就是接收PhsLoader_v4.0传送过来的Hex记录。解读Hex记录中的启始位,命名,地址,数据和结束位,将数据烧录到指定的程序存储器的位置上,然后通过串口返回Response消息给PC端PhsLoader_v4.0。

  PhsBoot_v4.0 位置

  PhsBoot_v4.0放置在程序存储器的第2个Page(第一个Page为Reset vector和IVT/AIVT vector),大小为0x800程序字。

  

  如上图所示,对于dsPIC33/PIC24, HyperBoot_v4.0的ROM Range是0x400~0xBFF, 对于dsPIC30, HyperBoot_v4.0的ROM Range是0x100~0x5FF。

  ROM Range 设置

  下面以dsPIC33FJ256GP710A为例,详细说一下如何设置ROM Range。在编译PhsBoot_v4.0时,需要添加p33FJ256GP710A.gld文件到项目目录中来,并对其修改以下地方。

  program (xr) : ORIGIN = 0x400, LENGTH = 0x0800 /*2A9FE*/
  __CODE_BASE = 0x400;
  __CODE_LENGTH = 0x0800; /*2AA00;*/

  这样就完成了对PhsBoot_v4.0的ROM Range的设置。

  另外由上图可知,应用程序需要烧录到dsPIC33FJ256GP710A ROM的0xC00之后。所以在编译应用程序时,同样需要添加p33FJ256GP710A.gld文件到项目目录中来,并对其修改以下地方来完成ROM Range设置。

  program (xr) : ORIGIN = 0xC00, LENGTH = 0x02A000 /*2A9FE*/
  __CODE_BASE = 0xC00;
  __CODE_LENGTH = 0x02A000; /*2AA00;*/

  PhsBoot_v4.0 主要代码段

  PhsBoot_v4.0采用的是程序字烧录,具体实现代码段如下。

    unsigned char RecivedByte = 0;
    while (1)
    {
        if (U1STAbits.URXDA)
        {
            RecivedByte = ReadUART1();
            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:
                        WriteWordMem(PM_WORD_WRITE);
                        sendResponse();
                        break;
                    case WR_CFG:
                        WriteWordMem(CM_WORD_WRITE);
                        sendResponse();
                        break;
                    case ER_MEM:
                        EraseMem();
                        sendResponse();
                        break;
                    case RUN_APP:
                        sendResponse();
                        secCount = 0x7ffff;
                        U1MODE = 0x0;
                        U1STA = 0x0110;
                        while(secCount--);
                        //RCONbits.SWDTEN=1;     // use Watch Dog to reset device
                        //while (1);
                        (*((void(*)(void))PROG_START))();
                    default:
                        break;
                    }
                }
                else
                { //Send data error back
                    while (BusyUART1());
                    WriteUART1('?');
                }
                m_buffer_Index=0;
            }
        }
    }

  如何使用

  1. 使用XC16编译PhsBoot_v4.0(编译前,需先修改gld文件,详见"ROM Range设置")。

  2. 使用pickit3烧录PhsBoot_v4.0的Hex文件到目标板中。

  3. 拔除pickit3烧录器

  4. 连接目标板与PC的串口,打开PhsLoader_v4.0用户界面,选择COM端口,BAUD RATE。

  5. 点击PhsLoader_v4.0用户界面上的“.."按钮加载需要烧录的应用程序Hex文件(编译前,需先修改gld文件,详见”ROM Range设置")

  6. 重启目标板,接着立刻在PhsLoader_v4.0界面上点击Download按钮。如果超时未点击Download按钮,目标板会自动跳转到上次烧录的应用程序中去。

  7. 烧录完毕,再次重启目标板, 2秒后目标板开始正常运行应用程序。

  之后每次更新应用程序,只需重复步骤 4 ~ 7 就可以了。

  主要特性

  PhsBoot_v4.0有以下主要特性

  1. C语言写的,XC16 编译。

  2. 非常容易移植, 支持dsPIC30, dsPIC33, PIC24。

  3. 支持FLASH烧写

  4. 可支持EEPROM烧写。

  5. 支持CONFIG BITS/IDLOC 烧写。

  如果你有什么疑问,或有兴趣了解更多关于bootloader 的C语言实现,请加我QQ: 1273623966 验证信息请填 bootloader 或 cnblogs)。

  若需了解我的上一款dsPIC/PIC24 串口bootloader 请阅读随笔《自己用C语言写dsPIC / PIC24 serial bootloader》

原文地址:https://www.cnblogs.com/geekygeek/p/dsPIC_serial_bootloader.html