如何解决处理:如何写串口?
|boolean squareVisible = true;
int x = 50;
int y = 50;
int w = 100;
int h = 100;
import processing.serial.*;
Serial port;
int val;
void setup() {
size(200,200);
noStroke();
fill(255,0);
rect(x,y,w,h);
port = new Serial(this,9600);
}
void draw() {
background(255);
if (squareVisible) {
fill(40,80,90);
} else {
fill(255,0);
}
rect(x,h); // Draw a square
}
void mousePressed() {
if (((mouseX > x) && (mouseX < x + w) &&
(mouseY > y) && (mouseY < y + h))) {
// if mouse clicked inside square
squareVisible = !squareVisible; // toggle square visibility
port.write(\"8\");
}
}
void mouseMoved() {
if (((mouseX > x) && (mouseX < x + w) &&
(mouseY > y) && (mouseY < y + h))) {
port.write(\"2\");
}
}
我全都在处理。这是一个简单的拨动开关,切换后我正尝试写入串行端口。我正在尝试将其与arduino集成,但似乎无法读取任何来自串行端口的信息。我做的每一个开关都有不同的方式写入串行端口,我有问题吗?提前致谢...
解决方法
我发现了一个问题:
port = new Serial(this,9600);
应该是port = new Serial(this,Serial.list()[0],9600);
。您缺少Serial构造函数的(重要)参数。始终在处理控制台中检查错误(查看您的代码),尤其是在代码不起作用的情况下:)
我将从处理随附的SimpleWrite示例开始,以便您首先了解处理/ Arduino之间的通信是如何工作的,然后继续进行并使用从项目中获得的知识。
基本设置是这样的:
在处理中,您可以在setup()中初始化Serial实例,在绘制中,可以使用Serial \的write()方法发送值。
在Arduino中,在setup()中初始化Serial(Serial.begin(yourBaudRate)),在loop()中检查是否有可用数据和read()值。
在Processing和Arduino中使用相同的波特率非常重要,否则您将无法识别出大量传输的数据。
另外,您也不必发送字符串,也可以发送整数,字节等。
如果要显示这些内容,请不要忘记将类型添加为Serial.print()或Serial.println()的第二个参数(例如Serial.println(myByte,BYTE);或Serial.println( myInt,DEC));
我已经在Arduino中设置了一个非常基本的草图,以便在切换正方形时使LED闪烁一次
不做其他任何事情。同样,输入的数据将在串行监视器中打印:
int int = 0; //这将存储来自Serial的值
void setup(){
pinMode(13,OUTPUT);//add an LED on PIN 13 for kicks
Serial.begin(9600);//init Serial library (make sure Processing is sending data at the same baud rate)
}
void loop(){
if(Serial.available() > 0){//look for Serial data
incoming = Serial.read();//read and store teh value
Serial.print(incoming,DEC);//print it to the Serial monitor,change DEC to the type of variable you\'re using
if(incoming == 1){//if it\'s a 1 blink once
digitalWrite(13,HIGH);
delay(500);
digitalWrite(13,LOW);
delay(500);
}
}
}
我已经调整了您的处理草图:
boolean squareVisible = true;
int x = 50;
int y = 50;
int w = 100;
int h = 100;
import processing.serial.*;
Serial port;
int val;
void setup() {
size(200,200);
noStroke();
fill(255,0);
rect(x,y,w,h);
String portName = Serial.list()[0];
port = new Serial(this,portName,9600);
}
void draw() {
background(255);
if (squareVisible) {
fill(40,80,90);
} else {
fill(255,0);
}
rect(x,h); // Draw a square
}
void mousePressed() {
if (((mouseX > x) && (mouseX < x + w) &&
(mouseY > y) && (mouseY < y + h))) {
// if mouse clicked inside square
squareVisible = !squareVisible; // toggle square visibility
if(squareVisible) port.write(0);
else port.write(1);
}
}
/*
void mouseMoved() {
if (((mouseX > x) && (mouseX < x + w) &&
(mouseY > y) && (mouseY < y + h))) {
port.write(2);
}
}*/
祝好运!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。