Tutorial.SerialCallResponseASCII History

Hide minor edits - Show changes to markup

June 09, 2010, at 10:47 PM by Equipo Traduccion -
June 09, 2010, at 10:46 PM by Equipo Traduccion -
Changed lines 16-17 from:
  • Pulsador conectado a la E/S digital 2.
to:
  • Interruptor conectado a la E/S digital 2.
Changed lines 25-27 from:

Esquema click the image to enlarge

to:

Esquema.

Pincha sobre la imagen para agrandarla.

Changed line 33 from:

Code

to:

Código:

Changed lines 40-41 from:

Processing Code

to:

Código de Processing.

Changed lines 122-125 from:

Output

As you change the value of the analog sensor, you'll get a ball moving onscreen something like this. When you turn the switch off, the ball will disappear:

to:

Salida.

Tal como cambia el valor de los sensores analógicos podrás observar movimiento en la bola de la pantalla como en la imagen siguiente. Cuando desconectas el interruptor la bola desaparece.

Changed lines 128-131 from:

Max Code

The max patch looks like this. The text of the patch is linked behind the image.

to:

Código Max.

El esquema Max queda así. El texto del esquema esta unido a la imagen.

June 09, 2010, at 10:38 PM by Equipo Traduccion -
Changed lines 5-18 from:

Un ejemplo de comunicación basada en cadenas entre la Arduino y el ordenador utilizando un metodo de llamada-respuesta (handshaking).

This program sends an ASCII string on startup and repeats that until it gets a serial response from the computer. Then it sends three sensor values as ASCII-encoded numbers, separated by commas and terminated by a linefeed and carriage return, and waits for another response from the computer.

You can use the Arduino serial monitor to view the sent data, or it can be read by Processing (see code below), Flash, PD, Max/MSP (see example below), etc. The examples below split the incoming string on the commas and convert the string into numbers again.

Compare this to the Serial call and response example. They are similar, in that both use a handshaking method, but this one encodes the sensor readings as strings, while the other sends them as binary values. While sending as ASCII-encoded strings takes more bytes, it means you can easily send values larger than 255 for each sensor reading.

Circuit

  • Analog inputs connected to analog input pin 0 and 1.
  • Switch connected to digital I/O 2.

click the image to enlarge

to:

Un ejemplo de comunicación basada en cadenas entre la Arduino y el ordenador utilizando un método de llamada-respuesta (handshaking).

Este programa envía una cadena ASCII para comenzar y la repite hasta que obtiene una respuesta desde el ordenador. Después envía tres valores, obtenidos de sensores, codificados en ASCII, separados con comas y terminados por un fin de línea con retorno de carro, y espera otra respuesta desde el ordenador.

Puedes usar el monitor serie de Arduino para ver los datos enviados. También pueden ser leidos por Processing (ver código mas adelante), Flash, PD, Max/MSP (ver ejemplo mas adelante), etc. Los ejemplos siguientes dividen las cadenas de entrada con comas y convierten la cadena en números otra vez.

Compara esto con el ejemplo de llamada y respuesta serie. Son similares, ambos utilizan el método del aptretón de manos (handshaking), pero este codifica las lecturas de los sensores como cadenas, mientras que el otro envía valores binarios. Mientras que enviar cadenas codificadas como ASCII consume más bytes, lo cual significa que puedes enviar fácilmente valores mayores de 255 para cada lectura del sensor.

Circuito.

  • Entradas analógicas conectadas a los pines analógicos 0 y 1.
  • Pulsador conectado a la E/S digital 2.

Clicar la imagen para agrandarla.

Changed lines 22-25 from:

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematic

to:

Imagen generada con Fritzing. Para ver más circuitos de ejemplo, ver la página del proyecto Fritzing.

Esquema

June 09, 2010, at 12:51 PM by Equipo Traduccion -
Changed lines 1-6 from:

Examples > Communication

Serial Call and Response (handshaking) with ASCII-encoded output

An example of string-based communication from the Arduino board to the computer using a call-and-response (handshaking) method.

to:

Ejemplos > Comunicación.

Llamada y respuesta serie (handshaking) con salida codificada en ASCII.

Un ejemplo de comunicación basada en cadenas entre la Arduino y el ordenador utilizando un metodo de llamada-respuesta (handshaking).

