Cronaca della salute pubblica

Questa mattina mi reco presso l’Istituto Dermatologico S. Gallicano di Roma per un trattamento di crioterapia. Sulla mia impegnativa ci sono indicati tre appuntamenti a distanza di alcuni giorni (tralascio un certo numero di dettagli che potete immaginare sulla prenotazione). Alla cassa mi rilasciano quietanza di pagamento e al mio turno entro nell’ambulatorio.

Il medico mi chiede se ho le copie della quietanza. Che copie? Quelle che dovrà portare quando verrà ai prossimi appuntamenti, no? E come faccio ad averle? Le deve chiedere alla cassa, no? Io? Le devo chiedere io? Non dovrebbe essere la cassa a darmele, se sono necessarie? Ma è ovvio che sono necessarie. Lei deve capire che quando tornerà la prossima volta dovrà portarmi un pezzo di carta come questo no?

Ah, già! Che sciocco che sono. Devo capirlo. Che ci volete fare. Sono solo un fisico. A tanto non ci arrivo…

Pensate che io credevo che funzionasse tutto in un’altra maniera, visto che, all’atto della prenotazione, mi avevano dato un numero. Pensavo che con quel numero si potesse andare su un servizio Internet attraverso il quale avrei potuto pagare la prestazione con carta di credito o altro metodo. In seguito al pagamento avrei potuto ricevere un codice che il medico avrebbe potuto chiedermi per accertare l’avvenuto pagamento, come fa il controllore di un treno che chiede il codice di prenotazione al passeggero: si dice paperless, perché non si spreca carta, inchiostro, tempo e spazio (la struttura trattiene copia dei pagamenti, certamente per accatastarli inutilmente in qualche prezioso locale). Ma che cretino che sono: credevo forse di vivere nel futuro? Queste cose si vedono solo nei film di fantascienza!

Qualcuno dirà che questa cosa che ho reso pubblica è inutile. Non cambierà niente. Eppure solo pochi giorni fa avevo inutilmente tentato di fare una prenotazione via Internet invece che chiamando il CUP, ma mi ero scontrato con il fatto di non essere in possesso di un famigerato codice assistito e avevo trovato questo post: http://www.rainwiz.com/2011/08/25/il-codice-assistito-la-privacy-e-i-servizi-on-line-della-regione-lazio/.

Non ci crederete, ma oggi sono riuscito ad accedere senza quel codice! Ma guardate che non ho mica detto che funziona, eh? Badate bene. Non è che con quel servizio puoi prenotare o disdire un appuntamento. Puoi solo chiedere di essere richiamato per farlo. Chissà se lo faranno. Intanto, il fatto che non mi abbiano chiesto il codice assistito è un passo avanti…

Annunci

Using DC motors with Arduino

In one of my last posts I have shown how to drive a servo motor. Servo motors comes in two flavours: the standard servo motors can be set such that they reach a given position and maintain it; the continuous rotation servo can rotate continuously at a given speed.

DC motors are very similar to continuous rotation servo motors, in fact. With respect to the latter, DC motor technology is much simpler and, as a consequence, these motors are cheaper than servos. As suggested by their name, DC motors need just a DC voltage source to run, so there is no need to use any PWM pin. They just have two wires to be connected to a voltage source. The direction of rotation depend on how you connect the wires to the voltage source. Reversing the polarity of the power makes the motor run in the opposite direction. The speed of a DC motor depends on the applied voltage: the higher the voltage, the higher the speed. Motor specifications tell you in which voltage range it operates: below the minimum voltage the motor will probably do not move at all or they move with lot of difficulty; above the maximum voltage you seriously risk to damage it.

Some DC motor, as the one we used for our tests, comes with a gear embedded in their body: gears make the motors more powerful, but slower.

If, for any reason, you need to control the rotation of a DC motor using Arduino, in principle it would be enough to connect one of the motor leads to the GND pin and the other to any digital pin. Setting the pin to LOW the motor doesn’t move. Setting the pin to HIGH the motor runs if 5V is in its range. Given the fact that the direction of rotation depends on the polarity of the voltage, inverting the wires makes the motor rotate in the opposite direction.

In some cases, however, this very simple schema cannot work: manifestly it does not work if 5V are not enough to run the motor; moreover, the maximum current that an Arduino pin can provide is 40 mA (but it is recommended to not exceed 20 mA) and it may not be sufficient to run the motor. In those cases you need an external power source. You cannot use Arduino as the power source, but you can use it as the driver of the motor, controlling an external power source used to feed the motor. Suppose, for example, that you need at least 9V to run your motor. You can use Arduino to realise a sort of switch that stays open until a given digital pin is set to HIGH. As soon as that pin flips from LOW to HIGH, the switch closes and the motor is connected to the power source.

Of course you can use a relays to this purpose, but we are going to illustrate the use of a transistor to obtain the same result. Understanding how to use transistors is always a good idea, even if you are not going to use them: knowledge is power!

