segunda-feira, 21 de março de 2016

Function to generate a random date value in PostgreSQL


In order to populate a database with artificial but semantically valid contents, sometimes we need to obtain random values.



Considering PostgreSQL DBMS, in the case of generating DATE type values, we could create a customized function, named gen_date(), which receives the lower bound for the date to be created as argument:

CREATE OR REPLACE FUNCTION gen_date(min date) RETURNS date AS $$
  SELECT CURRENT_DATE - (random() * (CURRENT_DATE - $1))::int;
$$ LANGUAGE sql STRICT VOLATILE;

The following instruction is able to check the function results:

SELECT gen_date('1980-01-01'), gen_date('2015-12-31');

  gen_date  |  gen_date  
------------+------------
 2003-03-08 | 2016-01-20
(1 record)

quarta-feira, 17 de fevereiro de 2016

Arduino Project #2: Musical keyboard (6 notes) with buzzer and pushbuttons


Overview

With Arduino, we can generate sounds in several frequencies using a simple buzzer or speaker.
Arduino's API comes with specific functions for this given task: tone() and noTone() [1].

In this project, we'll use a bunch of pushbuttons in order to create a musical keyboard!

The goal is to produce distinct tones for each of the 6 available pushbuttons.
These six tones should correspond to these musical notes: C5, D5, E5, F5, G5, and A5.
Yeah, B5 is missing due to lack of space in my small 400-contacts breadboard.

Note frequencies were retrieved from Physics of Music Notes (MTU Physics) [2].



Components

  • 1 buzzer (or speaker)
  • 6 pushbuttons
  • 6 current resistors
  • Jumper wires
  • Breadboard
  • Arduino Uno compatible

Schematics

[https://github.com/hjort/arduino-toys/blob/master/buzzer/MusicalKeyboard.fz]


Source Code

#define BUTTON1_PIN 3
#define BUTTON2_PIN 4
#define BUTTON3_PIN 5
#define BUTTON4_PIN 6
#define BUTTON5_PIN 7
#define BUTTON6_PIN 8
#define BUZZER_PIN  9

#define FIRST_BUTTON BUTTON1_PIN
#define LAST_BUTTON  BUTTON6_PIN

#define FREQ_C5 523.25
#define FREQ_D5 587.33
#define FREQ_E5 659.25
#define FREQ_F5 698.46
#define FREQ_G5 783.99
#define FREQ_A5 880.00

const float freqs[] = {FREQ_C5, FREQ_D5, FREQ_E5, FREQ_F5, FREQ_G5, FREQ_A5};

void setup()
{
  for (int pin = FIRST_BUTTON; pin <= LAST_BUTTON; pin++)
    pinMode(pin, INPUT);
}

void loop()
{
  int button = 0, freq = 0;
  for (int pin = FIRST_BUTTON; pin <= LAST_BUTTON; pin++) {
    if (digitalRead(pin) == HIGH) {
      button = pin - FIRST_BUTTON;
      freq = int(freqs[button]);
      tone(BUZZER_PIN, freq, 100);
    }
  }
  delay(100);
}

[https://github.com/hjort/arduino-toys/blob/master/buzzer/MusicalKeyboard.ino]


Project in Action




References

  1. Arduino Language Reference Guide - Tone: https://www.arduino.cc/en/Reference/Tone
  2. Frequencies of Musical Notes: http://www.phy.mtu.edu/~suits/notefreqs.html