⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 usb_demo.cpp

📁 ST公司upsd34XX评估板上位机源程序
💻 CPP
📖 第 1 页 / 共 4 页
字号:
            sprintf(str, "Writing flash: %d bytes remaining", (cbTemp/100)*100);
            mainForm->sbStatus->Panels->Items[0]->Text = AnsiString(str);// update text in status bar
            mainForm->Repaint(); // refresh the texts displayed on the main form

            cbTemp = cbRemaining;
        }
    }

    // Verify check sum

    REPORT_BUF statusBuf;
    if (GetStatus(&statusBuf))
    {
        if (statusBuf.report.u.status.checkSum != checkSum)
        {
            Application->MessageBox(
                "Write operation failed: the checksum calculated from\na readback does not match the checksum for the data written.",
                "Write Flash",
                MB_OK|MB_ICONEXCLAMATION);
            LeaveCriticalSection(&g_crSection);
            return FALSE;
        }
    }

    LeaveCriticalSection(&g_crSection);
    return TRUE;
}
//---------------------------------------------------------------------------


/////////////////// SectorErase()
//
// Sends a command to erase the selected flash sector.
//
// list and meaning of parameters:
// uchar flash    - flash selector, 0 = Main Flash (primary), 1 = Boot Flash (secondary)
// uchar sector   - sector selector, 0..7 for Main Flash, 0..3 for Boot flash
//
// Function returns TRUE on success, FALSE on error.

BOOL SectorErase(int flash, int sector)
{
   if (!SelectFlash(flash, sector))
   {
      return FALSE;
   }

   REPORT_BUF reportBuf;
   memset(&reportBuf, 0, sizeof(REPORT_BUF));

   // Convert sector address 0 to xdata address

   uint16 address = OffsetToAddress(flash, sector, 0);

   // Send command

   reportBuf.reportID               = 0;
   reportBuf.report.u.erase.cmd     = CMD_ERASE;
   reportBuf.report.u.erase.address = SWAP_UINT16(address);
   reportBuf.report.u.erase.flash   = (uchar) flash;

   DWORD cbWritten;
   if (!WriteFile(g_hDevice, &reportBuf, sizeof(REPORT_BUF), &cbWritten, NULL))
   {
      OnError("Error sending CMD_ERASE command.");
      return FALSE;
   }

   return TRUE;
}
//---------------------------------------------------------------------------


//---------------------------------------------------------------------------
//              MAIN IAP DEMO COMMANDS IMPLEMENTATION
//---------------------------------------------------------------------------


/////////////////// ReadData()
//
// Reads data from flash and displays it in edit controls.
//
// Function has no parameters.
// Function returns TRUE on success, FALSE on error.

BOOL ReadData()
{
   // Get specified count of how many bytes to read

   static char text[256];
   int nBytes;

   strcpy(text,mainForm->edCount->Text.c_str());
   if (!sscanf(text, "%x", &nBytes) || (nBytes > 16))
   {
      OnError("Invalid byte count field value (maximum count allowed is 16, input is HEXADECIMAL number).");
      return FALSE;
   }

   // Get specified address (offset within flash sector)

   int offset;
   strcpy(text,mainForm->edOffset->Text.c_str());
   if (!sscanf(text, "%x", &offset))
   {
      OnError("Invalid address field value.");
      return FALSE;
   }

   uchar flash = SELECTED_FLASH;
   uchar sector = SELECTED_SECTOR;

   // Select the target sector

   if (!SelectFlash(flash, sector))
   {
      return FALSE;
   }

   // Read flash

   BYTE buffer[256];
   if (!ReadFlash(flash, sector, (uint16)offset, buffer, nBytes))
   {
      return FALSE;
   }

   // Display the return values

   text[0] = 0;
   for (int i = 0; i < nBytes; i++)
   {
      sprintf(text + strlen(text), "%02X ", buffer[i]);
   }

   mainForm->edData->Text = AnsiString(text);
   return TRUE;
}
//---------------------------------------------------------------------------


