Использование Arduino LDR Sensor для переключения фона в обработке - PullRequest
0 голосов
/ 07 ноября 2019

Используя датчик LDR для Arduino, я хочу переключаться между двумя gif-фонами в Processing, в зависимости от интенсивности света, который воспринимает LDR. Моя настройка Arduino работает, и я вижу диапазон номеров в последовательном мониторе в зависимости от количества света, освещаемого датчиком - однако у меня возникают проблемы при обработке с переключением между фонами. Это мой первый проект, объединяющий Arduino с процессингом, поэтому, пожалуйста, прости меня, если я допустил какие-то явные ошибки.

Код Arduino

    int sensorPin = A0; // select the input pin for LDR
int sensorValue = 0; // variable to store the value coming from the sensor

void setup() {

  Serial.begin(9600); //sets serial port for communication
}

void loop() {

  sensorValue = analogRead(sensorPin); // read the value from the sensor

  Serial.println(sensorValue); //prints the values coming from the sensor on the screen

  delay(100);

}

ОбработкаКод

    //loads gif library for background

import gifAnimation.*;

Gif batmanGotham;

Gif batmanLair;

//loads Arduino 

import processing.serial.*;

Serial myPort;

int sensorValue = 0;


void setup() {

  size(1067, 800); //size of canvas

  batmanGotham = new Gif(this, "background.gif"); //set gif

  batmanGotham.play();

  batmanLair = new Gif(this, "batman_lab.gif");  //set second gif

  batmanLair.play();

  String portName = "/dev/cu.usbmodem14201";

  myPort = new Serial(this, portName, 9600);

  myPort.bufferUntil('\n');
}

void draw() {

}

void serialEvent (Serial myPort) {

  if (sensorValue > 300) {

    image(batmanLair, 0, 0);   //lays down gif background

  } else {

    image(batmanGotham, 0, 0);   //lays down gif background
  }
}

Ответы [ 2 ]

2 голосов
/ 07 ноября 2019

Вы забыли прочитать данные с последовательного порта, попробуйте добавить следующую строку в вашу serialEvent() процедуру:

byte[] buffer = new byte[2];
sensorValue   = myPort.readBytes(buffer);

в самом начале.

Как вы видите, у вас естьвосстановить данные из буфера самостоятельно. Событие запускается автоматически всякий раз, когда есть что прочитать, но вы должны взять его оттуда и сохранить или обработать.

Вы должны читать два байта за раз, чтобы учесть размер int вы отправляете с вашего Arduino.

1 голос
/ 08 ноября 2019

Маркос прав, через вас будет отправлено более двух байтов. Предположим, вы отправляете 1023, то есть фактически 4 символа (байта) + еще одну новую строку (от println).

Вы можете рисовать непрерывно и просто обновлять изображение на основе прочитанных данных,в идеале с некоторой проверкой ошибок:

   //loads gif library for background

import gifAnimation.*;

Gif batmanGotham;

Gif batmanLair;

//loads Arduino 

import processing.serial.*;

Serial myPort;

int sensorValue = 0;


void setup() {

  size(1067, 800); //size of canvas

  batmanGotham = new Gif(this, "background.gif"); //set gif

  batmanGotham.play();

  batmanLair = new Gif(this, "batman_lab.gif");  //set second gif

  batmanLair.play();

  String portName = "/dev/cu.usbmodem14201";

  try{
    myPort = new Serial(this, portName, 9600);
    myPort.bufferUntil('\n');  
  }catch(Exception e){
    println("error opening serial port: double check the cable is connected, the portName is right and SerialMonitor anything else trying to access the port is closed");
    e.printStackTrace();
  }


}

void draw() {
  if (sensorValue > 300) {

    image(batmanLair, 0, 0);   //lays down gif background

  } else {

    image(batmanGotham, 0, 0);   //lays down gif background
  }
}

void serialEvent (Serial myPort) {
  try{
    String rawString = myPort.readString();
    if(rawString != null && rawString.length() > 0){
      // remove newline
      rawString = rawString.trim();
      // parse value
      sensorValue = int(rawString);
    }
  }catch(Exception e){
    println("error parsing serial data");
    e.printStackTrace();
  }
}

Если вы хотите упростить часть Processing Serial, вы можете сделать пороговую логику для arduino и просто отправить один байт в Processing, например 1 или 0, в зависимости от того, какойизображение, которое вы хотите отобразить:

int sensorPin = A0; // select the input pin for LDR
int sensorValue = 0; // variable to store the value coming from the sensor

void setup() {

  Serial.begin(9600); //sets serial port for communication
}

void loop() {

  sensorValue = analogRead(sensorPin); // read the value from the sensor

  if(sensorValue > 0){
    Serial.print('1');
  }else{
    Serial.print('0');
  }

  delay(100);

}

Затем в обработке:

   //loads gif library for background

import gifAnimation.*;

Gif batmanGotham;

Gif batmanLair;

//loads Arduino 

import processing.serial.*;

Serial myPort;

boolean showLair;


void setup() {

  size(1067, 800); //size of canvas

  batmanGotham = new Gif(this, "background.gif"); //set gif

  batmanGotham.play();

  batmanLair = new Gif(this, "batman_lab.gif");  //set second gif

  batmanLair.play();

  String portName = "/dev/cu.usbmodem14201";

  try{
    myPort = new Serial(this, portName, 9600);
  }catch(Exception e){
    println("error opening serial port: double check the cable is connected, the portName is right and SerialMonitor anything else trying to access the port is closed");
    e.printStackTrace();
  }


}

void draw() {
  // read 1 char
  if(myPort != null && myPort.available() > 0){
    char fromArduino = myPort.read();
    showLair = (fromArduino == '1');
  }
  // update content
  if (showLair) {

    image(batmanLair, 0, 0);   //lays down gif background

  } else {

    image(batmanGotham, 0, 0);   //lays down gif background
  }
}
...