// 2010 mlab.taik.fi/paja // Connecting to PC // PC <-> Arduino with Messenger library // // download the library from following URL // arduino.cc/playground/Code/Messenger // // Copy the library folder following location // Arduino.app > (Show package contents) > // Contents > Resources > Java > hardware > libraries // // Example protocal using Messenger Arduino library. // Send following string from PC as a command. // Each string needs to end with carrige return (13 in ASCII) // // - Read analog values: r a [a/d (pin)] [pin] // (e.g. "r a d 7") // - Read digital pins: r d [pin] // (e.g. "r d 6") // - Write digital pin: w d [pin] [value] // (e.g. "w d 12 1") // - Write analog pins: w a [pin] [value] // (e.g. "w a 9 255") // // Do not use "Seril Monitor" in Arduino IDE. // It doesn't send "Carrige return" thus data never completes. // Inport Messenger library #include // Instantiate Messenger object with the default separator // (default is the space character) Messenger message = Messenger(); void setup(){ Serial.begin(9600); // Attach callback function to the Messenger message.attach(messageReady); } void loop(){ // The following line is the most effective way to receive incoming data while (Serial.available()) message.process(Serial.read () ); } //Function for reading proximity sensor int readPing(int pin){ int input; pinMode(pin, OUTPUT); digitalWrite(pin, LOW); delayMicroseconds(2); digitalWrite(pin, HIGH); delayMicroseconds(5); digitalWrite(pin, LOW); pinMode(pin, INPUT); input = pulseIn(pin, HIGH); return input; } //Reading incoming data void messageReady(){ // Checks to see if the message is complete if (message.available()){ // read first char switch (message.readChar()){ case 'r': readValue(); break; case 'w': writeValue(); break; default: Serial.println("1st char error"); } } } void readValue(){ int value; if (message.readChar() == 'a'){ if (message.readChar() == 'd'){ int pin = message.readInt(); if (pin == 7){ value = readPing(pin); value = map(value, 0, 8000, 0, 255); // send the value to PC followed by linefeed. Serial.println(value); } else { Serial.println("pin number error"); } } else { Serial.println("3rd char error"); } } else { Serial.println("2nd char error"); } } //Send values void writeValue(){ if(message.readChar() == 'a'){ int pin = message.readInt(); if(pin == 9){ analogWrite(pin, message.readInt()); Serial.println("ok"); } else { Serial.println("pin number error"); } } else { Serial.println("2nd char error"); } }