-2
#include <reg51.h>
#include "_LCD_R8C.c"
#define INPUT_LENGTH 11

char input[INPUT_LENGTH];  /* The input from the serial port */
int  input_pos = 0;       /* Current position to write in the input buffer */

int main()
{
  int i;

  lcd_init();
  lcd_clear();
  SCON = 0x50;
  TMOD = 0x20;                /* timer 1, mode 2, 8-bit reload */
  TH1 = 0xFD;                /* reload value for 2400 baud */
  TR1 = 1;
  TI = 1;
  RI = 1;
  while (1 == 1)
  {
    /* read the next character from the serial port */
    input[input_pos++] = getCharacter ();
    /* send it back to the original sender */
    for (i = 0; i <= input_pos; i++)
    {
      lcd_print_b(input[i]);
    }
  }
}

char getCharacter(void)
{
  char chr[INPUT_LENGTH];           /* variable to hold the new character */

  while (RI != 1) {;}
  chr[input_pos++] = SBUF;
  RI = 0;
  return (chr);
}

我尝试显示我从 rfreader 读取的 rs232 收到的号码。但是我在显示器上得到了错误的值,即 002100 而不是 0016221826。但是在超级终端上,我得到了准确的正确值,其中包含 $ 美元,即 $0016221826。

4

1 回答 1

0

首先,您确实需要采用合理的缩进样式,这段代码很难阅读。您的代码的问题是您将用户输入数组读入本地数组“chr”,然后将该数组的地址返回给 main,而不是一个字符。main() 不需要地址,它需要一个字符。不管怎样,一旦你离开了函数,数组“chr”就无效了。

您的 for 循环打印也不正确,没有任何意义。每次收到新字符时,您都会一遍又一遍地打印所有字符。

硬件或MCU可能还有其他问题,我只是修复了最明显的软件错误。

#include <reg51.h>
#include "_LCD_R8C.c"

#define INPUT_LENGTH 11


int main()
{
  char input[INPUT_LENGTH];  /* The input from the serial port */
  int  input_pos  = 0;       /* Current position to write in the input buffer */

  lcd_init();
  lcd_clear();

  SCON = 0x50;
  TMOD = 0x20;                /* timer 1, mode 2, 8-bit reload */
  TH1  = 0xFD;                /* reload value for 2400 baud */
  TR1  = 1;
  TI   = 1;
  RI   = 1;

  while(1)
  {
    /* read the next character from the serial port */
    if(input_pos < INPUT_LENGTH)    /* check for buffer overflow */        
    {
      input[input_pos] = getCharacter();
      lcd_print_b(input[input_post]);  /* only makes sense to print each character once */
      input_pos++;
    }
 }


 char getCharacter (void)
 {
   char chr          /* variable to hold the new character */

   while (RI != 1) 
     ;

   chr = SBUF;
   RI = 0;

   return(chr);
 }
于 2012-09-06T06:48:46.223 回答