February 23, 2010, at 11:39 PM by Tom Igoe -
Changed lines 34-58 from:
 /*
   Serial Call and Response in ASCII
  Language: Wiring/Arduino
  
  This program sends an ASCII A (byte of value 65) on startup
  and repeats that until it gets some data in.
  Then it waits for a byte in the serial port, and 
  sends three ASCII-encoded, comma-separated sensor values, 
  truncated by a linefeed and carriage return, 
  whenever it gets a byte in.
  
  Thanks to Greg Shakar and Scott Fitzgerald for the improvements
  
   The circuit:
  * potentiometers attached to analog inputs 0 and 1 
  * pushbutton attached to digital I/O 2
  
  
  http://www.arduino.cc/en/Tutorial/SerialCallResponseASCII
  
  Created 26 Sept. 2005
  by Tom Igoe
  Modified 14 April 2009
  by Tom Igoe and Scott Fitzgerald
  */
to:
Changed lines 36-39 from:
 int firstSensor = 0;    // first analog sensor
 int secondSensor = 0;   // second analog sensor
 int thirdSensor = 0;    // digital sensor
 int inByte = 0;         // incoming serial byte
to:
Changed lines 45-51 from:
 void setup()
 {
   // start serial port at 9600 bps:
   Serial.begin(9600);
   pinMode(2, INPUT);   // digital sensor is on digital pin 2
   establishContact();  // send a byte to establish contact until receiver responds 
 }
to:
 Reads in a string of characters from a serial port until 
 it gets a linefeed (ASCII 10).  Then splits the string into 
 sections separated by commas. Then converts the sections to ints, 
 and prints them out.
Deleted lines 49-91:
Added lines 53-54:

This example code is in the public domain.

August 27, 2009, at 08:57 PM by Tom Igoe -
Changed lines 21-23 from:
to:

image developed using Fritzing. For more circuit examples, see the Fritzing project page

July 05, 2009, at 07:43 PM by Tom Igoe -
Changed lines 30-103 from:
to:
Deleted lines 104-150:

int firstSensor = 0; // first analog sensor int secondSensor = 0; // second analog sensor int thirdSensor = 0; // digital sensor int inByte = 0; // incoming serial byte

void setup() {

  // start serial port at 9600 bps:
  Serial.begin(9600);
  pinMode(2, INPUT);   // digital sensor is on digital pin 2
  establishContact();  // send a byte to establish contact until receiver responds 

}

void loop() {

  // if we get a valid byte, read analog ins:
  if (Serial.available() > 0) {
    // get incoming byte:
    inByte = Serial.read();
    // read first analog input, divide by 4 to make the range 0-255:
    firstSensor = analogRead(0)/4;
    // delay 10ms to let the ADC recover:
    delay(10);
    // read second analog input, divide by 4 to make the range 0-255:
    secondSensor = analogRead(1)/4;
    // read  switch, map it to 0 or 255L
    thirdSensor = map(digitalRead(2), 0, 1, 0, 255);  
    // send sensor values:
    Serial.print(firstSensor, DEC);
    Serial.print(",");
    Serial.print(secondSensor, DEC);
    Serial.print(",");
    Serial.println(thirdSensor, DEC);               
  }

}

void establishContact() {

  while (Serial.available() <= 0) {
    Serial.println("0,0,0");   // send an initial string
    delay(300);
  }

} @]

Processing Code

[@

June 25, 2009, at 10:50 PM by Tom Igoe -
Changed lines 17-18 from:

click the image to enlarge

to:

click the image to enlarge

Changed lines 22-28 from:
to:

Schematic click the image to enlarge

April 16, 2009, at 07:58 PM by Tom Igoe -
Changed lines 14-19 from:

Analog inputs connected to analog input pin 0 and 1. Switch connected to digital I/O 2.

to:
  • Analog inputs connected to analog input pin 0 and 1.
  • Switch connected to digital I/O 2.

click the image to enlarge

April 16, 2009, at 12:53 AM by Tom Igoe -
Changed line 157 from:
to:
April 16, 2009, at 12:52 AM by Tom Igoe -
Added lines 1-157:

Examples > Communication

Serial Call and Response (handshaking) with ASCII-encoded output

An example of string-based communication from the Arduino board to the computer using a call-and-response (handshaking) method.

This program sends an ASCII string on startup and repeats that until it gets a serial response from the computer. Then it sends three sensor values as ASCII-encoded numbers, separated by commas and terminated by a linefeed and carriage return, and waits for another response from the computer.

You can use the Arduino serial monitor to view the sent data, or it can be read by Processing (see code below), Flash, PD, Max/MSP (see example below), etc. The examples below split the incoming string on the commas and convert the string into numbers again.

Compare this to the Serial call and response example. They are similar, in that both use a handshaking method, but this one encodes the sensor readings as strings, while the other sends them as binary values. While sending as ASCII-encoded strings takes more bytes, it means you can easily send values larger than 255 for each sensor reading.

Circuit

Analog inputs connected to analog input pin 0 and 1. Switch connected to digital I/O 2.

Code

int firstSensor = 0;    // first analog sensor
int secondSensor = 0;   // second analog sensor
int thirdSensor = 0;    // digital sensor
int inByte = 0;         // incoming serial byte

void setup()
{
  // start serial port at 9600 bps:
  Serial.begin(9600);
  pinMode(2, INPUT);   // digital sensor is on digital pin 2
  establishContact();  // send a byte to establish contact until receiver responds 
}

void loop()
{
  // if we get a valid byte, read analog ins:
  if (Serial.available() > 0) {
    // get incoming byte:
    inByte = Serial.read();
    // read first analog input, divide by 4 to make the range 0-255:
    firstSensor = analogRead(0)/4;
    // delay 10ms to let the ADC recover:
    delay(10);
    // read second analog input, divide by 4 to make the range 0-255:
    secondSensor = analogRead(1)/4;
    // read  switch, map it to 0 or 255L
    thirdSensor = map(digitalRead(2), 0, 1, 0, 255);  
    // send sensor values:
    Serial.print(firstSensor, DEC);
    Serial.print(",");
    Serial.print(secondSensor, DEC);
    Serial.print(",");
    Serial.println(thirdSensor, DEC);               
  }
}

void establishContact() {
  while (Serial.available() <= 0) {
    Serial.println("0,0,0");   // send an initial string
    delay(300);
  }
}

Processing Code

/*  
 Serial Call and Response in ASCII 
 Language: Processing

 Reads in a string of characters from a serial port until 
 it gets a linefeed (ASCII 10).  Then splits the string into 
 sections separated by commas. Then converts the sections to ints, 
 and prints them out.

 created 2 Jun 2005
 modified 14 Apr 2009
 by Tom Igoe
 */

import processing.serial.*;     // import the Processing serial library
Serial myPort;                  // The serial port

float bgcolor;			// Background color
float fgcolor;			// Fill color
float xpos, ypos;	        // Starting position of the ball

void setup() {
  size(640,480);

  // List all the available serial ports
  println(Serial.list());

  // I know that the first port in the serial list on my mac
  // is always my  Arduino module, so I open Serial.list()[0].
  // Change the 0 to the appropriate number of the serial port
  // that your microcontroller is attached to.
  myPort = new Serial(this, Serial.list()[0], 9600);

  // read bytes into a buffer until you get a linefeed (ASCII 10):
  myPort.bufferUntil('\n');

  // draw with smooth edges:
  smooth();
}

void draw() {
  background(bgcolor);
  fill(fgcolor);
  // Draw the shape
  ellipse(xpos, ypos, 20, 20);
}

// serialEvent  method is run automatically by the Processing applet
// whenever the buffer reaches the  byte value set in the bufferUntil() 
// method in the setup():

void serialEvent(Serial myPort) { 
  // read the serial buffer:
  String myString = myPort.readStringUntil('\n');
  // if you got any bytes other than the linefeed:
    myString = trim(myString);

    // split the string at the commas
    // and convert the sections into integers:
    int sensors[] = int(split(myString, ','));

    // print out the values you got:
    for (int sensorNum = 0; sensorNum < sensors.length; sensorNum++) {
      print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t"); 
    }
    // add a linefeed after all the sensor values are printed:
    println();
    if (sensors.length > 1) {
      xpos = map(sensors[0], 0,1023,0,width);
      ypos = map(sensors[1], 0,1023,0,height);
      fgcolor = sensors[2];
    }
    // send a byte to ask for more data:
    myPort.write("A");
  }

Output

As you change the value of the analog sensor, you'll get a ball moving onscreen something like this. When you turn the switch off, the ball will disappear:

Max Code

The max patch looks like this. The text of the patch is linked behind the image.

Share