/////////////////// WriteData()
//
// Reads data and length from edit controls and writes to flash.
//
// Function has no parameters.
// Function returns TRUE on success, FALSE on error.

BOOL WriteData()
{
   // Get data to write

   char text[256];
   memset(text, 0, sizeof(text));
   strcpy(text,mainForm->edData->Text.c_str());

   // Parse it for values

   BYTE buffer[256];
   int nBytes = 0;
   for (char* p = text; *p; p++)
   {
      int value;

      if (*p == ' ')
         continue;

      // Value can't be longer than two characters
      if (p[1] && (p[1] != ' '))
      {
         if (p[2] && (p[2] != ' '))
         {
            OnError("Invalid data value: value is more than two characters long.");
            return FALSE;
         }
      }

      if (!sscanf(p, "%x", &value))
      {
         OnError("Invalid data value: not a valid numeric value.");
         return FALSE;
      }
      buffer[nBytes] = (BYTE) value;
      nBytes++;
      p++;
   }

   // Set byte count text field in dialog

   sprintf(text, "%X", nBytes);
   mainForm->edCount->Text = AnsiString(text);

   if (!nBytes)
   {
      OnError("No data given to write.");
      return FALSE;
   }

   // Get specified offset within flash sector

   int offset;
   strcpy(text,mainForm->edOffset->Text.c_str());
   if (!sscanf(text, "%x", &offset))
   {
      OnError("Invalid address field value: not a numeric value.");
      return FALSE;
   }

   uchar flash = SELECTED_FLASH;
   uchar sector = SELECTED_SECTOR;

   // Select the target sector

   if (!SelectFlash(flash, sector))
   {
      return FALSE;
   }

   // Write the data

   if (!WriteFlash(flash, sector, (uint16) offset, buffer, nBytes))
   {
      return FALSE;
   }

   return TRUE;
}
//---------------------------------------------------------------------------


/////////////////// BlankCheck()
//
// Checks to see if a flash sector is blank.
//
// list and meaning of parameters:
// uchar flash    - flash selector, 0 = Main Flash (primary), 1 = Boot Flash (secondary)
// uchar sector   - sector selector, 0..7 for Main Flash, 0..3 for Boot flash
//
// Function returns TRUE on success, FALSE on error.
// The result of the test is displayed using MessageBoxes.
// "Sector is blank" means that every byte in the sector has value of 0xFF
// "Sector is not blank" means that at least one of the bytes in the sector
// has value different from 0xFF

BOOL BlankCheck(int flash, int sector)
{
   // Select target flash sector

   if (!SelectFlash(flash, sector))
   {
      return FALSE;
   }

   // Read sector into buffer

   BYTE buffer[MAX_SECTOR_SIZE];
   memset(buffer, 0xFF, sizeof(buffer));

   uint16 cbSector = SectorSize(flash, sector);

   if (!ReadFlash(flash, sector, 0, buffer, cbSector))
   {
      return FALSE;
   }

   // See if it's all FF values

   for (int i = 0; i < cbSector; i++)
   {
      if (buffer[i] != 0xFF)
      {
         char str_m[100];
         sprintf(str_m,"Sector is not blank.\nSome data found at address 0x%04X",i);
         Application->MessageBox(str_m,"Blank check result",MB_OK);
         return TRUE;
      }
   }

   Application->MessageBox("Sector is blank.", "Blank Check result", MB_OK);
   return TRUE;
}
//---------------------------------------------------------------------------


/////////////////// UploadToFile()
//
// Uploads flash contents to a hex file.
//
// list and meaning of parameters:
// uchar flash    - flash selector, 0 = Main Flash (primary), 1 = Boot Flash (secondary)
// uchar sector   - sector selector, 0..7 for Main Flash, 0..3 for Boot flash
//
// Function returns TRUE on success, FALSE on error.

