我试图从连接到Arduino的PixyCam获取颜色x和y坐标,一切正常,但是当我打开串口时,它输出的数字和字母甚至不在代码中。
它的作用示例:
b(a right arrow) (tabbed over 2 times) 96
q(2 right arrows) (tabbed over once) 183
p(no arrows) (tabbed once) 52 (tabbed 2 times) 105
我的目标是:
X y
~ ~
B:182 5
P:23 82
O:62 140
这是我的代码
Pixy pixy;
void setup()
{
//Put your setup code here, to run once:
Serial.begin(9600);
Serial.print("Starting...\n");
Serial.print("\t\n X \t Y");
Serial.print("\t\n ~ \t ~\n");
pixy.init();
}
void loop()
{
int blocks = pixy.getBlocks();
if(pixy.getBlocks())
{
//For the color red
if (pixy.blocks[0].signature == 1)
{
Serial.print("R:\t"+ pixy.blocks[0].x);
Serial.print("\t\t");
Serial.println(pixy.blocks[0].y);
delay(500);
}
//For the color Orange
else if (pixy.blocks[0].signature == 2)
{
Serial.print("O:\t"+ pixy.blocks[0].x);
Serial.print("\t\t");
Serial.println(pixy.blocks[0].y);
delay(500);
}
//For the color Yellow
else if (pixy.blocks[0].signature == 3)
{
Serial.print("Y:\t"+ pixy.blocks[0].x);
Serial.print("\t\t");
Serial.println(pixy.blocks[0].y);
delay(500);
}
//For the color Green
else if (pixy.blocks[0].signature == 4)
{
Serial.print("G:\t"+ pixy.blocks[0].x);
Serial.print("\t\t");
Serial.println(pixy.blocks[0].y);
delay(500);
}
//For the color Cyan
else if (pixy.blocks[0].signature == 5)
{
Serial.print("C:\t"+ pixy.blocks[0].x);
Serial.print("\t");
Serial.println(pixy.blocks[0].y);
delay(500);
}
//For the color Blue
else if (pixy.blocks[0].signature == 6)
{
Serial.print("B:\t"+ pixy.blocks[0].x);
Serial.print("\t\t");
Serial.println(pixy.blocks[0].y);
delay(500);
}
//For the color Violet
else if (pixy.blocks[0].signature == 7)
{
Serial.print("V:\t"+ pixy.blocks[0].x);
Serial.print("\t\t");
Serial.println(pixy.blocks[0].y);
delay(500);
}
}
}
很抱歉,如果代码是平庸的,我是Arduino的新手/编程新手。
答案 0 :(得分:2)
尝试拆分每一行:
Serial.print("R:\t"+ pixy.blocks[0].x);
Serial.print("O:\t"+ pixy.blocks[0].x);
Serial.print("Y:\t"+ pixy.blocks[0].x);
Serial.print("G:\t"+ pixy.blocks[0].x);
Serial.print("C:\t"+ pixy.blocks[0].x);
Serial.print("B:\t"+ pixy.blocks[0].x);
Serial.print("V:\t"+ pixy.blocks[0].x);
进入(例如):
Serial.print("R:\t");
Serial.print(pixy.blocks[0].x);
我怀疑pixy.blocks[0].x
正在返回一个整数。当你在C中的字符串中添加一个整数时(可能是违反直觉的),通过字符串计算这个字符数。因为这将在"R:\t"
字符串的末尾,导致Serial.print()
从Arduino内存输出随机字符。将调用拆分为两个可以正确打印整数部分。
答案 1 :(得分:1)
实际上,我发现了什么是错的。始终建议将文本添加到字符(char)数组中。然后打印存储有文本的缓冲区(在示例代码中称为' buf')。此外,使用流畅的连续打印添加延迟(已注释)帮助。
char buf[32]; //Hold's 32 characters, or so I was told?
sprintf(buf,"Your data goes here %d",pixy.getBlock[0]);//Grabs block zero's data
//delay(500); <<< In milliseconds
Serial.print(buf);