Transistors can be thought as a sort of switches. In fact transistors may act both as amplifiers as well as switches, depending on how they are polarised. If you want to understand how transistors work in a non technical manner you can read my article published on ‘The Physics Teacher‘ (Giovanni Organtini, “A flush toilet model for the transistor”, Phys. Teach. 50, 221 (2012); http://dx.doi.org/10.1119/1.3694073). In order to understand this post you don’t need to understand how transistor work: it is enough to know that they behave like a switch. The switch connects the transistor emitterwith its collector and its operation is driven by its base. Consider the following circuit.

 

DCmotorCircuitSchema.png

The Arduino board is used just to provide a digital signal on a given pin (pin 9 in the example). This pin is connected to a resistor (whose value is not very important: its purpose is just to limit the current flowing out of the pin) that, in turn, is connected to the base of a transistor. If no current flows to the transistor base, the transistor is said to be in interdiction and acts as an open switch between the emitter and the collector. In our schema the motor is connected to a 9V battery trough the transistor, but you can imagine the transistor being substituted by an open switch. The Arduino ground is in common with the 9V minus lead.

As soon as you make enough current flowing into the transistor base, the transistor goes in saturation and acts as a closed switch. In that case the transistor emitter (the lower lead with the arrow in the schema) appears to be short circuited with its collector (the top lead, connected to the motor). In this case the current can flow from the battery and feed the motor that starts running.

Below you can see a Fritzing model of the device where you can see that the base of the transistor is its central lead; the emitter is on the left, while the collector is on the right

DCmotorCircuit.png

Below you can see our actual setup.

IMG_20160317_183148.jpg

In order to identify the collector, the base and the emitter of a transistor you must refer to its data sheet. There are common rules among producers, allowing you to identify the leads looking at the transistor shape (the one shown in the picture above is called TO-92). However, it is always a good idea to check the pinout on the specific transistor data sheet, because not all the manufacturers may use the same pinout for the same enclosure. The actual pinout, in fact, depends also on the transistor type.

There are two types of transistors: NPN and PNP. Transistors are made out of three semiconductor slices and semiconductors comes in two flavours: N-type and P-type semiconductors. In N-type semiconductors the current carriers are electrons, while in P-type semiconductors the current is due to holes (lack of electrons). In NPN transistors the base is made of a P-type semiconductor, while in PNP ones the base is an N-type semiconductor.

In the above example we showed how to use an NPN transistor. If you are going to use a PNP one, you should connect the collector to the positive lead of the battery and the emitter to the motor, while the second lead of the motor goes directly to ground.

Working with motors

In certain cases you may need to use motors for different purposes. Depending on the experiment or the device you are building, the type of motor to use can be different. In this series of posts I will show you how to use those motors with Arduino.

Servo Motors

Servo motors are motors for which you can control accurately enough the speed and the angle of rotation. They can be used to precisely move parts in your device. For examples, in physics experiment you can use a servo motor to hold a ball in a given position and release it at a given time to study its motion.

As most of the motors, servo motors can just rotate around their axis. However, with a bit of mechanics you can realise any kind of movement. To have an idea of what you can do with a rotating axis and some mechanics, just read the article on http://makezine.com/2015/04/20/understand-1700-mechanical-linkages-helpful-animations/.

Controlling a servo motor is incredibly easy with Arduino. Servo motors have three wires: usually coloured in black, red and white. The black one must be connected to the GND pin of the Arduino, while the red one to the 5V pin. They are used to feed the motor with some power. The third wire is used to control it. Any servo motor works receiving voltage pulses of a given width. Pulses are repeated at regular intervals (e.g. 20 ms), while the duration of a single pulse determines the rotation angle of the motor around its axis or its speed.

Given the working principle of a servo motor, you will not be surprised to know that you need to connect the control wire to one of the PWM (Pulse Width Modulation) pins of Arduino. PWM pins can be configured such that they provide voltage pulses at given interval with the chosen duty cycle. The duty cycle of a PWM pin is the faction of time for which the pin is at its highest voltage. An excellent tutorial on PWM pins is given here.

Putting the pin to zero makes the PWM pin to stay off, while putting it at its maximum value of 255 makes the pin to stay always on, i.e. with a duty cycle of 100%. In order to observe a square wave on the pin you must put it at 128, such that f=128/255=0.5 and the duty cycle is 50%. Any other number makes the pin to produce a square wave whose pulse width ranges from 0 to T, where T depends on the Arduino flavour. On the Arduino UNO T is about 2 ms.

With Arduino you don’t need to compute the values yourself to control a servo motor. The Servo library is in fact available for use and provides all the relevant configurations automatically. Consider the following sketch:

Servo myservo;

void setup() {
  myservo.attach(9);
}

void loop() {
  myservo.write(90);
  delay(1500);
  myservo.write(0);
  delay(1500);
}

The attach() method in setup() just tells Arduino to which pin the motor is attached, represented by the object myservo, defined as a member of the main class (Servo myservo). In the example the servo is attached to pin 9. You can then provide an angle, in degrees, to the write() method. Its effect depends on which type of servo motor you have.

There are, in fact, two types of servo motors: continuous rotation and standard. The write() command makes a standard servo rotate of the specified angle. A call to

  myservo.write(90);

with a standard servo makes it rotate of 90 degrees. With the above sketch a servo of this type rotates of 90 degrees, then holds that position for 1.5 s, before returning at its initial position, where it stays for 1.5 s. Being in the loop the above rotations are repeated continuously.

When a servo motor of this type is powered and is receiving a train of pulses, it resists to forces applied to it holding its position. Of course you cannot apply forces too large, if you do not want to damage your servo. The maximum torque you can exert on the servo axis is one of the characteristics you can find on the servo data sheet.

The maximum torque is usually measured in kg·cm and is the product of the mass of a weight suspended at a given distance on a beam mounted on the motor axis. Using a servo whose maximum torque is 10 kg·cm you can suspend 10 kg at a distance of 1 cm from the axis as well as 1 kg at 10 cm. The larger the distance, the lower the weight the servo can tolerate. Needless to say, it is not a good idea to use a servo close to its limit. If you need a given torque, choose a servo that can tolerate at least twice that torque.

In order to compute the torque in N·cm it is enough to multiply the torque in kg·cm by 9.8, i.e. by the gravitational acceleration. In this case a servo whose maximum torque is 10 kg·cm can tolerate a force acting 1 cm far from the axis of 10·9.8=98 N, or a force of 9.8 N acting at a distance of 10 cm from the axis.

Continuos rotation servo motors, instead, rotate clockwise or anticlockwise until they are powered. The number passed to the write() method represents the rotation speed: numbers from 0 to 89 make the motor axis rotate anticlockwise (seen from above), while numbers from 91 to 180 make it rotating clockwise. The maximum speed is attained for 0 or 180. The higher the number, the slower the speed if the number is less than 90. On the contrary, if the number is larger than 90, the speed increases with the number. Setting the speed at 90 makes the servo stop rotating. In the above sketch, then the servo rotates anticlockwise for 1.5 s, then stops for other 1.5 s and so on.

Here you can find the motor we used for our tests, but it is plenty of them in the Farnell Electronics store. Here is a video showing our continuous rotation servo working with the sketch outlined above.

This post appears on the Element14 Arduino Blog, who partly sponsored it, and its content will be included in my Scientific Arduino publication.

 

Using magnetic sensors to make kinematic’s experiments

This time I’m going to introduce the usage of a kind of magnetic sensors called digital magnetoresistive sensors. Magnetoresistive sensors are based on a property of several materials called magnetoresistance, consisting in the variation of their electrical resistivity when placed in a magnetic field. In practice, the current flow through a magnetoresistive wire depends on the strength and on the orientation of an external magnetic field. The adjective “digital” in the name of these sensors refers to the fact that they provide just two states: either they are sensing a magnetic field or they are not. In other words, they are not able to provide a precise and accurate measurement of the strength of any external magnetic field: they only react to magnetic fields stronger than a given threshold, providing a sort of signal that can be only somewhat proportional to its strength. In most cases these devices are sensitive to the magnetic field only if it is oriented in a given direction (typically parallel to one of the sides of their package).

The Honeywell 2SS52M is a device that belongs to the class of digital magnetoresistive sensors. It comes in a compact package with three pins (see picture): two of which are used to bias it (GND and Vcc), 2ss52m-imagewhile the third one is its “output”.  The device is sensitive to magnetic fields oriented such that they are parallel to the longest side of its package (the white arrow in the figure). Being the sensor omnipolar, the orientation of the magnetic field doesn’t matter: either south-north or north-south alignment triggers the device.

When the external magnetic field in the given direction is strong enough, the device works as a sink for the current. There are, in fact, two kinds of sensors: those whose output mode is source and those whose output mode is sink. A source is a point from which current flows from the device; a sink, on the contrary, is a point to which current flows. In order to operate a sink sensor, you need an external power supply to be connected to the sink through a resistor. If no magnetic field is detected, the sink works as an open switch and current does not flow from the power supply to the device. When a magnetic field is measured, instead, the sink acts as a closed switch and some current flows from the external power supply to the device.

According to the Ohm’s Law, when a current I flows through a resistor R, the voltage drop across it is V=RI. In order to tell if the device is sensing a magnetic field, it is enough to measure V: if it is zero, no external magnetic field is present (apart, of course, the earth’s magnetic field); if a strong enough magnetic field is placed close to the sensor you should be able to measure a voltage V.

schematic_bb

We can use an Arduino board to build a device that is able to tell you when a magnet is close to a given position (see the schematic above). The 2SS52M can be operated with a wide variety of input voltages (from 3.8 V up to 30 V). Connecting its leftmost pin to the Arduino ground (black wire) and its rightmost pin to the Arduino 5V pin (red wire) is enough to make it working. Then, we can use the Arduino 3.3V pin as an external power supply: connecting this pin by the blue wire to the central pin of the sensor will make some current flowing from Arduino to the device. It is important to limit such a current that must not exceed the maximum current that the Arduino board can provide through its pins: 200 mA. That means that we must connect the 2SS52M central pin to the 3.3V Arduino pin by means of a resistor of at least

R = V/I = 3.3/0.2=16.5 Ω

Of course, since we do not need a large current flowing, using much higher values is recommended: this way the current flowing through the resistor will be much less, reducing power consumption and heating. For example, using a 2 kΩ resistor will cause a current of I = V/R = 3.3/2000=1.65 mA from Arduino to the sensor. On the other hand, the voltage drop across the resistor will still be 3.3V, independently of the current.

In the above schema we show a possible alternative: the resistor through which the current flows from the Arduino to the sink is made by the series of two resistors. We then measure the voltage drop across one of them (we then expect that we are going to read 3.3/2=1.65 V). There is no special reason to do that, but to show how a voltage divider works!

The tricky part comes when trying to measure the voltage drop across the resistor. Voltages can be measured using the Arduino analog pins A0-A5. They measure a voltage up to 5 V with respect to the Arduino ground. However, the voltage drop across the resistor cannot be measured relative to it. Let’s try to understand why. In the figure below you can see a schematic of our circuit.

2ss52mVwrong

The magnetic sensor is represented as a box connected to the ground and the 5V pin of the Arduino board. The sink is in fact a transistor that conducts when a magnet is close to the sensor and does not if the magnet is far from it. It is connected through a chain of resistors to the 3.3V Arduino pin. If you try to measure the voltage between the ground (i.e. the sink pin) and the resistor lead connected to the Arduino pin you always see 3.3 V, irrespective of the presence of a magnet close to the sensor, since such a potential is always there with respect to ground.

If, however, you measure the voltage drop across the resistor, i.e. as shown in the picture below,

2ss52mVright

you would see 0 V if no current is drawn from the 3.3 V pin to the sink, while you can measure 3.3 V in the opposite case. We must then measure the voltage difference between the leads of the resistors. To do that we can measure the potentials V0 and V1 at the two leads of the resistor with respect to the Arduino ground and obtain the voltage drop as V=V1-V0. We can, then, measure the voltage V0 connecting one lead of the resistor to the Arduino A0 pin (blue wire), and the voltage V1 connecting the other resistor lead to the Arduino A1 pin (orange wire).

 

magnetsThis device can be used as a proximity sensor. Fix the 2SS52M to something and a small magnet (see, e.g., the small neodymium magnets in the picture) to something else: when the magnet is close enough to the sensor it gives you a signal. In the Arduino sketch you can tell when the magnetic field is sensed waiting for a voltage drop different from zero using a function like this:

void waitUntilSensed() {
 int j = 0;
 int thr = 100 + analogRead(A0); // get the "zero" level
 while (j < thr) {
   j = analogRead(A1);
 }  
 return;
}

When entering into the function, the first operation is to measure the voltage at A0, that is expected to be the same of A1, using the analogRead() function We then just continuously read the A1 pin until its value exceeds those of A0 plus 100 (or any other large enough value). The function returns as soon as a magnetic field is detected.

With two such devices you can build a system with which you can measure the speed of a cart or of a falling object. Fix a small magnet to the cart and two 2SS52M sensors on a rail at a reasonable small distance x (e.g. 5 cm) with respect to each other.

With the Arduino connected to the sensors you can measure the times of passage of the cart in front of the first and the second sensor: t0 and t1. The time needed to the cart to travel for the corresponding distance x is t=t1-t0, then its average speed is v=x/t. Look at the following sketch.

// the sensor reading for which we can consider it as triggered
#define THRESHOLD 100
// the distance between sensors (in m)
#define S10 0.05

void sense(int pin, long int &t, long int &duration, 
           float &resolution) {
 /*
   This method return the time at which a magnetic field was
   sensed by a device read on pin
 
   The signal is measured with respect to A0
 */
 int j = 0;
 int thr = THRESHOLD + analogRead(A0); // get the "zero" level
 while (j < thr) {
   j = analogRead(pin);
 }
 // get the time at which the signal starts rising
 long int lead = micros(); 
 while (j > thr) {
   j = analogRead(pin); 
 }
 // get the time at which the signal fall down
 long int trail = micros(); 
 t = (trail + lead)/2; 
 duration = trail - lead; 
 resolution = duration/sqrt(12); 
}

void loop() {
 // measures the times of passage
 int t0, w0, sigma0;
 int t1, w1, sigma1;
 int t0 = sense(A1, t0, w0, sigma0);
 int t1 = sense(A2, t1, w1, sigma1);
 double v = S10/(t1-t0);
 ...
}

The sense() method waits until a non-zero voltage is provided from the sensor connected to the given pin. The micros() function returns the number of microseconds elapsed since the beginning of the sketch. Then then sense() method provides a measurement of the time at which a magnet passed in front of the corresponding sensor, the duration of the pulse and its error (given by the statistical theory as the width of the pulse divided by the square root of 12). The ampersand in front of the parameters in the function tells the compiler to pass the address of the memory to the function and not its value, such that the readings are all passed to the variables used in the loop() function.

In fact we measure the time at which the voltage between A0 and another pin becomes different from zero, then we wait until it becomes zero again (in the second while loop). Measuring the time at which the signal starts to be non zero and the one at which it returns to zero, we can assume that the magnet passed in front of the sensor at a time given by the average of the two times. The duration of the passage is given by the difference of the two times.

Measuring the times of passage in front of two sensors we are then able to tell the speed of the cart. With three or more sensors, you can then measure the speed at various positions od an object to study its motion. With such a system you can do many physics experiments, in fact.

The cost of such a system can be below 40 EUR, while a professional system to make the same experiments with a comparable precision may cost from hundreds to even thousands of euros!

According to my very preliminary tests, I was able to trigger the device using a small neodymium magnet (4 mm diameter) when it was at about 2-3 cm distance from the sensor. My plan is to make a systematic measurement campaign that will be reported on my free e-book on scientific uses of Arduino boards. The e-book is in preparation and there is a very preliminary version here.

This post was kindly supported by Farnell and can be found on their blog Element14.

Getting data over the Internet with Arduino

In my previous post on the subject I showed how to configure the Arduino Ethernet shield, in such a way you can save a lot of memory. Now it’s time to use the shield for something useful.

Arduino is mostly used to take data from sensors and to drive actuators to perform actions (such as motors, servos, relays, etc.). In this post we are going to use Arduino to collect some data (e.g. temperatures) and store them on a computer disk for subsequent analysis. As a physics teacher, in fact, I am interested in using Arduino as a laboratory tool and in physics you always collect data from experiments to be analysed offline.

Then, suppose you want to perform the following calorimetry experiment: take a resistor and wrap it in a waterproof material; then connect its leads to a voltage generator and make current flow through it. If R is the resistance of the device and V the voltage across its leads, the Ohm’s Law states that the current flowing is I=V/R. The resistor dissipates heat, because of the Joule’s effect, as W=RI2, where W is the amount of energy per unit time. If you plunge the resistor into water, the energy released by the resistor causes the heating of the water and you expect that the temperature of the water raises linearly with time.

You can perform this experiment using an LM35 connected to an Arduino to measure the water temperature versus time (the sensor leads must be made waterproof, of course, e.g. using some heat-shrink tubing). An Ethernet shield can then be used to send data to a computer.

Let’ start looking at the Arduino sketch, shown below.

#include <Ethernet.h>
#include <SPI.h>

#define PORT 5000
#define LM35PIN A0

byte mac[] = {0x5e, 0xa4, 0x18, 0xf0, 0x8a, 0xf6};
IPAddress arduinoIP(192, 168, 1, 67);
IPAddress dnsIP(192, 168, 1, 1);
IPAddress gatewayIP(192, 168, 1, 1);
IPAddress subnetIP(255, 255, 255, 0);

EthernetServer server(PORT);
boolean notYetConnected;

void setup() {
  Ethernet.begin(mac, arduinoIP, dnsIP, gatewayIP, subnetIP);
  notYetConnected = true;
}

void loop() {
    int i = 0;
    EthernetClient client = server.available();
    if (client) {
      if (notYetConnected) {
        client.println("Welcome!");
        notYetConnected = false;
      }
      if (client.available()) {
        unsigned long now = millis();
        int lm35 = analogRead(LM35PIN);
        now += millis();
        double T = 5000.*lm35/10240.;
        server.print(0.5*now);
        server.print(" ");
        server.println(T);
      }
    }
} 

The first include directives are needed to use the Ethernet shield. Then we define two symbols: PORT is used to send data over the Internet, LM35PIN represents the Arduino pin to which the LM35 sensor is connected.

Besides the addresses used to configure the Ethernet shield (see my previous post), a number of data members are defined: in particular, the EthernetServer object called server is instantiated, listening on port PORT. This creates an object in the Arduino memory that connects to the Internet and waits for signals on the given port, represented as an integer (5000 in the example).

The setup() method just initialise variables and configure the Ethernet shield. The most interesting part is in the loop() method. Here we instantiate (create) an object called client of class EthernetClient. Such an object is returned by the server object that continuously polls the port to which is connected. If no client is connected, the server returns NULL. Then, as soon as client is found to be not NULL, and available for communication, we can send and receive data to/from it.

Before sending data we must get them: first of all we obtain the current time as the number of milliseconds elapsed since the beginning of the execution of the sketch (we don’t care about the absolute time of the event). This time is returned by the function millis() and is represented as an unsigned long integer, i.e. a binary code of 32 bits. With 32 bits, the highest number that can be represented is 232-1= 4294967295. Dividing this number by 86400 (the number of seconds in a day) and by 1000 we get about 50: this is the number of days during which the millis() can work without reaching the overflow condition. In other words, there is plenty of time to perform our experiment.

Then we get the reading from the LM35 sensor using analogRead and measure the time again. Averaging the last time with the one previously measured provides a better estimate of the time of reading. Note that, in between, we just read raw data, in such a way we minimise the time spent in data acquisition and obtain the time with as much precision as possible. Computing the temperature in degrees is made after getting the time: the analog pin reading is a 10 bits binary number: its highest value (1024) corresponds to an input of 5 V, i.e. 5000 mV. The actual temperature, in Celsius, can be obtained reading the output voltage of the sensor divided by 10.

To transmit data to a remote client, it’s enough to call the print method of the server object. We then print the time reading, a blank and the actual temperature. Without any delay in the loop(), the sketch will read temperatures at a rate of one measurement every few milliseconds (quite fast, indeed).

In order to collect those data on a computer you need an Internet client that connects to the Arduino port 5000, writes some data on that port to announce it (knock, knock) and waits for data. An example of such a program in C is below.

#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>

#define PORT 5000
#define ADDRESS "192.168.1.67"

int main() {
  int len;
  int i;

  /* create socket */
  int sock = socket(AF_INET , SOCK_STREAM , 0);
  if (sock <= 0) {
    printf("Can't create socket. Error");
    return -1;
  }

  struct sockaddr_in server;
  server.sin_addr.s_addr = inet_addr(ADDRESS);
  server.sin_family = AF_INET;
  server.sin_port = htons(PORT);

  /* connect */
  if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0) {
    printf("can't connect to the server. Error");
    return -1;
  }

  printf("CONNECTED: hit return to start DAQ\n");

  char message[255];
  scanf("%s", message);
  send(sock, message, strlen(message), 0);

  /* read */
  while (1) {
    unsigned char c;
    recv(sock, &c, sizeof(unsigned char), 0);
    printf("%c", c);
  }

  return 0;
}

