We basically looked at the Arduino Uno and the coding platform, and some simple setting with the Arduino pins, such as #define directive, void setup and void loop, which is all good fun.
Although I can understand everything in the section, I can tell why the code is set to be in some certain way, I am still quite far from writing my own code without looking at some references. which is why I need to learn more about it and practice more of it too.
Later on that section, Tom gave an example of cooperating Arduino with Processing, using 2 anolog reads and a digital read, with serial port to draw on Processing.
The following codes are from Tom.
Arduino:
#define X_POT A0#define Y_POT A1#define CLR_BTN 7void setup() {pinMode( X_POT, INPUT );pinMode( Y_POT, INPUT );pinMode( CLR_BTN, INPUT );Serial.begin( 9600 );}void loop() {Serial.print( analogRead( X_POT ) );Serial.print( "," );Serial.print( analogRead( Y_POT ) );Serial.print( "," );Serial.print( digitalRead( CLR_BTN ) );Serial.println();}In the Serial.Print(",") means show a comma in between each variable onSerial MonitorSerial.println() means to create a new line after the each run.Processing:import processing.serial.*;Serial arduino;int x = 0;int y = 0;int prev_x = 0;int prev_y = 0;void setup() {// Create a VGA canvassize( 800, 600 );// Get a list of serial portsString ports[] = Serial.list();int id = 0;// Find an Arduino tty.usb* portfor ( int i = 0; i < ports.length; i++ ) {if ( ports[i].indexOf( "tty.usb" ) != -1 )id = i;}// Connect to the Arduinoprintln( "Connecting to: " + ports[id] );arduino = new Serial( this, ports[id], 9600 );// Start looking for dataarduino.bufferUntil( '\n' );// Set background colourbackground( 204 );// Set line thicknessstrokeWeight( 2 );}void draw() {// Turn on strokestroke( 0 );// Draw a line from current to previous X,Yline( x, y, prev_x, prev_y );// Store X,Y position for next frameprev_x = x;prev_y = y;// Set the fill colour to transparent whitefill( 255, 255, 255, 2 );// Turn off strokenoStroke();// Fill screen with transparent whiterect( 0, 0, width, height );}// New Serial Data Eventvoid serialEvent(Serial p) {// Trim white space and split data on commasString[] data = split( trim( p.readString() ), ',' );// If there are 3 bits of data process it.if ( data.length == 3 ) {// Update X/Y positions for drawingx = int( map ( int( data[0] ), 0, 1024, 0, width ) );y = int( map ( int( data[1] ), 0, 1024, 0, height ) );// If 3rd data item is 1 clear the screenif ( int( data[2] ) == 1 ) {background( 204 );}}}// Key Press Eventvoid keyPressed() {// If key is s then save image of canvasif ( key == 's' ) {saveFrame();println( "Saved" );}}I know the program Processing, but only had a chance to use it for once or twice,therefore I am not exactly clear why is it coded inthis way but I guess this is something I will and keen to learn in thefuture.
No comments:
Post a Comment