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, 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, 0);
}
rect(x, y, w, 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");
}
}
Run Code Online (Sandbox Code Playgroud)
我在加工过程中总是很棒.这是一个简单的切换开关,我正在尝试在切换时写入串口.我正在尝试将其与arduino集成,但我似乎无法读取来自串口的任何内容.有没有一种不同的方式用我的每个开关写入串口,我有什么不对吗?提前致谢...
我发现了一个问题:port = new Serial(this, 9600);应该是哪个问题port = new Serial(this, Serial.list()[0], 9600);.您错过了Serial构造函数中的(重要)参数.始终检查处理控制台中的错误(以下代码),特别是如果代码不起作用:)
我将从Processing附带的SimpleWrite示例开始,这样您就可以了解Processing/Arduino之间的通信是如何工作的,然后继续使用您在项目中获得的知识.
基本设置如下:在Processing中,在setup()中初始化Serial实例,在draw中使用Serial的write()方法发送值.在Arduino中,在setup()中初始化Serial(Serial.begin(yourBaudRate))并在循环()中检查是否有可用数据和read()值.这是非常使用的加工和Arduino的相同的波特率重要的,否则你将无法做太大的转移数据.
此外,你不会发送字符串,你也可以发送整数,字节等.如果你想显示这些,不要忘记添加类型作为Serial.print()或串行的第二个参数.println()(例如Serial.println(myByte,BYTE);或Serial.println(myInt,DEC));
我在Arduino中设置了一个非常基本的草图,当你的方块被切换时,它会闪烁一次LED,否则就什么也不做.此外,传入的数据打印在串行监视器中:int incoming = 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
而且我已经调整了你的处理草图:
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, 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, 0);
}
rect(x, y, w, 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);
}
}*/
Run Code Online (Sandbox Code Playgroud)
祝好运!
| 归档时间: |
|
| 查看次数: |
12556 次 |
| 最近记录: |