I’m not dead. I’m only (terribly) busy! :-(

Hi techo girls and boys!
I know…I know.
It’s more than one year that I don’t publish new posts on Garretlabs.
The fact is tied to new engagements: on the work (yes, I have a work which is very important to me and I want do the best on it…), in the frame of my family.
And I have also (of course) new musical projects,as composer and musician (please,check out my italian music site, and dowload for free all my compositions: http://www.marcolastri.net) but also as project engineer  and producer of noise machines and analog and digital synthesizers.
For example, for the friend Stefano Muscas of great band “Correlazione quantistica” (please, visit the facebook page: https://www.facebook.com/correlazionequantistica) I designed an produced a very interesting noise machine based on Arduino, called ALGOnoise.

image

I took the idea from here: http://little-scale.blogspot.it/2008/01/arduino-noise-maker-info.html but I added some modification (a repetition function, an output amplifier and some funny values changes on the resistors). I will publish very soon the result on Garretlabs (I hope)!
Here you can see a live concert of Correlazione Quantistica with Stefano playing ALGOnoise (yes, it’s the yellow box 🙂 ):

image

image

image

I’m very honoured of this collaboration!
After this I produced a modified version (the modification are: all controllers are panel mounted, the on-off button can be bypassed by a switch pedal, double resonance potentiometer and an adapter for the use with a power supplier) of the well known SparkPunk by Sparkfun. I did it for my friend Alessandro “Mazza”, the singer of the historical italian demential-metal band Tossic (http://www.tossic.it/home.html).
Here you can see the naked machine called “Mazzulator”:

image

I’m very excited to work with Alessandro, since I love his band from ever. I was 14 when I encountered for the first time the politically uncorrect world of heavy metal, and the first disc I listened was “Il Regno del Cingliale” of a strange and demential band called Tossic: one of the first italian heavy metal bands. Now I am 40, an d I love Tossic as the first day. 😉

Well… after this I produced some other music/noise machines, especially guitar effects pedals For example, I built an echo/delay and a chorus pedals for my friend and guitar player Fabiano Vezzosi, and I modified a model of the well known pedal “Metal Zone” (by Boss) in order to transform this pedal in a great fuzz effect. It kicks asses now! 😉

I also modified a great number of other guitar pedals of many friends…But in the meantime I produced also some other interesting things: for example new versions of old (diy) synthesizers. :-O

…But it is another story: keep in touch to discover this “dark side of Garretlabs”. 🙂

…and now ANOTHER music post: SparkPunk Sequencer MIDI synchronisation with Arduino (work in progress)

“Tunz-tunz-tunz” 😀 my dear geek-musician friends (female and male of course)!

Today I used for you my “house-disco-techno”-style “hello”, because today I wan t to talk you about msuica (again).

Some day ago I bought from my preferred store (RobotItaly, as you know), and I assembled two new exciting toys from Sparkfun: Sparkpunk Sound Generator and SparkPunk Sequencer.

The Sparkpunk Sound generator is a very interesting sound generator similar to the famous ATARI Punk Console,  The Sparkpunk Sequencer is a control voltage step sequencer used to control the the Sound Generator.

After the assembly of the two devices, I played some hour with these objects… but, as you know, I am a (pro-am) musician, and I would like to have a MIDI IN  port in all my instruments. Because I attach my devices to my DAW (digital audio workstation, examples are: Steinberg Cubase, Ableton Live, Cakewalk Sonar, Apple Logic Pro etc.) resident on my computers (Mac or PCs), and my DAW  is ALWAYS the MIDI master for my set of instruments. I should command the tempo, the start and stop of my devices.

Before to do my modifications, I printed (and read) the following IMPORTANT page: https://learn.sparkfun.com/tutorials/sparkpunk-sequencer-theory-and-applications-guide . So, firstly I followed the steps for modifications in the section “Synchronizing Multiple Sequencers” and I opened the connections between IN and OUT for the pins CLK, BTN, RUN, STOP (and I used jumpers in order to re-close them again, in case the sequencer isn’t controlled from another device and it used stand alone).

After this, I thinked to use an Arduino UNO as interface between my MIDI master (the DAW) and the Sparkpunk Sequencer in order to force the Sparkpunk Sequencer to follow the MIDI clock of the DAW. This is the actual setup of my experiment:

wpid-20141021_071110.jpg

Well, the PC (Midi OUT port) to Arduino (MIDI IN port) is not difficult: it’s a very simple circuit described in one of my old posts. Using this setup the MIDI in signal pin will be connected to the Arduino D10 pin via SoftSerial.

In order to build logicaly and electrically the interface between Arduino and the SparkPunk Sequencer I studied the signals on the CLK IN, BTN IN, RUN IN, STOP IN pins in the Sequencer stand-alone configuration (so the CLK IN is connected to CLK OUT, BTN IN is connected to BTN OUT, RUN IN is connected to RUN OUT and STOP IN is connected to STOP OUT… using my preferred tools: the jumpers!).

I studied them connectinfg the oscilloscope on the pins and pressing the Run button on the Sequencer in order to start and stop the sequence. These are the results (drawn by hand… it’s so stylish and vintage! 🙂 ):

wpid-storageemulated0DCIMCamera2014-10-21-07.58.15.png.pngWell… as you see the behavior is very simple. And we can simply replicate it using Arduino with the following logic:

  • When Arduino receives from DAW the MIDI START message it commands the RUN IN pin high, the STOP IN pin  low and BTN IN pin firstly high and after a short delay (I used 5ms and it works…but you can measure the real value with the oscilloscope if you want) it commands it again low.
  • When Arduino receives from DAW the MIDI STOP message it commands the RUN IN pin low, the STOP IN pin high and BTN IN pin firstly high and after a short delay (I used 5ms and it works…but you can measure the real value with the oscilloscope if you want) it commands it again low.
  • The CLK IN value is commanded by Arduino following the reception of the MIDI CLK message, in order to synchronize the tempo of Sparkpunk Sequencer with the DAW tempo.

IMPORTANT Note: a standard MIDI CLK message is sent by a DAW 24 times per quarter note. A time of 120 BPM (beats per minute) is equivalent to 120 quarter notes per minute, so in this case the DAW sends from the MIDI out (120*24)/60 messages per second. It’s too much for our Sparkpunk sequencer (if you sends all these messages to ther sequencer, it doesn’t work…and you can’t see the ON/OFF of the Rate led).

So I decided to send to the SparkPunk sequencer only one MIDI CLK message per 24 received by the MIDI IN port on Arduino. In other words Arduino decreases the rate of MIDI CLK message in order to correctly command the sequencer.

Regarding the hardware connections, the are very simple:

  • Connect the Arduino GND to a GND point of the Sparkpunk system (i.e. the ground of the Speaker port on the Sound Generator)
  • Connect the Arduino pin D2 to the RUN IN of Sparkpunk sequencer
  • Connect the Arduino pin D3 to the STOP IN of Sparkpunk sequencer
  • Connect the Arduino pin D4 to the CLK IN of Sparkpunk sequencer
  • Connect the Arduino pin D5 to the BTN IN of Sparkpunk sequencer

This is the simple Arduino code:

#include <SoftwareSerial.h>
SoftwareSerial MidiSerial(10, 11); // RX, TX

byte midi_start = 0xfa; 
byte midi_stop = 0xfc; 
byte midi_clock = 0xf8; 
byte midi_continue = 0xfb; 
int play_flag = 0;
byte data;

//synchro values
int number_of_received_clocks=0;

#define MAX_BPM 160
#define MIN_BPM 20

void setup() 
{ 
  MidiSerial.begin(31250); 
  Serial.begin(115200);
  //led 13 used for debug
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
 
  //interface --->Sparkpunk sequencer
  pinMode(2,OUTPUT);
  digitalWrite(2,LOW); //midi start sequencer
  
  //interface --->Sparkpunk sequencer
  pinMode(4,OUTPUT);
  digitalWrite(4,LOW); //midi synch sequencer
  
  //interface --->Sparkpunk sequencer
  pinMode(3,OUTPUT);
  digitalWrite(3,HIGH); //midi stop sequencer
  
  //interface --->Sparkpunk sequencer
  pinMode(5,OUTPUT);
  digitalWrite(5,LOW); //button sequencer 
}

void loop() 
{
  if(MidiSerial.available() > 0) 
  {
    data = MidiSerial.read();
     if(data == midi_start) {
       Serial.println("Start Midi");
       
       //sparkpunk interface commands
       digitalWrite(2,HIGH);//start/run sequencer
       digitalWrite(3,LOW);//stop sequencer
       digitalWrite(5,HIGH);//button sequencer
       delay(10);
       digitalWrite(5,LOW);//button sequencer
       
       play_flag = 1;
      }
      else if(data == midi_continue) 
      {
        play_flag = 1;
      }
      else if(data == midi_stop) {
        Serial.println("Stop Midi");
       
       digitalWrite(2,LOW);//start/run sequencer
       digitalWrite(3,HIGH);//stop sequencer
       digitalWrite(5,HIGH);//button sequencer
       delay(10);
       digitalWrite(5,LOW);//button sequencer
       
        play_flag = 0;
        number_of_received_clocks=0;
      }
      else if((data == midi_clock) && (play_flag == 1)) { 
        number_of_received_clocks++;
        //Serial.println(number_of_received_clocks);
        if(number_of_received_clocks%24==0) //see MIDI specification: the clock is sent 24 times for quarter note, and 120BMP=120 quarter notes for minute => BPM value= 60/time to receive 24 clocks
          {
            Sync();
          }
      } 
  }
}

void Sync() {
     digitalWrite(4, HIGH);
     delay(100); //high part of the clock square wave.
     digitalWrite(4, LOW);
}

As you see I used for the CLK IN  a square wave with a period of 200 ms (100 ms high and 100 ms low). It seems sufficient in order to command the step ahead of the sequence.

Ok, using this sketch and starting the MIDI clock on my DAW, the Sparkpunk Sequencer starts working, exactly synchronized with the DAW (and the sound is correctly generated by the Sound Generator). Modifying the BPM tempo on the DAW causes that Sparkpunk SEquencer changes correctly his tempo, and it correctly starts/stopswhen the start/stop command is sent by the DAW. Yeahhhhhhhhh! 😉

But.

Yes, there are always some “But” in my projects. 🙂

In this case there are still some strange behaviors of the system, to be investigated and debugged (also with YOUR contribution, my dear followers, if you want):

  1.  The Sequencer start working also if the POWER switch is OFF, and at the same time the . It’s clear that the sequencer and sound module takes power from the 4 pins connected to Arduino…
  2. In this condition the ouput volume of the Sound Generator is a little low… maybe the Arduino doesn’t drive the correct power supply to all the system. 😦
  3. In this condition (POWER switched OFF) only the LONG pulse works, if I switch on SHORT no sound is emitted from the Sound Generator.
  4. If I change the POWER switch from OFF to ON on the sequencer (or on the Sound Generator), only the SHORT pulse is emitted (if I switch to LONG pulse no sound is emitted)
  5. Finally, in this case (POWER switched ON on the Sequencer) the output volume of the Sound Genrator is higher.

I think all is tied to the fact that Arduino power is not sufficient to drive all the circuits (Arduino itself+MIDI interface, Sound Generator and Sequencer), and to the fact that Arduino uses 5V as HIGH value for the CLK IN, but Sparkpunk sequencer uses 7.5V. See also the paragraph called “Switch Voltage Processing” in the  https://learn.sparkfun.com/tutorials/sparkpunk-sequencer-theory-and-applications-guide …I think it is very involved in this behavior of the circuit. I’m continuing my investigation.

Another solution I would try in the near step of my experiment is to use a MOSFET commanded by Arduino pin D5 (connecting the D5 to the gate pin, the CLK IN to the source pin and the CLOCK OUT to the drain pin, for example), in order to control the synch pulse on the CLK IN connecting it to the CLK OUT (something similar to a electronic switch), in order to have the same situation of the stand alone Sequencer configuration, but generating the clock pulses using the MIDI tempo. It’s a solution similar to which used in this video from Sparkfun: https://www.youtube.com/watch?v=LUcqDM4k1gU

Well… but now, after this ordeal, I’m really ready for a glass (…a bottle?) of my preferred grappa. If you know what I mean. 😉

Bye bye daft-punk-electronicmusicians-techno friends!

 

Garretlabs meets Bleep Drum: an Arduino based drum machine with some “tasty hacks”!

Hi techno girls and techno boys!

A long time is passed from my last post, but I worked to many projects in parallel… some of these will pe published here in the near (…ehhhhmmmm!) future. 😉

Since you know I am also a musician (please visit my italian music homepage, which contains  good music to download 😉 : www.marcolastri.net), today I present you a very interesting “hack” which I’ve done starting from a beautiful device from Bleep Labs: the famous, open source and open hardware, and overall groovy Bleep Drum (a very powerful drum machine with a set of 80’s sounds):

The great Bleep Drum with MIDI controller

I asked Dr. Bleep (the Bleep Labs boss) the permission to publish here my complete hacking project….and he gave it to me with pleasure. Many thanks Dr. Bleep, you’re a great!

…So, I am here to describe you my work.

Starting from the schematic of Bleep Drum I noticed that the device used one ATMEGA 328 with 16Mhz quartz….very similar to Arduino architecture.

Then I downloaded the source code (version 07)  for Bleep Drum from the official repository…and I saw that the code was written for Arduino! 🙂 . Note the newest version of the software is the 09.

So, I replicated the embedded project using and Arduino Uno (using the well known mapping between Arduino GPIO pins and the ATMEGA328 pins) and two/three breadboards in order to apply my hacks.

Well, I wanted to add three main functionalities to Bleep Drum:

  1. A two channels-mon0 output instead the original one channel mono (because in my home studio I would like to use the output of the Bleep Drum to enter in two mono parallel filters)
  2. A Volume control
  3. A little amplification functionality

So, I worked on the output stage of the Bleep Drum and I applied the following modifications (all is designed “by hand”, as usual! 😉 ). In the drawing (made by ML 🙂 ) you can see the differences from my output stage and the original one.

wpid-storageemulated0DCIMCamera2014-10-08-10.19.22.png.png

In practice, I directly connected the output of the MPC4901 DAC to a LM358 dual operational amp, removing the resistor and the capacitor and adding a 10K potentiometer in order to control the volume.

I connected this output to the two gates of the LM358, in order to have two amplified mono channels.

Finally,  as you see,  I’ve connected the two outputs of the  LM358 gates to the jack tip and ring using two 10uF capacitors.

This is the complete Fritzing schema of the project (click to view the full size image).

BleepDrumsML_v04---FINAL---amplified+stereo_bbThis is the overall project photo:

wpid-20141008_065606.jpg

And finally, thi is the detail of the modified output stage:

wpid-20141008_065617.jpg

Regarding the Arduino software, the version 07 of the official sofware is working great on my hack! 😉

Now the output of my homemade Bleep Drum is very loud (and also “pumping”, if you know what I mean 😉 ), controlled in volume and on two mono channels. YEAHHHHHH! 🙂 So…I will use this instrument in my next electronic music compositions… because (as many of you know) I love the 80’s sounds!

Before to close this post I would like to thank again Dr. Bleep (and Bleep Labs) for his great work and for his helpfulness.

Bye bye geek-girls and geek-boys: I go to compose some good music…using my new instrument! 😉

See you soon!

 

Thermostat with Arduino and touchscreen

..Hi, dear techno frieds (obviously male and female)!
My holidays unfortunately ended some day ago, and now it’s time to restart the work in my garret (and in the Garretlabs). It seems that your visits to my little blog during August increased…so many many many (many) thanks to you all! 🙂
Once returned from my vacation, my dear friend Luka Cekka (it isn’t his real name, so he isn’t a Russian guy, but a real Italian guy, and he is a “spitting image” of Tim Robbins in “Antitrust”…have you seen the movie? 😉 ) asked to me to realize a thermostat with touch screen for his new house thermo installation.

LukaCekka

My friend Tim Robbins… ehmm Luka Cekka! 😉

So… I realized the first prototype using my old friend Arduino UNO, a temperature and humidity DHT22 sensor and the well known Adafruit TFT 2.8” touchscreen. (http://www.adafruit.com/products/1651). As usual, I bought the touchscreen from Robot Italy, my preferred italian store!
Well, in order to extract the necessary pins for DHT22 and a led (used as alarm monitor for the thermostat), I inserted between Arduino and the TFT screen a cheap proto shield (from Sparkfun) modified and transformed in a very useful “breakout shield”.

Once created the “sandwich” with Arduino, the breakout shield and the TFT, I connected to Arduino the DHT22 and the alarm led on the breadboard.
This is the Fritzing diagram (please, see the note and pay attention to the use of Arduino pins in order to drive the Adafruit TFT):

Cekka_controller_v1(one temp sensor)_bb
Regarding the software, I started using the following ad-hoc DHT22 library (and one very useful example found on internet) and verifying that the sensor was OK (and the alarm led ON/FF strategy).
Secondly, I added the code to manage the visualization of the temp on TFT, starting from the well coded examples from Adafruit libraries.
I decided to have two software modes: in the “temps” mode you can see the actual temperature acquired from DHT22. In this mode you can touch the software button “SETUP” on the touchescreen in order to enter “setup” mode. In “setup” mode you can adjust the alarm temperature using two software buttons on the touchscreen (one “+” button and one “-” button). You can return to “temps” mode touching the “TEMPS”software button. …All simple! 😉

This is the complete Arduino code for my application:

#include "DHT.h"
#include <Adafruit_GFX.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_ILI9341.h>
#include <Adafruit_STMPE610.h>

//Adafruit screen data
// This is calibration data for the raw touch data to the screen coordinates
#define TS_MINX 150
#define TS_MINY 130
#define TS_MAXX 3800
#define TS_MAXY 4000

//define screen and touch screen plus control signals
#define STMPE_CS 8
Adafruit_STMPE610 ts = Adafruit_STMPE610(STMPE_CS);
#define TFT_CS 10
#define TFT_DC 9
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

//temperatures frame
#define FRAME_X_T 80
#define FRAME_Y_T 6
#define FRAME_W_T 150
#define FRAME_H_T 150
//button frame
#define FRAME_X_B 210
#define FRAME_Y_B 180
#define FRAME_W_B 100
#define FRAME_H_B 50

//declare temp sensor
DHT dht;

//declare inital default max temp (setpoint) in order to signal an alarm
float max_temp=27.0;

//display modes--->used to define the menu (in the right-low corner) button text and behaviour
 #define MODE_TEMPS 1
 #define MODE_SETUP 2
 int current_display_mode=MODE_TEMPS;//at startup we see the temps..
 //coords and dimension for the + and - buttons, used to set max temps...
 #define X_PLUS_B 224
 #define X_MINUS_B 270
 #define Y_PLUS_B 3
 #define BUTTON_W 40
 #define BUTTON_H 35

void setup()
 {
   //serial
   Serial.begin(9600);
   Serial.println();
   Serial.println("Status\tHumidity (%)\tTemperature (C)\t(F)");
   //Use pin D2 to read temp/hum from DHT22
   dht.setup(2);
   //set pin D5 to output (alarm pin)
   pinMode(5,OUTPUT);
   
   //initialize touch screen
   tft.begin();
   if (!ts.begin()) {
      Serial.println("Unable to start touchscreen.");
   }
   else {
      Serial.println("Touchscreen started.");
   }
   tft.fillScreen(ILI9341_BLUE);
   // origin = left,top landscape (USB left upper)
   tft.setRotation(1);
   
   //draw button TS
   drawMenuButton(current_display_mode);
 }

void loop()
 {
   //set delay
   delay(dht.getMinimumSamplingPeriod());

   //get values from DHT22
   float humidity = dht.getHumidity();
   float temperature = dht.getTemperature();
   
   //debug: print value on serial
   Serial.print(dht.getStatusString());
   Serial.print("\t");
   Serial.print(humidity, 1);
   Serial.print("\t\t");
   Serial.print(temperature, 1);
   Serial.print("\t\t");
   Serial.println(dht.toFahrenheit(temperature), 1);
   
   //print value on Adafruit screen
   if (current_display_mode==MODE_TEMPS)
   {
      drawFrameT();
      RefreshTemp1Value(temperature);
   }
   else if (current_display_mode==MODE_SETUP)
   {
      //nothing
   }
   
   //Management of max temp in order to activate the alarm (led)
   if (temperature>=max_temp)
   {
      //set HIGH alarm pin (D5)
      digitalWrite(5,HIGH);
   }
   else
   {
      digitalWrite(5,LOW);
   }
 
   //Management of Adafruit touchscreen
   // See if there's any touch data for us
   if (!ts.bufferEmpty())
   {
       // Retrieve a point
       TS_Point p = ts.getPoint();
       // Scale using the calibration #'s
       // and rotate coordinate system
       p.x = map(p.x, TS_MINY, TS_MAXY, 0, tft.height());
       p.y = map(p.y, TS_MINX, TS_MAXX, 0, tft.width());
       int y = tft.height() - p.x;
       int x = p.y;

       //check if the Menu button is pressed
       if((x > FRAME_X_B) && (x < (FRAME_X_B + FRAME_W_B)))
       {
          if ((y > FRAME_Y_B) && (y <= (FRAME_Y_B + FRAME_H_B)))
          {
              if (current_display_mode==MODE_TEMPS)
              {
                  current_display_mode=MODE_SETUP;
                  tft.fillScreen(ILI9341_BLACK);
                  drawMenuButton(current_display_mode);
                  
                  //draw the Temp max set points controls
                  drawCurrentMaxTemp1(max_temp);
              }
              else
              {
                  current_display_mode=MODE_TEMPS;
                  tft.fillScreen(ILI9341_BLUE);
                  drawMenuButton(current_display_mode);
              }
          }
      }

      //check if + or - buttons are pressed and adjust max temp
      if((x > X_PLUS_B) && (x < (X_PLUS_B + 40)))
      {
          if ((y > Y_PLUS_B) && (y <= (Y_PLUS_B + 35)))
          {
             if (current_display_mode==MODE_SETUP)
             {
                max_temp=max_temp+0.5;
                tft.fillRect(6,6,X_PLUS_B-3,Y_PLUS_B+BUTTON_H,ILI9341_BLACK);
                drawCurrentMaxTemp1(max_temp);
             }
          }
      }
      
      if((x > X_MINUS_B) && (x < (X_MINUS_B + 40)))
      {
         if ((y > Y_PLUS_B) && (y <= (Y_PLUS_B + 35)))
         {
            if (current_display_mode==MODE_SETUP)
            {
                max_temp=max_temp-0.5;
                tft.fillRect(6,6,X_PLUS_B-3,Y_PLUS_B+BUTTON_H,ILI9341_BLACK);
                drawCurrentMaxTemp1(max_temp);
            }
         }
      }
   }
 }
 

//Adafruit screen functions
void RefreshTemp1Value(float value)
{
 //drawFrameT1();
 //tft.fillRect(REDBUTTON_X, REDBUTTON_Y, REDBUTTON_W, REDBUTTON_H, ILI9341_BLUE);
 tft.setCursor(6 , 6);
 tft.setTextColor(ILI9341_WHITE);
 tft.setTextSize(4);
 tft.print("T1= ");
 tft.println(value);
}

void drawFrameT()
{
 tft.fillRect(FRAME_X_T, FRAME_Y_T, FRAME_W_T, FRAME_H_T, ILI9341_BLUE);
}

void drawMenuButton(int current_mode)
{
 tft.fillRect(FRAME_X_B, FRAME_Y_B, FRAME_W_B, FRAME_H_B, ILI9341_BLUE);
 tft.drawRect(FRAME_X_B, FRAME_Y_B, FRAME_W_B, FRAME_H_B, ILI9341_BLACK);
 tft.setCursor(FRAME_X_B+ 6 , FRAME_Y_B + 15);
 tft.setTextColor(ILI9341_RED);
 tft.setTextSize(3);
 if (current_mode==MODE_TEMPS)
      tft.println("SETUP");
 else if (current_mode==MODE_SETUP)
      tft.println("TEMPS");
}
void drawCurrentMaxTemp1(float value)
{
 tft.setCursor(6 , 6);
 tft.setTextColor(ILI9341_WHITE);
 tft.setTextSize(3);
 tft.print("MAX T1=");
 tft.println(value);
 drawPlusButton(X_PLUS_B/*224*/,Y_PLUS_B/*3*/);
 drawMinusButton(X_MINUS_B/*270*/,Y_PLUS_B/*3*/);
}

void drawPlusButton(int x, int y)
{
 tft.fillRect(x, y, BUTTON_W, BUTTON_H, ILI9341_BLUE);
 tft.setCursor(x+10 , y+5);
 tft.setTextColor(ILI9341_WHITE);
 tft.setTextSize(4);
 tft.print("+");
}

void drawMinusButton(int x, int y)
{
 tft.fillRect(x, y, BUTTON_W, BUTTON_H, ILI9341_BLUE);
 tft.setCursor(x+10 , y+5);
 tft.setTextColor(ILI9341_WHITE);
 tft.setTextSize(4);
 tft.println("-");
}

Ok, these are the photos of the complete project.

wpid-storageemulated0DCIMCamera2014-09-15-17.08.25.png.png

wpid-storageemulated0DCIMCamera2014-09-10-06.39.30.png.png

Note that on the screen there are four temperature values: I’m now working on a more powerful application in order to match Luka request (he wants to use four DHT22 sensors in his house… I think I will use a input multiplexer with the Arduino UNO, or more simply an Arduino Mega! 😉 ).
But you can use this project in order to add the powerful Adafruit TFT touchscreen to your application.
Only two notes on the Adafruit TFT:
1. the screen refresh is slow (very slow in my opinion), but it’s an acceptable issue in embedded projects
2. the touchscreen is natively very sensitive to human touch, so if your touch is “too long” it will be detected as a multiple touch. You could implement some “low-pass software filter” (i.e. you could manage the touch only after a multiple touch).

Well boys and girls, now you have a thermostat with a touch screen for your hi-tech house. I hope Luka will be happy with his new toy (but I’m not sure..he is a very perfectionist guy! 😉 ).
…But attention friends, the touchscreen will record your fingerprints ;-), so clean it with attention…especially if you don’t like CSI! 🙂

Bye bye!

The GL holidays post: a multifunction anti-intrusion system using Arduino!

….Thanks God it’s holidays time, my dear geeks! 🙂

Well… during these days it isn’t a good idea to remain in a dark and little microelectronics laboratory, it’s a better solution to close your laboratory in order to go in a good house/hotel by the sea (or at the mountains)! 😉

So, today Garretlabs wants to propose you a very simple (but) all-in one solution of house anti-intrusion alarm system, based on Arduino UNO.

This basic idea is very compact (but you can add all the subsystem you invent/want):

  • we will monitoring a set of house internal doors via a “wired connection”, using the digital in/out Arduino pins in order to detect a door openting (…I confess: this is inspired from a old joke which I knew 😦 during a high school week at the mountains … as we say in Italy literally “White Week” that is “Settimana bianca”)
  • we will also manage a ultrasonic sensor in order to monitoring tha opening of another house internal door
  • in case of door opening detection, we will send an alarm email using the well known Arduino Ethernet Shield

This is, as usual, my hand-made design of the system 🙂 :

2014-07-22 09.17.29

The part list is (as usual) very short, because my goal is to use (when possible) only the parts present at the moment in my …garret! 😉

  • One Arduino UNO
  • One Arduino Ethernet shield
  • One ultrasonic sensor
  • Assorted cables (never too many! ;-))

This is the Fritzing circuit (click on the image to see it bigger):

Ultrasonic alarm v1_bb

Well, remember to the Arduino place in a safe and fixed position in the house (for exaple fixed on the roof or fixed inside a electrical box on the wall) because if someone will open one of the doors connected by wire, our goal is that the wire will be disconnected from one of the two used Arduino digital pins (in order to open the controlled signal circuit).

Now, let’s go to code some line. The ultrasonic sensor is managed by the excellent newPing library, and the code to send email using the Arduino Ethernet shield is took from the my preferred site about Arduino resources (the only and one Arduino.cc …”made in Italy” rules! :-)), and modified by myself. The specific link is the following: http://playground.arduino.cc/Code/Email.

So, this is the code.

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

#define TRIGGER_PIN 6 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 7 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

// choose the MAC!
byte mac[] = { 0x90, 0xAA, 0xAA, 0x00, 0x59, 0x67 };

// change network settings
IPAddress ip( 192, 168, 0, 30 );
IPAddress gateway( 192, 168, 0, 1 );
IPAddress subnet( 255, 255, 255, 0 );

// change to your server SMTP
char server[] = "out.alice.it"; //note I used my italian ISP provider server to send emails... :-)
EthernetClient client;
unsigned int initial_distance;
bool ULTRASONIC_ALARM_ARMED=true;
bool PERIMETRAL_ALARM_ARMED=true;
void setup()
{   
   //start ehternet and serial
   Serial.begin(9600);
   pinMode(13,OUTPUT);
   digitalWrite(13,HIGH);
   Ethernet.begin(mac, ip, gateway, gateway, subnet);
   delay(2000);
   //calibration of ultrasonic sensor
   Serial.print("Calibrating....");
   for (int i=0;i<100;i++)
   {
      delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
      unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
      initial_distance+=uS / US_ROUNDTRIP_CM;
   }
   
   initial_distance=initial_distance/100;
   Serial.print("Initial distance:");
   Serial.print(initial_distance);
   Serial.println("cm");
   digitalWrite(13,LOW);
   //setup the perimetral cable
   pinMode(10,OUTPUT);
   pinMode(11,INPUT);
   digitalWrite(10,HIGH);
}

void loop()
{  
   byte inChar;
   unsigned int distance=0;
   unsigned int medium_distance=0;
   //inChar = Serial.read();
   for (int i=0;i<20;i++)
   {
      delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
      unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
      distance+=uS / US_ROUNDTRIP_CM;
   }
   medium_distance=distance/20;
   Serial.print (medium_distance);
   Serial.println (initial_distance);
   if(medium_distance<initial_distance && ULTRASONIC_ALARM_ARMED==true) //note that you can add a threshold in order to reduce false alarms
   { 
      if(sendEmail(1)) Serial.println(F("Email sent"));
      else Serial.println(F("Email failed"));
      ULTRASONIC_ALARM_ARMED=false; //the alarm should send only one email!
   }
   else
   {
      ULTRASONIC_ALARM_ARMED=true; //re-arm the alarm!
   }
   
   if(digitalRead(11)==LOW && PERIMETRAL_ALARM_ARMED)
   {
      if(sendEmail(2)) Serial.println(F("Email sent"));
      else Serial.println(F("Email failed"));
      PERIMETRAL_ALARM_ARMED=false; //the alarm should send only one email per violation!
   }
   else
   {
      //nothing to do: note that the perimetral wire alarm cannot be auto-rearmed! :-(
   }
}

//////////////////////////////////////////////////////////////////////////////
// Send email helper functions.
// Based on: http://playground.arduino.cc/Code/Email
//////////////////////////////////////////////////////////////////////////////

byte sendEmail(int type_alarm)
{
    byte thisByte = 0;
    byte respCode;
    if(client.connect(server,25)) {
        Serial.println(F("connected"));
    } else {
       Serial.println(F("connection failed"));
       return 0;
    }
    if(!eRcv()) return 0;
    Serial.println(F("Sending helo"));
    // change to your public ip
    client.println(F("helo 1.2.3.4"));
    if(!eRcv()) return 0;
    Serial.println(F("Sending From"));
    // change to your email address (sender)
    client.println(F("MAIL From: <your_email@alice.it>"));
    if(!eRcv()) return 0;

    // change to recipient address
    Serial.println(F("Sending To"));
    client.println(F("RCPT To: <your_recipient_address@your_provider.com>"));

    if(!eRcv()) return 0;
    Serial.println(F("Sending DATA"));
    client.println(F("DATA"));
    if(!eRcv()) return 0;
    Serial.println(F("Sending email"));
    // change to recipient address
   client.println(F("To: You <your_recipient_address@your_provider.com>"));

   // change to your address
   client.println(F("From: Me <your_email@alice.it>"));
   if(type_alarm==1) //ultrasonic alarm type
   {
      client.println(F("Subject: Arduino Ultrasonic alarm!\r\n"));
     client.println(F("The Arduino Ultrasonic alarm has been powered ON!"));
   }
   else if (type_alarm==2) //perimetral alarm type
   {
      client.println(F("Subject: Arduino Perimetral alarm!\r\n"));
      client.println(F("The Arduino Perimetral alarm has been powered ON!"));
   }
   client.println(F("."));
   if(!eRcv()) return 0;
   Serial.println(F("Sending QUIT"));
   client.println(F("QUIT"));
   if(!eRcv()) return 0;
   client.stop();
   Serial.println(F("disconnected"));
   return 1;
}

byte eRcv()
{
   byte respCode;
   byte thisByte;
   int loopCount = 0;
   while(!client.available()) {
      delay(1);
      loopCount++;
      // if nothing received for 10 seconds, timeout
      if(loopCount > 10000) {
          client.stop();
          Serial.println(F("\r\nTimeout"));
          return 0;
        }
     }
   respCode = client.peek();
   while(client.available())
   {
      thisByte = client.read();
      Serial.write(thisByte);
   }
   if(respCode >= '4')
   {
      efail();
      return 0;
   }
   return 1;
}

void efail()
{
   byte thisByte = 0;
   int loopCount = 0;
   client.println(F("QUIT"));
   while(!client.available()) {
      delay(1);
      loopCount++;
      // if nothing received for 10 seconds, timeout
      if(loopCount > 10000) {
          client.stop();
          Serial.println(F("\r\nTimeout"));
          return;
      }
   }

   while(client.available())
   {
      thisByte = client.read();
      Serial.write(thisByte);
   }
   client.stop();
   Serial.println(F("disconnected"));
}

Note that I used a SMTP email server which donesn’t use SSL access. In this case the SMTP sender library doesn’t work properly.

Well.. it’s very hot in Florence. I need a cold drink and a visit to a near pool. So, I think I will shutdown my computer now.;-)

But first…I hope you will have good vacation boys and girls. Your microelectronics worm should need a little time of relax, so see you soon at the end of August with other new open source ideas!

 

MIDin: a trasmitter/receiver sytem for MIDI messages using XBee and Arduino

Hi hi-tech friends (…with a prominent geek attitude 🙂 )!

This time I would like to talk about…MUSIC! Ta-daaaa!!

As you know I am also a musician, and I produce freely downloadable music from my music website www.marcolastri.net (only italian language, sorry!  ).

I have a large set of keyboards and synthesizers in my studio, and I have also a Roland AX-7, a “wearable” MIDI controller keyboard similar to a guitar (today these instruments are called “keytars” 😉 ). This keytar is used also by the mighty Herbie Hancock…. 😉

This keytar has also a great feature: it can be power by 6 AA batteries….but you will have always the midi cable in order to command your sound generator or expander (or software synth etc.). The midi cable is a limitation to your performance freedom on stage…so I want to cut it! 😉

There are some good wireless solution off-the-shelf, for example the Mid-Air product from M-Audio….and the price is not so low. 😦

…So I want to realize a DIY solution, using two Arduinos UNO, two XBee Shields and two XBee modules: this is the Garretlabs MIDin project! Ta-daaaa!

I bought from my preferred store (www.robot-italy.com) the following components:

Then I connected these components to two Arduino UNO boards in order to realize: one component working as MIDI Receiver-XBee Sender and one component working as MIDI Sender-XBee Receiver.

Thi is the system overview…design handmade by ML! 😉

20140711_093503

First step: program the XBee modules

This is the more complex step…I don’t love it but (unfortunately) it is necessary.

We must to setup the Series 2 modules in order to enable the “AT mode” communication (the Series 2 chips support also another -more complicated- configuration, in order to realize very complex networks of XBee modules). In other words, we must to program the devices in order to simulate a point-to-point-connection, a true serial wireless connection.

The best tutorial I’ve found on the internet is the following: http://tutorial.cytron.com.my/2012/03/08/xbee-series-2-point-to-point-communication/comment-page-1/. I used it step-by-step in order to configure my XBee modules…and it worked great! 😉

Firstly I downloaded  and installed the X-CTU utility (only for Windows… 😦 ) from Digi site.

After this, I attached a wire to the RESET pin of the Arduino and I connected it to GND. Then I connected the XBee Shield with the XBee module onboard (remember to set his jumper on “USB”): this is the way to directly access the XBee modules for programming them using Arduino board USB connection. In other words, to program the XBee modules it’necessary to disable the ATMEGA chip, so…or you remove it, or you connect to GND the RST Arduino pin. 😉

So, I used as network ID the suggested number (1234), then I configured one module as Coordinator AT (setting in the values SH/SL of  serial number of Router module), and I configured the other module as Router AT (setting in the values SH/SL of Serial Number of Coordinator module).

Well, once configured, the two modules start to “talk” each other, and the leds on shields start to blink. To test the correct configuration you can use the procedure well explained in the  http://tutorial.cytron.com.my/2012/03/08/xbee-series-2-point-to-point-communication/comment-page-1/.

IMPORTANT NOTE: I used the default speed of serial connection (9600 bps) for XBee modules, since I noticed that if I change the data speed, the USB connection from Arduino IDE to Arduino in order to download applications should fatally fail.

 

Second step: the MIDI receiver-XBee sender

The difficult step is passed…so, one moment of relax now! 😉

Ok, let’s start with the secdond step.

This MIDI receiver/XBee Sender has one MIDI connector in order to receive MIDI signals from a synthesizer, the software collect them, then it uses the XBee serial link to send MIDI signals to the other system component (see the third step).

The circuit is very simple…. and it is based on the standard MIDI-IN circuit. See http://www.midi.org/techspecs/electrispec.php to see the details. I modified it a little (especially the optocoupler)…in order to match the parts I had in the “Garret” at the moment 😉 !

The components are:

  • 1x Optocoupler 4N35
  • 1x Diode 4148
  • 1x 100KOhm resistor
  • 1x 220Ohm resistor
  • 1x 3.3KOhm resistor

Note that in the schema I added the XBee module and the XBee shield on the right side of Arduino, in order to better explain the connections, but OBVIOUSLY their must be mounted ON the Arduino! 🙂

XBEE_sender+MIDI_receiver_Garretlabs_bb

The software is simply a MIDI messages collector and re-sender.

Note that I used a buffer to memorize a certain number of MIDI message before to send them, because if wen I receive a message I resend it immediately, I could loose another MIDI message incoming in the meantime. So, I used a “buffering approach”. I verified -as musician 🙂 – that the latency due to buffering is very (very) low, so this approach is acceptable. 😉

Note also that I use the Software Serial (the RX is on pin 10)  to receive MIDI messages, because XBee must use the Serial port.

 #include <SoftwareSerial.h>

SoftwareSerial MidiSerial(10, 11); // RX, TX

byte in_buffer[1024]; //maximum number of bytes arrived in one cpu cycle
unsigned int received_bytes;

void setup()
{
  Serial.begin(9600); //XBEE transmission
  MidiSerial.begin (31250); //MIDI transmission
  
  //led 13 used for debug
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  
  received_bytes=0;

}

void loop()
{
  if(MidiSerial.available()>0)
  {
      received_bytes=MidiSerial.available();
      for (int i=0;i<received_bytes;i++)
        in_buffer[i]=MidiSerial.read();  //save in the buffer all bytes arrived from MIDI port
      
      //write all bytes arrived in the present cycle (so, the input is decoupled from the output)
      digitalWrite(13, HIGH);
      for (int i=0;i<received_bytes;i++)
      {
        Serial.write(in_buffer[i]);
      }
      digitalWrite(13, LOW);
      
      //reset the counter of received bytes in the cycle
      received_bytes=0;
  }
}

In order to write the program on Arduino, you must set the XBee jumper on “USB” position (and obviously you must to remove the cable to ground connected to the RST pin…see step one!). After programming, you should set the jumper on “XBee” position.

 

Third step: the MIDI sender-XBee receiver

Well, this component is more simple than the previous: it receives the MIDI messages from Xbee serial wireless link and it resend them to the MIDI Out port, in order to command a sound generator, a expander or another synth.

Only one component in this case:

  • 1x 220Ohm resistor

This is the (simple) circuit. As you can note, the MIDI In and Out circuits are NOT mirrored (this is the standard)! ….What a strange design choice!!! 🙂

XBEE_receiver+MIDI_sender_Garretlabs_bb

 

And this is the Arduino software (the MIDI management functions are taken from http://arduino.cc/en/Tutorial/Midi?from=Tutorial.MIDI):

#include <SoftwareSerial.h>

SoftwareSerial MidiSerial(10, 11); // RX, TX

void setup()
{
  Serial.begin(9600); //XBEE transmission
  MidiSerial.begin (31250); //MIDI transmission
  
  //led 13 used for debug
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);

}

void loop()
{
  
  if(Serial.available() > 0)
  {
    digitalWrite(13, HIGH);
    MidiSerial.write(Serial.read()); //receives the midi messages via XBEE...and send it to Synth
    digitalWrite(13, LOW);
  }
  //Test function
  //SendAllNotes();
}
////////////////////////////////////////////////////////////////////////////////////////////
//
// MIDI HELPER FUNCTIONS (taken from http://arduino.cc/en/Tutorial/Midi?from=Tutorial.MIDI)
//
////////////////////////////////////////////////////////////////////////////////////////////

void SendAllNotes() {
  // play notes from F#-0 (0x1E) to F#-5 (0x5A):
  for (int note = 0x1E; note < 0x5A; note ++) {
    //Note on channel 1 (0x90), some note value (note), middle velocity (0x45):
    digitalWrite(13, HIGH);
    MIDICommand(0x90, note, 0x45);
    delay(100);
    digitalWrite(13, LOW);
    //Note on channel 1 (0x90), some note value (note), silent velocity (0x00):
    MIDICommand(0x90, note, 0x00);   
    delay(100);
    
  }
}

//  Send a midi command.  Doesn't check to see that
//  cmd is greater than 127, or that data values are  less than 127:
void MIDICommand(int cmd, int pitch, int velocity) {
  MidiSerial.write(cmd);
  MidiSerial.write(pitch);
  MidiSerial.write(velocity);
}

Now you can write the software on Arduino,

And…well… that’s done! 🙂

To test the system you can connect a master keyboard (better if it is a keytar! 😉 ) to Midi Receiver-XBee Sender and a sound generator to Xbee Receiver-Midi Sender…. and you can try to emulate Sandy Marton’s (one of my 80’s Italo Disco heroes) performances with their faboulous keytars!

This is the mighty Sandy in one of his mighty performances:

sandy_marton

Well… it seems a DIY keytar!

 

Bye bye people, now I go to play some note with my AX7…I need a music overdose (I think today I will write an italo-disco song)! 😉

And…remember tio visit my music site www.marcolastri.net!

 

The dark side of porting Arduino sketches on Intel Galileo (part three: comparing Galileo and Arduino on realtime performances)

Hi dear geeks and Intel Galileo lovers!

I’m sorry if I abandoned for a while your preferred board…but as you know Garretlabs (and I) have many other interests (Raspberry based projects, music and so on…).

Today I want to front one of “dearest” problems of my life: the realtime behavior and characteristics of  boards.

I know, it is one of my preffered psychiatric problems: I want ALWAYS to know the realtime performaces of a board (and of his operating system, if present)  😉

So, this time I want to compare the realtime performances of Arduino UNO and Intel Galileo.

In order to do it, I used the most simple circuit that I know (and that YOU know): one blinking led.

Well, the circuit in Fritzing is:

test_realtime_Galileo_vs_UNO_bbAnd the software is the same (obviously) for both boards:

void setup() 
{
    pinMode (2,OUTPUT);
}
void loop() 
{
   digitalWrite(2,HIGH);
   delay(10);
   digitalWrite(2,LOW);
   delay(10);
}

So, the behavior of code should be very very (very) simple: 10 milliseconds the led is ON and 10 milliseconds it is OFF. So the GPIO2 output is a 5V square wave, with a period of 20 milliseconds  and a duty cycle of 50%.

I connected the channel 1 of my oscilloscope to TestPoint1 and the channel 2 to TestPoint2.

As you see the behavior of the two boards are very different: since the square wave of Arduino UNO (TestPoint 1) is fixed on the timeline with a period of 20 milliseconds, the square wave of Galileo is moving on the timeline and it has more long period than 20 milliseconds. It means that the period is not exactly 20 milliseconds, and it is variable.

This is the trace for Arduino UNO:

Oscill_arduino

As you see, the square wave is perfect (…note that the horizontal scale is 10 milliseconds for division)!

This is the trace for Intel Galileo (stopped in a certain moment, since the trace is continously shifting right):

Oscill_galileo

Well...in this case the square wave  has a period major than 20 milliseconds (because each half wave has a duration major than 10 milliseconds).

Plus, if we measure two random periods, they havent the same duration (the continuous shift of the trace is depending on this).

These are both waveforms:

Oscill_arduino+galileo

So, for me the result is clear: since Arduino UNO commands GPIOs using a very strict realtime, Galileo does not command GPIOs with a realtime scheduling politics.

The motivation can be probably tied to the fact that Galileo launches Arduino scripts as Linux user processes (as I noticed in my prevoius post), so without realtime characteristics.

My conclusion is that, at the moment, we can’t use Galileo as hard realtime controller for particular hardware (ie. safety critical mechanisms and so on). 😦 …

And what are your thinkings about this behaviour of Galileo? Have you found my same results?

Obviously, possible solutions and workarounds are welcome (I thinked to modify the Intel Galileo native Linux in order to add some realtime extension, i.e. RT-PREEMPT or Xenomai).

So, the discussion is open! Let me know what you think! 🙂

…Bye bye electro-babes!