通过串行端口发送整数并打印到LCD

通过串行端口发送整数并打印到LCD,c,matlab,serial-port,arduino,lcd,C,Matlab,Serial Port,Arduino,Lcd,我试图通过USB串行端口将整数从MATLAB发送到Ardunio Uno,然后在LCD上显示它们。在Arduino显示屏上,128到159之间的数字显示为63时,我遇到了一个问题 以下是我的MATLAB代码: q = serial('COM4'); % set com port location set(q,'BaudRate',9600); % set baud rate fopen(q); % open the port fprintf(q,a_number) % send the inte

我试图通过USB串行端口将整数从MATLAB发送到Ardunio Uno,然后在LCD上显示它们。在Arduino显示屏上,128到159之间的数字显示为63时,我遇到了一个问题

以下是我的MATLAB代码:

q = serial('COM4'); % set com port location
set(q,'BaudRate',9600); % set baud rate
fopen(q); % open the port
fprintf(q,a_number) % send the integer
这是我的Arduino代码:

int incomingByte = 0; // storage for integer
void serialRead () // 
{
   incomingByte = Serial.read(); // read the serial port 
   if (Serial.available() > 0) // if there is data print it to LCD
   {
      lcd.setCursor(0,1);  // set the cursor to column 0, line 1 
      lcd.print("Boot:     %");
      delay(500);
      lcd.setCursor(6,1);
      lcd.print(incomingByte,DEC); // print the Integer to the LCD
      delay(500);
   }
}
除了显示为值63的数字128到159之外,0到255之间的所有数字都正确显示


更新:我使用串行分析器在我的计算机上测试了串行端口,看起来MATLAB应该为错误发送数据负责。我单独测试了Arduino代码,它工作得非常好

解决了这个问题,在我的MATLAB代码中添加了以下行来代替fprintf行:

fwrite(q,a_number,'uint16','sync');

您的最后一句话有些矛盾:“0到255之间的所有数字都正确地显示在LDC上,我不知道为什么128到159之间的数字不正确地显示为63。”我不知道关于Arduino的任何信息,但一个简短的说明表明,Serial.read()在没有可用数据时返回-1。你没有检查这个,那么你怎么知道有可用的数据呢?@Michael Walz我已经相应地编辑了我的问题。我想说的是,128到159的数字显示为63的值不正确,0到255的所有其他数字显示为正确的值。@Lundin感谢您指出这一点。我添加了一个if语句,仅在有数据可用时显示一个值,但不幸的是,这并不能解决问题。在读取串行数据之前添加
if(Serial.available()>0)
时会发生什么情况?如果发送字节值
[0 255]
,对于Matlab端,最好使用8位类型,如
uint8
(在Arduino端,确保也只读取8位类型)。这样,您就不会因为处理器之间的endianness(字节顺序)可能不同而感到烦恼。