Briefly, we first create a so-called socket to make a connection between the client and the server (the Arduino). We must connect the socket to the same port to which the server is listening at. Once connected, with scanf we just read a string from the keyboard and send it to the server. This way the server answer and data acquisition starts. Data sent from the server are read with the recv statement (one character at a time). In the above example the reading loop lasts forever and just print characters on screen. You can, of course, write data on a file until some event happens (e.g. key pressed, maximum number of data received, etc.).

This post was kindly sponsored by Farnell Element14. You can find all the electronics components described above on their online shop.

The Minchioduino

There are words, in Italian, that are not very polite, who becomes funny and acceptable when they change gender. That’s the case for “minchio” (pronounced minkio), used to give a name to something that does not have a name or for which you don’t know it.

A friend of mine bought, few weeks ago, a device to control remotely the air conditioners in his house on the beach. The device was supposed to learn from any remote controller and replicate its behaviour. It can be controlled from a phone using SMS. Sadly, that device did not work for my friend. In fact it works fine with all other appliances (TV, VCR, etc.), but for the air conditioners.

I then proposed to build it from scratch using an Arduino, an IR sensor, an IR LED and a GSM shield. We tested a prototype of it as follows: after a bit of hacking of the Shirriff’s libraries for IR remotes, we were able to read the whole set of codes produced by the air conditioner remote controller (air conditioners’ codes are much longer than TV ones); we then tried to mimic them using our LED, but unfortunately it didn’t work, too. Hard to say why.

