×
单片机 > 单片机程序设计 > 详情

采用UDP协议实现PIC18F97J60 ethernet bootloader

发布时间:2020-06-08 发布时间:
|

  TCP/IP Stack

  使用pic18f97j60开发过多个项目,项目中都使用了Microchip免费提供的TCP/IP Stack实现远程控制。但是每次更新程序,都需要将pic18f97j60目标板取回来重新烧录,很不方便。既然可以实现远程控制,为什么不实现远程更新呢?这就是我的ethernet bootloader的由来。Microchip的TCP/IP Stack功能很强大,我决定只用它的UDP模块来实现。为了实现远程更新,我需要写pic18f97j60单片机端UDP协议的ethernet bootloader程序--我将其命名为PhnBoot_v1.0; 同时还需要写PC端与bootloader交互的UDP通信程序--我将其命名为PhnLoader_v1.0。我还定义了PhnBoot_v1.0和PhnLoader_v1.0之间传输数据的通信协定。

  通信协定

  单片机端PhnBoot_v1.0和PC端PhnLoader_v1.0之间的通信数据包采用以下协定

...

  定义如下:

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)

  具体有以下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

  PhnLoader_v1.0 功能

  定义好了通讯协定, 接着就按照协定去实现PhnLoader_v1.0。 PhnLoader_v1.0的具体功能包括选择IP地址,端口和协议类型,目前只支持UDP协议, 创建UDP服务器,加载应用程序Hex文件,Parse 应用程序的Hex文件,一行一行解读Hex文件,一旦收到更新请求,立刻按照通讯协定采用UDP协议发送Hex记录到单片机,接收单片机发送回来的Response,发送完毕后断开UDP通信,发送期间出现问题就立马结束发送。

  PhnLoader_v1.0 主要代码段

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


        private void btnDownload_Click(object sender, EventArgs e)
        {
            btnDownload.Enabled = false;
            pBarLoading.Visible = false;            if (!this.connect())
            {
                Debug.WriteLine("Udp server building unsuccessfully");
                textBoxStatus.ForeColor = Color.Red;
                textBoxStatus.AppendText("Udp server building unsuccessfully\r\n");
                textBoxStatus.ForeColor = Color.Black;
                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();
                loaderServer.Close();
                btnDownload.Enabled = true;                return;
            }

            loaderFrame = new SerialFrame();
            DateTime startTime = DateTime.Now;
            IPEndPoint clientPoint = new IPEndPoint(IPAddress.Any, 0);            
            if (!loaderServer.Read(readyMsg,timeSpan))
            {
                Debug.WriteLine("Error: Timeout receive ready message from bootloader");
                textBoxStatus.ForeColor = Color.Red;
                textBoxStatus.AppendText("Timeout receive ready message from bootloader\r\n");
                textBoxStatus.ForeColor = Color.Black;
                loaderServer.Close();
                loaderReader.Close();
                btnDownload.Enabled = true;                return;
            }            if (!erase())
            {
                textBoxStatus.ForeColor = Color.Red;
                textBoxStatus.AppendText("Erase unsuccessfully\r\n");
                textBoxStatus.ForeColor = Color.Black;
                loaderReader.Close();
                loaderServer.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(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);
                            Address_U = Convert.ToInt32(addrU, 16) <


  PhnLoader_v1.0 用户界面

  

  PhnBoot_v1.0 功能

  在PhnLoader_v1.0完成后,接着就是完成PhnBoot_v1.0。 PhnBoot_v1.0主要功能就是使用Microchip的TCP/IP Stack建立UDP Client,发送更新应用程序请求,接收PhnLoader_v1.0传送过来的Hex记录。解读Hex记录中的启始位,命名,地址,数据和结束位,将数据烧录到指定的程序存储器的位置上,然后通过ethernet返回Response消息给PC端PhnLoader_v1.0。

  PhnBoot_v1.0 位置

  PhnBoot_v1.0放置在程序存储器的头部,大小为0x2400程序字。

   

  Interrupt Vector Remap

  由于PhnBoot_v1.0位于程序存储器的头部,需要对Interrupt Vector进行remap. 代码如下。


  #define REMAPPED_APP_HIGH_INTERRUPT_VECTOR  0x2408
  #define REMAPPED_APP_LOW_INTERRUPT_VECTOR   0x2418
  #pragma code low_vector_section=0x018
  void low_vector (void)
  {
      _asm
          goto REMAPPED_APP_LOW_INTERRUPT_VECTOR
      _endasm
  }

  #pragma code high_vector_section=0x08
  void high_vector (void)
  {
      _asm
          goto REMAPPED_APP_HIGH_INTERRUPT_VECTOR
      _endasm
  }


  PhnBoot_v1.0 主要代码段

  PhnBoot_v1.0 是用C语言写的,Microchip 8-bit C Compiler--MCC18编译的。


        switch (GenUDPSt)
        {        case SM_HOME:
            ARPResolve(&Server.IPAddr);            if (ARPIsResolved(&Server.IPAddr,&Server.MACAddr))
            {
                MySock = UDPOpen(ClientPort,&Server,ServerPort);                if (MySock != INVALID_UDP_SOCKET)
                {
                    tick = 0x10000;
                    delay = BOOT_TIMEOUT;
                    GenUDPSt++;
                }
            }            else
            {
                tick--;                if (tick==0)
                {
                    tick = 0x10000;                    if (delay == 0)
                    {
                        delay = BOOT_TIMEOUT;
                        GenUDPSt = SM_CLOSE;
                    }
                    delay--;
                }
            }            break;        case SM_READY:            if (UDPIsPutReady(MySock) > BUFFER_MAX)
            {
                UDPPutString(ok);
                UDPFlush();
                GenUDPSt++;
            }            else
            {
                tick--;                if (tick==0)
                {
                    tick = 0x10000;                    if (delay == 0)
                    {
                        delay = BOOT_TIMEOUT;
                        GenUDPSt = SM_CLOSE;
                    }
                    delay--;
                }
            }            break;        case SM_RESPONSE:
            udpPackets = UDPIsGetReady(MySock);            if (udpPackets >= BUFFER_MAX)
            {
                UDPGetArray(line_buffer, BUFFER_MAX);
                UDPDiscard();                
                if (line_buffer[0] == STX && line_buffer[BUFFER_MAX - 1] == ETX)
                {                    switch (line_buffer[CMD_INDEX])
                    {                    case WR_MEM:
                        EECON1 = PGM_WRITE;
                        WriteMem();                        break;                    case WR_CFG:                        if (!last_block_written&&!CFG_NUM)
                        {
                            WriteStart();
                            last_block_written = 1;
                            ResetBlockBuffer();
                        }
                        CFG_NUM++;
                        EECON1 = CFG_WRITE;
                        WriteCfg();                        break;                    case ER_MEM:
                        EECON1 = PGM_ERASE;
                        EraseMem();                        break;                    case RUN_APP:                        if (!last_block_written)
                        {
                            WriteStart();
                            last_block_written = 1;
                            ResetBlockBuffer();
                        }
                        GenUDPSt++;                    default:                        break;
                    }                    if (UDPIsPutReady(MySock) >= BUFFER_MAX)
                    {
                        UDPPutArray(line_buffer, BUFFER_MAX);
                        UDPFlush();
                    }
                }
            }            else
            {
                tick--;                if (tick==0)
                {
                    tick = 0x10000;                    if (delay == 0)
                    {
                        delay = BOOT_TIMEOUT;
                        GenUDPSt = SM_CLOSE;
                    }
                    delay--;
                }
            }            break;        case SM_CLOSE:            while (!TXSTAbits.TRMT);
            TXREG='>';
            UDPClose(MySock);
            MySock = INVALID_UDP_SOCKET;
            _asm                goto APP_START
            _endasm            break;
        }
    }


  如何使用 

  1. 使用MCC18编译PhnBoot_v1.0,

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

  3. 拔除pickit3烧录器

  4. 将目标板与PC的接入同一局域网,并设置PC的IP地址和目标板的IP地址为同一网域,打开PhnLoader_v1.0用户界面,选择IP, 端口,和通信协议。

  5. 点击PhnLoader_v1.0用户界面上的“.."按钮加载需要烧录的应用程序Hex文件 (注意:由于PhnBoot_v1.0占用了程序存储器头部0x2400程序字,所以应用程序编译需要设置Code offset为0x2400)。

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

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

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

  主要特性

  本PIC ethernet bootloader有以下主要特性

  1. 使用了Microchip免费的TCP/IP Stack,采用UDP协议。

  2. C语言写的,MCC18 编译。

  3. 非常容易移植。

  4. 支持FLASH烧写, 快速,占用空间小。

  5. 可支持EEPROM烧写。

  6. 支持CONFIG BITS/IDLOC 烧写。



『本文转载自网络,版权归原作者所有,如有侵权请联系删除』

热门文章 更多
8051单片机的函数发生器的设计