processing与arduino互动编程

Processing向串口发送数据

 1 import processing.serial.*;
 2 Serial port;
 3 String message;
 4 void setup() {
 5   message = "c";
 6   port = new Serial(this, "COM3", 9600);
 7 }
 8 
 9 void draw() {
10   port.write(message);
11 }

arduino连接的是com3,执行程序后Arduino板载的RX灯一直亮起,说明有数据在不停地发送过去。关闭程序后,RX灯熄灭。

2.3Arduino串口编程

通过头文件HardwareSerial.h中定义一个HardwareSerial类的对象serial,然后直接使用类的成员函数来实现的。

Serial.begin()  用于设置串口的比特率,除以8可得到每秒传输的字节数

Serial.end()   停止串口通信

Serial.available()  用来判断串口是否收到数据,该函数返回值为int型,不带参数

示例:从串口输出“The char I havr received:" 字符

 1 int c = 0;
 2 
 3 void setup()
 4 {
 5   Serial.begin(9600);
 6 }
 7 
 8 void loop()
 9 {
10   if (Serial.available()){
11     c = Serial.read();
12     Serial.print("The char I have received:");
13     Serial.println(c, DEC);
14   }
15   delay(200);
16 }

打开Arduino界面的串口监视器,输入任意字符,单片机收到会返回该字符的ASCII码。一次输入多个字符,会返回多个ASCII码。

2.4 Process与Arduino通信编程

实例一:在Processing界面上画一个矩形,当用鼠标单击矩形内的时候,Arduino板载的LED灯点亮,单击矩形外的时候,Arduino板载的LED熄灭。

processing代码

 1 import processing.serial.*;
 2 Serial port;
 3 
 4 void setup() {
 5   port = new Serial(this, "COM3", 9600);
 6   size(300, 300);
 7 }
 8 
 9 void draw() {
10   rect(100, 100, 50, 50);
11 }
12 
13 void mouseClicked() {
14   if ((mouseX >= 100) & (mouseX <= 150) & (mouseY >= 100) & (mouseY <= 150)) {
15     println("LED turn ON!");
16     port.write("a");
17   } else {
18     println("LED turn OFF!");
19     port.write("b");
20   }
21 }

Arduino代码

int c = 0;

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop() {
  if(Serial.available()) {
    c = Serial.read();
    if (c == 97)
      digitalWrite(13, HIGH);
    else
      digitalWrite(13, LOW);
  }
}

猜你喜欢

转载自www.cnblogs.com/zlqw/p/9044633.html