BOOL UploadToFile(int flash, int sector)
{
   // Select target flash

   if (!SelectFlash(flash, sector))
   {
      return FALSE;
   }

   uint16 cbSector = SectorSize(flash, sector);

   // Read flash into buffer

   uchar buffer[MAX_SECTOR_SIZE];
   memset(buffer, 0xFF, sizeof(buffer));

   if (!ReadFlash(flash, sector, 0, buffer, cbSector))
   {
      return FALSE;
   }

   // Have user pick name of file

   if (!mainForm->SaveDialog1->Execute())
   {
      return FALSE;
   }

   // Open file

   FILE* file = fopen(mainForm->SaveDialog1->FileName.c_str(), "w");
   if (!file)
   {
      OnError("Failed to open file.");
      return FALSE;
   }

   // Write data in hex file format

   BOOL   bRet = FALSE;
   int    cbBuffer = cbSector;
   uchar* pbuf = buffer;
   uint16 addr = 0;

   while (cbBuffer)
   {
      int    cbWrite;
      char   line[256];
      char   temp[8];
      uchar  sum;

      cbWrite = ((cbBuffer > 16) ? 16 : cbBuffer);
      sprintf(line, ":%02X%04X00", cbWrite, addr);

      sum = cbWrite + ((addr & 0xFF00) >> 8) + (addr & 0xFF);

      for (int i = 0; i < cbWrite; i++, pbuf++)
      {
         sprintf(temp, "%02x", *pbuf);
         strcat(line, temp);
         sum += *pbuf;
      }
      sprintf(temp, "%02x\n", ((BYTE)(0x100 - sum))&0xFF);
      strcat(line, temp);

      fputs(line, file);

      addr += cbWrite;
      cbBuffer -= cbWrite;
      }

      fputs(":00000001FF\n", file);

      bRet = TRUE;
   fclose(file);

   return bRet;
}
//---------------------------------------------------------------------------


/////////////////// ProgramOrVerify()
//
// Programs the selected flash from a hex file or verifies that
// content matches.
//
// list and meaning of parameters:
// int flash   - flash selector, 0 = Main Flash (primary), 1 = Boot Flash (secondary)
// int sector  - sector selector, 0..7 for Main Flash, 0..3 for Boot flash
// BOOL verify - option for select the operation, TRUE for Verification, FALSE for Programming
//
// Function returns TRUE on success, FALSE on error.
// The result of the verification is displayed using MessageBoxes.

BOOL ProgramOrVerify(int flash, int sector, BOOL verify, char *filename)
{
   int i;

   if (!SelectFlash(flash, sector))
   {
      return FALSE;
   }

   // Open file

   FILE* file = fopen(filename,"r");
   if (!file)
   {
      OnError("Error opening file.");
      return FALSE;
   }

   // Read the hex file into a large memory buffer

   uint16 cbSector = SectorSize(flash, sector);

   uchar buffer[MAX_SECTOR_SIZE];
   memset(buffer, 0xFF, sizeof(buffer));
   BOOL bRet = FALSE;
      int leave_cycle = 0;
      char lineBuf[1000];
      while ((!leave_cycle) && (fgets(lineBuf, sizeof(lineBuf) - 1, file)))
      {
         BYTE   cbData;
         USHORT addr;
         BYTE   type;
         int temp, temp2, temp3; // temporary storage, function scanf requires data type of int
         addr = -1;
         BYTE   sum;
         if (sscanf(lineBuf, ":%02x%04x%02x", &temp, &temp2, &temp3) != 3)
            {
               bRet = false;
               leave_cycle = 1;
            }
         cbData = temp;
         addr = temp2;
         type = temp3;

         sum = cbData + ((addr & 0xFF00) >> 8) + (addr & 0xFF) + type;

         if (type == 1) // End of file
         {
            bRet = TRUE;
            leave_cycle = 1;
         }

        if (type == 0) // Data record
         {
            char* p = lineBuf + 9;

            for (; cbData; p+=2, cbData--, addr++)
            {
               sscanf(p, "%02x", &temp);
               *(buffer + addr) = temp;
               sum += temp;
            }

            // Read and validate checksum
            if (!sscanf(p, "%02x", &temp))
            {
               bRet = false;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -