Счетчик кнопок на Arduino не передает данные в Processing

Я хочу интегрировать элементы управления Arduino и интерфейс обработки. В моем коде Arduino есть три кнопки, подключенные к контактам a1, a0 и d0 (все они digitalRead).

int x;// assigned to A0 input
int y;// assigned to A1 input
int z; //assigned to D0 input
int votes[3]={0,0,0};

void setup() {
  // initialize the serial communication
  Serial.begin(9600);
  // wait while littleBits Arduino module is not connected to Serial Port
  // this should not take long at all
  while(!Serial);
  pinMode(0, INPUT);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
}

void loop() {
  // first we need to read the values from the BUTTONS

  x = digitalRead(A0);
  // read and assign the value of analog input A0 to the variable Hillary
  y = digitalRead(A1);
  // read and assign the value of analog input A0 to the variable Trump
  z = digitalRead(0);
  // read and assign the value of digital input 0 to the variable @FaradayScienceCat

  // next we need to send these values to Processing
  // Processing is expecting a particular format that looks like this "123,456 "
  // The format is: number | ',' | number | ' '
  // The ',' is used to tell the end of the first sensor value
  // The ' ' is used to determine the end of the second value and the packet as a whole

  if(digitalRead(A0) == HIGH) 
    {
    votes[0]=votes[0]+1;
    }
   else if(digitalRead(A1) == HIGH)
    {
    votes[1]=votes[1]+1;
    }
   else if(digitalRead(0) == HIGH) 
    {
    votes[2]=votes[2]+1;
     }

  // next we need to send these values to Processing
  // Processing is expecting a particular format that looks like this "123,456 "
  Serial.println(votes[0]);
  Serial.print(",");
  Serial.println(votes[1]);
  Serial.print(",");
  Serial.println(votes[2]);

  // After we send the values we need to wait a moment for the Serial port
  delay(200);
}

Когда кнопка нажата, она отправляется в обработку для отображения в виде гистограммы, увеличивающейся при каждом нажатии. Таким образом, если кнопка 1 нажата, первая гистограмма немного увеличится и т. д.

import processing.serial.*;

// Serial Port variables
Serial myPort;
String buff = "";
String buff1 = "";
String buff2 = "";
String buff3 = "";
int index = 0;
int NEWLINE = 10;

// Store the last 256 values from the sensors so we can draw them.
int[] valuesx = new int[256];
int[] valuesy = new int[256];
int[] valuesz = new int[256];

// setup() is where the Processing sketch is intitialized. This happens first thing
// sketch is run and only executes once.

void setup()
{ 
  // set size of the window 
  size(512, 512);
  // turn on anti-aliasing, this makes things look smoother 
  smooth();
  println(Serial.list()); // use this to determine which serial port is your Arduino
  myPort = new Serial(this, Serial.list()[0], 9600);
  myPort.bufferUntil('\n');
}

// draw() happens every frame of the sketch. This is where all the calculations are made.
// When draw() is finished executing, it executes again, over and over.
void draw() {
  // set the background to littleBits purple
  background(87, 36, 124);
  // set stroke weight(thickness of the line) to 5 pixels
  strokeWeight(5);

  for (int i = 0; i < 255; i++) {

    stroke(247, i);
    // draw the line (x1, y1, x2, y2)
    line(85, valuesx[i]+200, 85, valuesx[i + 1]+200);
    line(245, valuesy[i]+200, 245, valuesy[i + 1]+200);
    line(425, valuesz[i]+200, 425, valuesz[i + 1]+200);
  }

   // Check the Serial port for incoming data
  while (myPort.available () > 0) {
    // if there is data waiting...
    // execute serialEvent() function. Look below to see how SerialEvent works.
    serialEvent(myPort.read());
  }
}  

// serialEvent controls how incoming serial data from the littleBits Arduino module is handled
void serialEvent(int serial)
{
  if (serial != NEWLINE) {
    // Store all the characters on the line.
    buff += char(serial);
  } 
  else {
    // The end of each line is marked by two characters, a carriage
    // return and a newline.  We're here because we've gotten a newline,
    // but we still need to strip off the carriage return.
    buff = buff.substring(0, buff.length()-1);
    index = buff.indexOf(",");
    buff1 = buff.substring(0, index);
    buff2 = buff.substring(index+1, buff.length());
    buff3 = buff.substring(index+2, buff.length());

    // Parse the String into an integer.  We divide by 4 because
    // analog inputs go from 0 to 1023 while colors in Processing
    // only go from 0 to 255.
    int x = Integer.parseInt(buff1)/2;
    int y = Integer.parseInt(buff2)/2;
    int z = Integer.parseInt(buff3)/2;

    // Clear the value of "buff"
    buff = "";

    // Shift over the existing values to make room for the new one.
    for (int i = 0; i < 255; i++)
    {
      valuesx[i] = valuesx[i + 1];
      valuesy[i] = valuesy[i + 1];
      valuesz[i] = valuesz[i + 1];
    }

    // Add the received value to the array.
    valuesx[255] = x;
    valuesy[255] = y;
    valuesz[255] = z;
  }
}

К сожалению, когда я нажимаю кнопку, в ProCessing ничего не отображается.


person ksenia    schedule 21.07.2016    source источник


Ответы (2)


Вы только читаете из последовательного порта один раз, в функции setup().

Глядя на ваш последний вопрос, похоже, вы забыли свою функцию serialEvent().

person Kevin Workman    schedule 21.07.2016
comment
Я добавил запятую в код Arduino, так что теперь он прослушивает ее, но на гистограмме все еще нет изменений ... Я чувствую, что проблема здесь? строка(85, значенияx[i]+200, 85, значенияx[i + 1]+200); строка(245, значенияy[i]+200, 245, значенияy[i + 1]+200); строка(425, значенияz[i]+200, 425, значенияz[i + 1]+200); - person ksenia; 21.07.2016
comment
@K.Nadkina Как ты думаешь, почему твоя проблема именно в этом? Ваш код никогда не получает последовательное событие. Вы никогда не устанавливаете значения в своих массивах. Вот что вызывает вашу ошибку. Когда вы нажимаете кнопку, какой код в вашем скетче Processing вы ожидаете запустить? - person Kevin Workman; 21.07.2016
comment
хорошо, я обновил последовательное событие в обработке ниже. См. код выше. Проблема все еще существует. Вы видите, в чем потенциальная проблема может быть прямо сейчас? - person ksenia; 21.07.2016
comment
@K.Nadkina В вашем последнем вопросе я попросил вас распечатать значение buff. Вы сделали это? Какова ценность? - person Kevin Workman; 21.07.2016
comment
Извините, я не понимаю, почему мне нужно распечатать значение баффа. Не могли бы вы объяснить или предоставить пример кода? - person ksenia; 21.07.2016
comment
@K.Nadkina Основная цель - понять, что делает ваш код. Чтобы понять, что делает ваш код, нам нужно знать фактическое значение переменных. Вся ваша логика, кажется, основана на переменной buff, так что это первое, что вы должны проверить. Что вы ожидаете, что он будет содержать? Что он содержит вместо этого? Вот как вы решаете такие проблемы. - person Kevin Workman; 21.07.2016

похоже, вы забыли установить пин-режим для кнопок, которые вы используете. вы захотите использовать INPUT_PULLUP или INPUT, но я не могу вам сказать без дополнительной информации о настройке вашей кнопки.

pinMode(0, INPUT);
pinMode(A0, INPUT);
pinMode(A1, INPUT);
pinMode(0, INPUT);
pinMode(0, INPUT);
person redbow_kimee    schedule 21.07.2016