数组从1开始,而不是0 [英] Array starts at 1 and not 0
问题描述
我按照论坛成员之前的建议放弃了使用gets(),并使用getchar取得了很好的进展。但是又出现了另一个问题。
在下面的代码中,我希望传入的串行数据放在comin [0]的数组中,然后是comin [1],然后是comin [但是,当进入isr并且传入的数据加载到comin [1]时,索引会立即变为1。
索引是isr的本地索引,而不是在其他任何地方使用。
comin填入isr,然后在程序中使用。
谢谢
*** *********************************************** *** ***************************************
static char comin [3]; //这是在程序的顶部声明
。
。
。
void uart_rx_isr(void)interrupt 4 using 3 //这是isr
{
char index; // = 0;
EA = 0;
如果(RI == 1)/ *如果设置了RI则执行RxD例程,否则跳过并退出* /
do
{
comin [index] =(getchar());
index ++;
}
while(index< 4);
RI = LOW; / *清除RI中断标志并退出* /
EA = 1;
}
I dropped the use of gets() as advised earlier by a forum member and made good progress using getchar. But another problem popped up.
In the code below, I would expect incoming serial data to be placed in the array at comin[0] and then comin[1] and then comin[2] etc. However, what happens is index immeadiately goes to 1 upon entering the isr and the incoming data gets loaded into comin[1].
index is local to the isr and not used anywhere else.
comin is filled in the isr and then used later in the program.
Thanks
************************************************** **************************************
static char comin[3]; // this is declared at the top of the program
.
.
.
void uart_rx_isr (void) interrupt 4 using 3 //this is the isr
{
char index; //=0;
EA=0;
if (RI==1) /* if RI is set then execute the RxD routine, else jump over and exit*/
do
{
comin[index] = (getchar());
index++;
}
while (index<4);
RI = LOW; /* clear the RI interrupt flag and exit */
EA=1;
}
推荐答案
我认为是getchar()是这样一个功能,它继续从键盘读取数据,当你输入一个字符,然后按下输入键然后输入键也作为另一个输入实例,即输入键被加载到comin [1]作为一个字符''\ n''所以你应该使用swictch satatement来处理这种情况或尝试scanf ..
the reson i think is that getchar() is such a function that it continuly reads data from the keyboard and when u enter a character and then pres enter key then that enter key is also took as another instance of input i.e the input key is loaded to comin[1] as a character ''\n'' so u should use a swictch satatement that wud deal with this case or try scanf..
char index; // = 0;
所以你没有用零初始化它,它可以是1或-1或其他什么。顺便说一下,在isr中执行像getchar()这样的潜在阻塞函数是错误的。
char index; //=0;
So you did not initialize it with zero, and it can be 1 or -1 or whatever. Btw, executing potentially blocking functions like getchar() within isr is the wrong way.
你需要做两个修正:
1. char index = 0; //你必须将索引初始化为0;
2. getchar(); //在if(RI == 1)之前将此行放在isr函数中的任何位置。
修正理由2由zeeshan708给出。您可能在调用isr函数之前在函数中输入了一些数据,因此您需要使最后按下的回车键的效果无效。
Two corrections u need to do :
1. char index = 0; // you have to initialise index to 0;
2. getchar(); // Put this line anywhere in your isr function before "if(RI==1)".
Reason for correction 2 is given by zeeshan708. You might be entering some data in your function before calling isr function, therefore you need to nullify effect of last pressed enter key.
这篇关于数组从1开始,而不是0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!