However, a maker never gives up: failure is not an option! Hence I switched to plan B. I opened the remote DSC_0399controller and found the contacts corresponding to each key. A picture of the remote controller board is on the left: pressing a key makes a short circuit between two tracks on the board (the black ones). Such tracks are made of a conductive paint on top of the copper tracks behind them. They are separated from them by means of a thin isolation layer. I then carefully removed, usingDSC_0401 (1) sand paper, both the conductive tracks and the isolation layer in order to access the copper tracks. You can see the result in the photo on the right. The conductive paint connects with copper tracks where you can see those small copper dots in the picture: making a short circuit between two appropriate contacts produces the same effect of pressing a key.

DSC_0406 DSC_0408 (1)

This way, I could solder wires on the board. Since the tracks are quite fragile, I fixed the wires along the tracks using some wax dropped from a candle (quite smart, uh? See pictures). Each pair of wires were connected to the pins of a CD4066, an integrated circuit with four  switches that can be controlled by means of a digital signal. I used two CD4066 (I needed to switch the air conditioners on to heat and to cool, to switch it off, to increase and decrease the temperature).

The inputs for the CD4066 is driven by an Arduino YUN. It also reads an LM35 sensor to get the current temperature. The YUN is the ideal board because it connects to WiFi, that is available in my friend’s home. It also run a custom Linux version on which I can run a python script. We called such a system: the minchioduino.

