Here is another example of using arduino with the serial port. I took an example from the arduino site here, and tinkered it. I wanted to create a program to echo the actual letter that you send through the Serial Monitor program. The example on the arduino site returns the ASCII values of the characters sent, so I tinkered it to send the actual characters back. So here is the program:
* serial_echo.pde
* -----------------
* Echoes what is sent back through the serial port.
*
* http://spacetinkerer.blogspot.com
*/
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print((char)incomingByte);
}
}
The available() function returns the number of bytes (characters) available for reading in the serial port buffer. If it is zero then there is nothing to read. So the loop() runs until there is something to read. When you read something you take the number value of the character in the ASCII code. So if you just send back what you read the serial monitor will display a number. To turn that number back to a character you use a cast, the (char) thing before the variable in Serial.print(), which does just that. More on casts on wikipedia here.
You can download the code here.
No comments:
Post a Comment