ARM Cortex-M0 UartGets()筆記

The Definitive Guide to the ARM Cortex-M0 中文版, 目前讀到p.15-19 談到如何讓UART在NXP LPC1114動起來,而且在重定向之後, 自己修改程式,來解決scanf()的問題,最重要的就是UartGets()

試了一下程式執行的結果,和預期不一樣,按倒退鍵,不會倒退,按del鍵,結果出現的是 [3~。想說作者很好心,很次都會故意出一些小錯誤,讓我們讀者可以玩玩找問題的遊戲。這樣不但多了一些樂趣,也可以有更深刻的體驗。後來發現不是,其實是使用的Terminal軟體不同,或者其設定不同,就會造成這些問題。

我使用Putty,預設的設定:

開除錯去看:
按倒退鍵,出現127,預期是8
按ESC,出現[3~(三個鍵),預期是27
按del,出現27,預期是沒有動作或反應

修改Putty的設定後,行為就符合預期了:


int UartGets(char dest[], int length)
{
unsigned int textlen=0; // Current text length
char ch; // current character
do {
  ch = UartGetc(); // Get a character from UART
  switch (ch) {
    case 8: // Back space
     if (textlen>0) {
       textlen--;
       UartPutc(ch); // Back space
       UartPutc(' '); // Replace last character with space on console
       UartPutc(ch); // Back space again to adjust cursor position
       }
      break;
    case 13: // Enter is pressed
     dest[textlen] = 0; // null terminate
     UartPutc(ch); // echo typed character
     break;
    case 27: // ESC is pressed
     dest[textlen] = 0; // null terminate
     UartPutc('\n');
     break;
    default: // if input length is within limit and input is valid
      if ((textlen= 0x20) & (ch < 0x7F))) // valid characters
         {
         dest[textlen] = ch; // append character to buffer
         textlen++;
         UartPutc(ch); // echo typed character
         }
      break;
     } // end switch
  } while ((ch!=13) && (ch!=27));
  if (ch==27) {
    return 1; // ESC key pressed
  } else {
    return 0; // Return key pressed
    }
}


留言

這個網誌中的熱門文章

D-BUS學習筆記

關於藍牙裝置找尋(inquiry, scan)兩三事

Cisco Switch學習筆記: EtherChannel