6 Ekim 2012 Cumartesi

Serial Talk with Arduino


I would say that this post is a continuation of this one . In this tutorial I have made known made an application in C # that allow sending information by serial port. But often it is useful not only send but also receive. And for that reason here is another "draws near." All source code is available here below.

The goal this time is to do something with this: 
This application was made thinking in Arduino but, obviously, it can be used with any disposivo to communicate through the serial port of the PC. 

To use the program simply set the COM port and baud rate. The program window can be resized to suit the user for optimal viewing of messages to send / receive. 

The termination character serial communication can be defined in the code that make available through the following line: 
  TERM_CHAR const string = "\ n"; 

Simply replace \ n by other characters to choose from. 

Having regard to the code used in the Talk to Arduino , the only novelty is that there is athread dedicated to receiving messages. 

Messages followed by "S" correspond to messages sent and similarly messages followed by "R" correspond to incoming messages. 

The code is sent to the Arduino just an example. In this case the goal was to get strings and give it proper treatment for the information transferred aspceto had a more human-friendly(and less machine-friendly). The protocol used can be quite different and more optimized. 
  # Define BAUD_RATE 9600 
  # Define BUF_LEN 128 
  # Define TERM_CHAR '\ n' 

  void setup () { 
  Serial.begin (BAUD_RATE); 
  } 

  int i; 
  incomingChar char, buf [BUF_LEN]; 

  void loop () { 

  / / Clean buffer 
  memset (buf, '\ 0', BUF_LEN); i = 0; 

  / / Read incoming message 
  while (Serial.available ()) { 
  incomingChar = (char) Serial.read (); 
  if (incomingChar! = i && TERM_CHAR! BUF_LEN =) 
  buf [i + +] = incomingChar; 
  else 
  break; 

  delay (1); / / wait for another byte 
  } 

  / / Your protocol goes here 
  if (strcmp (buf, "Hello Arduino!") == 0) 
  Send ("PC Hello!"); 
  else 
  if (strcmp (buf, "How are you?") == 0) 
  Send ("I'm reeeally fine."); 

  } 

  void Send (char * msg) { 
  Serial.print (msg); 
  Serial.print (TERM_CHAR); 
  } 

Hiç yorum yok: