Physical Etoys tips – Time handling (part 1)


Hi everybody, today I’m going to start a new section here in our blog that I decided to call «Physical Etoys tips». The idea is to share a couple of tips I’ve learned over the years. Our first tip is about handling the passing of time inside Etoys. So let’s get started!

As we all know, Etoys objects are alive, they interact with the user and with each other and we can teach them new ways of interaction by building scripts. These scripts are not simply executed, they run inside an implicit loop (kind of like a videogame). This execution model forces the user to split complex behaviours into steps that each object will perform on every tick, without needing to specify how the iteration will be performed. Thus, Etoys doesn’t have any “forever” or “repeat until” structure (although it does have a “repeat times” structure, which is convenient but arguably unnecessary).

This ticking model does not only reinforce the idea of objects being alive but it also makes concurrency fairly simple. As in reality, where a lot of things are happening simultaneously, in Etoys all scripts are virtually running at the same time. This is a very powerful metaphor, but it has a disadvantage: it makes some time dependent tasks (such as performing an action for an amount of time or waiting a couple of seconds before doing something) a lot more difficult. Unlike other visual programming languages (such as Scratch) there is no «wait» tile in Etoys.

Instead, we have several other mechanisms to deal with time:

  1. We can represent the passing of time visually and use the “Test” tile to react to it.
  2. We can use the playfield’s «timer» slot and measure how much time has passed since it was last reset.
  3. We can use the Digital Clock special slots: “hours”, “minutes”, and “seconds”.
  4. Or we can use the Timer object (introduced in Physical Etoys 2.1).

Today, we are going to talk about the first mechanism, visually representing the passing of time. And to do it we’ll build a simple device controlled by time: a traffic light.

We’ll need:

  • An arduino.
  • A breadboard.
  • 3 leds (red, yellow, and green. Duh).
  • 3 resistors (between 200 ohm and 2 kohm are probably ok).
  • Some wires.

We’ll start by building the following circuit.

Hola a todos, hoy voy a inaugurar una nueva sección aquí en nuestro blog que he decidido llamar “Physical Etoys tips”. La idea es compartir algunos tips que fui aprendiendo en estos años. Nuestro primer tip se trata del manejo del paso del tiempo dentro de Etoys. Así que manos a la obra!

Como todos sabemos, los objetos de Etoys están vivos, interactúan entre sí y con el usuario, y podemos enseñarles nuevas formas de interacción armando guiones. Estos guiones no se ejecutan como cualquier script sino que corren en un ciclo implícito (casi como en un videojuego) donde cada ejecución es denominada “latido”. Este modelo de ejecución obliga al usuario a dividir comportamientos complejos en pasos concretos que cada objeto debe realizar en cada latido, sin tener que especificar cómo la iteración se llevará a cabo. Por esta misma razón, Etoys no tiene ninguna estructura de control “por siempre” o “repetir hasta que” (aunque sí tiene una estructura “repetir # veces”, que es conveniente pero cuya necesidad es discutible).

Este modelo de “latidos” no solo refuerza la idea de los objetos como entidades vivas sino que también hace muy fácil el pensar el comportamiento de forma concurrente. Como en la vida real, donde muchas cosas están pasando simultáneamente, en Etoys todos los guiones están virtualmente latiendo al mismo tiempo. Esta metáfora es muy poderosa pero tiene una desventaja: dificulta algunas tareas dependientes del paso del tiempo (por ejemplo, ejecutar una acción durante un tiempo determinado o esperar unos segundos antes de hacer algo). A diferencia de otros lenguajes de programación visuales (como Scratch) no hay ninguna instrucción “esperar”.

En su lugar tenemos otros mecanismos para lidiar con el tiempo:

  1. Podemos representar el paso del tiempo visualmente.
  2. Podemos usar la variable “cronómetro” del Campo de Juegos y medir cuánto tiempo pasó desde la última vez que fue reiniciado.
  3. Podemos usar las variables del Reloj Digital: “horas”, “minutos”, y “segundos”.
  4. O podemos usar el objeto Timer (introducido en Physical Etoys 2.1).

Hoy vamos a hablar del primer mecanismo, la representación visual del paso del tiempo. Y para hacerlo vamos a construir un dispositivo sencillo controlado por el tiempo: un semáforo.

Vamos a necesitar:

  • Un arduino.
  • Un protoboard.
  • 3 leds (rojo, amarillo y verde).
  • 3 resistencias (entre 200 ohm and 2 kohm deberían andar bien).
  • Unos cuantos cables.

Empezamos armando el siguiente circuito.

Traffic light_bb.3

Back in Physical Etoys, we’ll get an Arduino board from the bottom tab and we’ll connect the 3 leds. Changing the led colors and giving them proper names will allow us to identify them easily.
De vuelta en Physical Etoys, vamos a sacar un Arduino board de la pestaña inferior y le vamos a conectar 3 leds. Cambiamos los colores de los leds y les ponemos nombres para poder identificarlos rápidamente.

trafficlight-pe

leds

Now we’ll draw an object that will give us some notion of time passing, it can be almost any object but I’ll draw a small line with a blue tip on one side (this is an important detail, as we’ll see later).
Ahora vamos a dibujar un objeto que nos de alguna noción del paso del tiempo, puede ser casi cualquier objeto pero yo voy a dibujar una pequeña línea con una punta azul en uno de sus extremos (este detalle es importante, como veremos más adelante).

marker

By changing its rotation center and making a very simple script we can make our line rotate.
Cambiando su centro de rotación y con un sencillo guión podemos hacer que nuestra línea gire.

marker.3

Now we’ll use the blue tip as a marker. By testing which color is underneath the blue marker we can know which led to turn on.

For this we need an object that uses color to represent the different states of a traffic light. My drawing skills are very limited so in my case I used a couple of Sector objects (that you can find in the object catalog) to make this:

Vamos a usar la punta azul de nuestro objeto para testear qué color está debajo y así saber qué led prender.

Para esto necesitamos un objeto que use colores para representar los diferentes estados de un semáforo. Mis habilidades artísticas son bastantes limitadas por lo que, en mi caso, use varios objetos Sector, que pueden encontrar en el Catálogo de objetos.

traffic-light

As we can see, each section of the circle represents a different state of the traffic light:
Como podemos ver, cada sección del círculo representa un estado diferente del semáforo:

traffic-light.states

Then we can put our marker in the center of the object so that the blue tip can touch all the different states:
Luego ponemos nuestra línea en el centro del objeto de forma que en su giro completo pase por todos los diferentes estados.

marker.7

 

And now the only thing left is to detect which color is underneath the blue tip and turn on the appropriate led, which is as simple as this:
Y ahora lo único que falta es detectar qué color está debajo de la punta azul y prender el led correspondiente, que es tan simple como esto:

Script Editor

The result: El resultado final: http://youtu.be/5aaxMj3dPyI

And that’s all! 🙂

If you’re too lazy to do it yourself, you can download the full project here: http://tecnodacta.com.ar/gira/examples/TrafficLight.002.pe. And if you use a different mechanism to perform waiting in Etoys, please let me know in the comments.

And, as always, have fun!

¡Y eso es todo! 🙂

Si son demasiado vagos para hacerlo ustedes mismos, pueden descargar el proyecto completo aquí: http://tecnodacta.com.ar/gira/examples/TrafficLight.002.pe. Y si usan un mecanismo diferente, por favor háganmelo saber en los comentarios.

Y, como siempre, ¡que se diviertan!

 

, , ,

  1. No hay Comentarios
(No será publicado)


  1. No hay trackbacks