Using the techniques explained in a previous post of mine, I was able to do the following: the Arduino continuously  polls the twitter timeline of my friend. A command for the minchioduino consists of a tweet starting with “#minchio“, followed by the command that can be heat, cool, off, + or - (whose meaning is obvious). You can even start heating or cooling for a given amount of time, then the system automatically stops after the specified time (e.g. #minchio heat 0.2 switches on heating for 12 minutes: 0.2 hours). Once a command is got, it is removed from the twitter timeline, while the current status is posted. This way the user knows if the system accepted the command and what is the actual status.

Scienza e Arte nell’Anno della Luce

Dal 5 marzo al 21 giugno alle Scuderie del Quirinale c’è una mostra di opere di Matisse. Ne sono venuto a conoscenza grazie alla pubblicità esposta un un autobus in servizio che mi precedeva mentre tornavo a casa dal lavoro (vedi foto). La DSC_0433pubblicità mi ha subito colpito per un particolare. Per capire perché è necessario sapere che nel mio ruolo di Delegato alla Comunicazione Scientifica della Facoltà di Scienze di Sapienza Università di Roma, sto curando una mostra, che dovrebbe inaugurarsi a fine settembre, sul tema della luce, in occasione della proclamazione del 2015 come Anno Internazionale della Luce.

