2012年2月13日 星期一

Homework 04: Arduino + Processing



Arduino and Processing are connected by using the "serial" object.

Homework: 04_01: Arduino sends a byte of message to Processing.

// Arduino code
int buttonState = 0;
int lastButtonState = 0;
int switchPin = 4; // Switch connected to pin 4
void setup() {
pinMode(switchPin, INPUT); // Set pin 0 as an input
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
 int val;
 buttonState =digitalRead(switchPin);

if (buttonState != lastButtonState) { // If switch is ON,
  if (buttonState == HIGH)
     val=1;
   else  // If the switch is not ON,
     val=0;
Serial.write(val);
//Serial.println(val);
}

lastButtonState = buttonState;
delay(100); // Wait 100 milliseconds
}

// Processing code
import processing.serial.*;
Serial port; // Create object from Serial class
int val; // Data received from the serial port
void setup() {
size(200, 200);
frameRate(10);
// Open the port that the board is connected to and use the same speed (9600 bps)
println(Serial.list());
String portName = Serial.list()[0];
//where 0 is dependent on the "com" port number.

port = new Serial(this, portName, 9600);
}
void draw() {
if (0 < port.available()) { // If data is available,
val = port.read(); // read it and store it in val
}
background(255); // Set background to white
if (val == 0) { // If the serial value is 0,
fill(0); // set fill to black
} else { // If the serial value is not 0,
fill(204); // set fill to light gray
}
rect(50, 50, 100, 100);
}

// Arduino circuit
 Add a button in the bread board and connect the button to pin 4 of Arduino.


Homework:04_02: Processing sends a a byte of message to Arduino.
1. Go to Page 653 and Page 654 of the Processing_handbook pdf file.
2. Copy the code "Example 3A" and "Example 3B" for Arduino and Processing, respectively.
3. Modify the statement in Processing
int ledPin = 4;
into
int ledPin = 10;
and
port=new Serial(this, 9600)
into
println(Serial.list());
String portName = Serial.list()[0];
port = new Serial(this, portName, 9600);

where 0 is dependent on the "com" port number.

Homework:04_03:
1. Download the code form webhd.mcu.edu.tw using the group name "im2009".
2. Design a circuit with four buttons in Arduino.
3. Play the game and trace theses codes of Processing and Arduino.

沒有留言:

張貼留言