Quello che mi ha colpito della pubblicità è il quadro in essa riprodotto: “i pesci rossi”, realizzato nel 1911. Nel quadro Matisse dipinge una vasca con quattro pesci rossi che non si vedono solo attraverso le pareti trasparenti del vaso che li contiene, ma anche attraverso la superficie libera dell’acqua, cioè da sopra (vedi figura a destra). Di sicuro abbiamo avuto piú volte quest’esperienza che consiste nel vedere due immagini dello stesso soggetto.

matisse pesci rossiLa spiegazione del fenomeno è data dalla rifrazione che la luce subisce provenendo dai pesci e passando attraverso le pareti del recipiente dall’acqua ai nostri occhi, ma anche dagli stessi pesci agli occhi attraversando la superficie libera dell’acqua. I due percorsi sono diversi e diverso è l’angolo del quale sono deviati i raggi luminosi, ma hanno la caratteristica di partire da uno stesso punto e di raggiungere entrambi i nostri occhi facendoci percepire due immagini dello stesso soggetto.

È lo stesso fenomeno che mi permette di sorprendere i bambini delle primarie ai quali propongo il seguente esperimento: metto una moneta da due euro sul fondo di una ciotola dalle pareti opache posta al centro d’un banco. Li faccio quindi disporre in circolo attorno alla ciotola e chiedo loro di allontanarsi fino a quando non riescono piú a vedere la moneta. A questo punto verso acqua nella ciotola e magicamente la moneta riappare. A questo punto basta chiedere ai bambini di spiegare perché per far partire un’interessante dibattito scientifico che di solito giunge alla spiegazione corretta abbastanza rapidamente.

Suggerisco ai miei colleghi insegnanti di prepararsi, in occasione dell’Anno della Luce, una lezione integrata di geometria (in particolare di geometria analitica), ottica e arte: i vostri studenti non dimenticheranno piú le Leggi della rifrazione e l’opera di Matisse e di altri pittori che hanno riprodotto situazioni simili.

Di certo ancora una volta si dimostra, se mai ce ne fosse bisogno, che arte e scienza sono tra loro strettamente legate e che, al contrario di quanto pensano in troppi, non è affatto vero che le spiegazioni scientifiche distruggono la poesia di certe manifestazioni della Natura o dell’arte: semmai è vero il contrario! È proprio la possibilità di spiegare razionalmente certi fatti che li rende ancor piú affascinanti. Che meraviglia ci sarebbe se un fenomeno fosse opera di un mago o di qualcosa di soprannaturale? L’abilità di un prestigiatore desta certamente piú ammirazione della constatazione del possesso di poteri magici. Allo stesso modo la spiegazione scientifica di un fenomeno che induce sentimenti di stupore e meraviglia non fa che rafforzare questi sentimenti, dal momento che se ne possono godere tutti, ma proprio tutti, gli aspetti.

Solo chi conosce la fisica di un tramonto può apprezzarne fino in fondo la bellezza, e solo uno sciocco può pensare che la conoscenza dei fenomeni che permettono alla luce del Sole di produrre un tale meraviglia la renda arida e meno godibile di chi non la conosce.

Using the Arduino Ethernet Shield

This is the first of a series of posts devoted to the (clever) usage of Arduino, with particular emphasis to scientific tasks. These posts are kindly sponsored by Farnell Element14 and are published under their site http://www.element14.com/community/groups/arduino. The content of these posts will also be available on my free publication on using Arduino for scientific purposes: Scientific Arduino.

With respect to other similar posts, mine will not only show how to do something using Arduino: as a physics teacher I will explain why you are required to do that. In order to use any tool at its best, it is important to understand how it works behind the scenes.

As a physicist I often do measurements. Some of them can be done using an Arduino board equipped with some sensor. In fact, the advent of Arduino boards was a great advantage, mostly for those in need of cheap data acquisition systems for scientific purposes, like teachers in high schools or graduate students.

Most scientists do not take measurements, analyse them and show results in one single application: taking data can be a hard job that can keep your CPU very busy. Hence, in most cases, they just take as much data as they can out of the sensors and barely copy them as such on some mass storage device. Those data are then analysed offline using the best available tools that not necessarily coincide with the best tools for data acquisition. Presentation is a further step: once data have been analysed, the relevant results must be presented in the proper way and that job can be done with an even different technology.

In this post we show how to use Arduino to take data from some sensor and store them for further analysis. There are at least two very effective solutions: storing data onto files on SD cards or transfer data over the Internet to a remote location. The first solution is fairly simple, but data cannot be accessed during data acquisition; if the data taking persists for a long time you may prefer adopting the second solution.

Let’s then assume we are going to use an Arduino board to get the values of few sensors during an experiment that lasts for a relatively long time. Moreover, imagine that the equipment used to take data needs to be kept in conditions such that it is difficult to have access to it (e.g. a dark room, or a climatic chamber). The only solution to get the data out of the system in almost real time is to use an Ethernet shield, i.e. an Arduino shield capable to connect to the Internet and exchange data over the connection.

In order for any device to connect to the Internet, the device must acquire a unique identity on the network: the IP address. The IP address (IP stands for Internet Protocol) of a device is a unique identifier composed, in the IPv4 version of the standard, the most commonly used, of four bytes, each of which can have a value between 0 and 255. Few of them are reserved internationally and, in particular, subnetworks whose first two bytes are 192 and 168 are non-routable, i.e. packets sent over such a network cannot go beyond an Internet switch. In other words they can only reach those devices on the same physical network. That’s why devices in a home network usually have IP addresses like 192.168.x.y. The IP address of a device can be statically or dynamically assigned to it. In the first case, the device administrator tells the device its IP address: in this case the address is going to remains the same with time forever. A device not having a static IP address can ask for an IP address to any computer on the same network running as a DHCP server (Dynamic Host Configuration Protocol). Depending on the configuration of the server, available IP addresses can be assigned to the device randomly or based on the device identity.

Every physical device, in fact, brings a unique MAC (Media Access Control) address: a set of six bytes, usually expressed in the hexadecimal notation, as 5e:a4:18:f0:8a:f6. The MAC address is broadcasted over the network so that a DHCP server can choose if the request must be ignored, served using a randomly chosen address or with a fixed address.

Having an IP address in not enough for a device to communicate with other devices: data packets must reach a special device, called the gateway, that knows how to send data to the recipient. The gateway, too, must be assigned an IP address and its address must be known to the devices aiming to communicate with others.

IP addresses can be associated to strings composed of a host name and a domain name. All devices on the same network shares the same domain name, while host names are unique. A DNS (Domain Name System) is a device able to associate the IP address of any other device to its host name.

The last piece of information needed to setup a network device is the subnet mask. This is a rather technical element, but we can think of it as a way to identify the range of addresses a device can reach directly through a gateway. It is usually in the form of an IP address (but it is not, it is a mask) and often equal to 255.255.255.0, meaning that all the devices on the same network share the first three bytes of their IP address.

DSC_0434We now have all the ingredients to connect our Arduino to the network: first of all plug the Ethernet shield to the Arduino board (see picture), then connect the shield to your router using an RJ45 cable. In order to configure the device you must know the MAC address of your shield (you can find it printed on the box or you can just invent it, provided it is unique in your network). Consider the following excerpt of Arduino sketch:

#include <Ethernet.h>
#include <SPI.h>

byte macAddr[] = {0x5e, 0xa4, 0x18, 0xf0, 0x8a, 0xf6};
IPAddress arduinoIP(192, 168, 1, 67);
IPAddress dnsIP(192, 168, 1, 254);
IPAddress gatewayIP(192, 168, 1, 254);
IPAddress subnetIP(255, 255, 255, 0);

void setup() {
  Ethernet.begin(mac, arduinoIP, dnsIP, gatewayIP, subnetIP);
}

Including Ethernet.h and SPI.h is mandatory: the files contain the definition of the classes used in the sketch. The MAC address is defined as an array of bytes, each of which is represented as a pair of hexadecimal digits (thanks to the 0x preceding each number). The IP addresses of the shield, the DNS and the gateway is given as an object of class IPAddress, as well as the subnet mask. The object constructor takes four arguments that represent the four bytes of the address. Our Arduino will acquire the IP address 192.168.1.67, in a network whose gateway’s address is 192.168.1.254; the gateway works also as the DNS in this case, while the subnetwork is restricted to those devices having an IP address like 192.168.1.x.

The Ethernet.begin(mac, arduinoIP, dnsIP, gatewayIP, subnetIP) call does the job: it configures the Ethernet shield as above (and, of course, it does that in the setup() method).

In many tutorials you can easily find a much simpler configuration, that reads as

#include <Ethernet.h>
#include <SPI.h>

byte mac[] = {0x5e, 0xa4, 0x18, 0xf0, 0x8a, 0xf6};

void setup() {
 Ethernet.begin(mac);
}

In this case the Ethernet shield acquire a dynamic IP address from a DHCP server on the network. In fact the begin() method of the Ethernet class exists in many variants (it is said to be polymorphic). To many novices the last sketch may appear much more convenient: it’s simpler and shorter and does not require the knowledge of too much parameters. However, the length of the source code has mostly nothing to do with the size of the sketch in the Arduino memory.

This happens because what is stored in the Arduino memory is not the sketch as you can see here, but the sketch in machine language. Microprocessors work using electrical signals representing data and instructions. Because an electrical device can be easily found in two states (e.g. on/off), information (data and instructions) is represented as binary strings. A program for a microprocessor is then a long sequence of bits 0 and 1, not a flow of characters. The characters you write in the editor are translated into corresponding sequences of bits by the compiler (automatically invoked before uploading the sketch or when you click on the Verify button of the Arduino IDE). It is this long sequence of bits that is uploaded on the Arduino memory, not your sketch.

It happens that, in order for the shield to ask for an IP address to a DHCP server, the number of operations to perform is much larger with respect to those needed to assign manually all the parameters. As a result, the compiled program in the two cases is very different in size: the first sketch takes 2634 bytes in memory, once added an empty loop() method; the latter takes 10424 bytes! It’s about a factor 4 more space!

The memory space of an Arduino is precious, since it is not so large: as a result you may prefer the apparently longer sketch of the first example to the second one.

Now we own an Internet connected Arduino board. We are going to take data with it and send them to some remote storage for further analysis. In the next post we will show how to do that efficiently. Stay tuned…

Un corso di Arduino per fisici

Arduino è una straordinaria risorsa per un fisico: la semplicità con la quale si possono realizzare apparati di controllo e misura lo rende appetibile a ricercatori, studenti di fisica e DSC_0384insegnanti di scuola superiore. Apparati da laboratorio che una volta potevano arrivare a costare migliaia di euro oggi si possono realizzare con meno di 100 euro.

Insieme a un collega, abbiamo deciso così d’insegnare, alla fine del nostro corso di Laboratorio di Calcolo, l’uso di Arduino ai nostri studenti del primo anno del corso di laurea in Fisica.

 

Al corso, facoltativo, ha DSC_0374partecipato la metà degli studenti iscritti. Benché molto veloce (solo tre sessioni di laboratorio) il corso ha riscosso molto successo: molti studenti sono riusciti a realizzare progetti interessanti, come il theremino: una specie di theremin basato su Arduino che suona secondo la distanza cui si pone un ostacolo da un sensore ultrasonico.

Le foto e i filmati della terza e ultima sessione sono qui (vale la pena fare un giro per vedere il theremino in funzione).

Per l’occasione ho anche scritto un addendum per il libro di testo “Programmazione Scientifica” relativo alla programmazione di Arduino. Il documento si può scaricare dalla mia pagina dei documenti pubblici all’indirizzo http://www.roma1.infn.it/people/organtini/publications/ sotto la voce “Scientific Arduino“.

Blog su WordPress.com.

Su ↑