<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Hack your Mind</title>
	<atom:link href="http://www.hackyourmind.org/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.hackyourmind.org/blog</link>
	<description></description>
	<lastBuildDate>Thu, 23 May 2013 00:40:37 +0000</lastBuildDate>
	<language>it-IT</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Rpi-hw library v0.3.1: Philips PCD8544-based LCD, and much more</title>
		<link>http://www.hackyourmind.org/blog/rpi-hw-library-v0-3-1-philips-pcd8544-based-lcd-and-much-more/</link>
		<comments>http://www.hackyourmind.org/blog/rpi-hw-library-v0-3-1-philips-pcd8544-based-lcd-and-much-more/#comments</comments>
		<pubDate>Fri, 03 May 2013 18:05:09 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Elettronica]]></category>
		<category><![CDATA[Programmazione]]></category>
		<category><![CDATA[Raspberry Pi]]></category>
		<category><![CDATA[Rpi-hw]]></category>

		<guid isPermaLink="false">http://www.hackyourmind.org/blog/?p=5884</guid>
		<description><![CDATA[Main features - Low-level management of the GPIOs - Generic input/output interfaces - Displays support (7-segments, HD44780, PCD8544) - Keypad support (matrix keypad) - Stepper motor support - Unicode support (built-in) - Handles multiple image formats (using Magick++ API) (optional) - Supports standard fonts (using FreeType) (optional) - Drawing functions Enjoy it!]]></description>
				<content:encoded><![CDATA[<div class="wp-caption aligncenter" style="width: 202px"><a href="/img/pcd8544.png" target="_blank"><img title="Raspberry Pi and Nokia 3310 LCD" src="/img/pcd8544_preview.png" alt="" width="192" height="256" /></a>
<p class="wp-caption-text">Raspberry Pi and Nokia 3310 LCD</p>
</div>
<p><strong>Main features</strong><br />
- Low-level management of the GPIOs<br />
- Generic input/output interfaces<br />
- Displays support (7-segments, HD44780, PCD8544)<br />
- Keypad support (matrix keypad)<br />
- Stepper motor support<br />
- Unicode support (built-in)<br />
- Handles multiple image formats (using Magick++ API) (optional)<br />
- Supports standard fonts (using FreeType) (optional)<br />
- Drawing functions</p>
<p>Enjoy it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackyourmind.org/blog/rpi-hw-library-v0-3-1-philips-pcd8544-based-lcd-and-much-more/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rpi-hw: interfacing the Raspberry Pi with Hitachi HD44780</title>
		<link>http://www.hackyourmind.org/blog/rpi-hw-interfacing-the-raspberry-pi-with-hitachi-hd44780/</link>
		<comments>http://www.hackyourmind.org/blog/rpi-hw-interfacing-the-raspberry-pi-with-hitachi-hd44780/#comments</comments>
		<pubDate>Tue, 20 Nov 2012 15:59:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Elettronica]]></category>
		<category><![CDATA[Progetti]]></category>
		<category><![CDATA[Programmazione]]></category>
		<category><![CDATA[Raspberry Pi]]></category>
		<category><![CDATA[Rpi-hw]]></category>

		<guid isPermaLink="false">http://www.hackyourmind.org/blog/?p=5702</guid>
		<description><![CDATA[I just released version 0.2.2 of the Rpi-hw library and, as you can see from the video, this version finally supports LCD displays compatible with the Hitachi HD44780 driver. To manage an LCD you need to instantiate the class &#8220;display::hd44780&#8243;, defined in the header file &#8220;display/hd44780.hpp&#8221;. Its constructor method takes the GPIO pins used by [...]]]></description>
				<content:encoded><![CDATA[<p>I just released version 0.2.2 of the <a href="http://www.hackyourmind.org/blog/progetti/rpi-hw/">Rpi-hw</a> library and, as you can see from the video, this version finally supports LCD displays compatible with the <a class="extern" href="https://en.wikipedia.org/wiki/Hitachi_HD44780_LCD_controller" target="_blank">Hitachi HD44780 driver</a>.</p>
<div class="wp-caption aligncenter" style="width: 410px">
<iframe width="400" height="240" src="https://www.youtube-nocookie.com/embed/DEvJnCHCPjE?rel=0" frameborder="0" allowfullscreen></iframe></p>
<p class="wp-caption-text">Hitachi HD44780 interfacing &#8211; Video</p>
</div>
<p>To manage an LCD you need to instantiate the class <em>&#8220;display::hd44780&#8243;</em>, defined in the header file &#8220;display/hd44780.hpp&#8221;. Its constructor method takes the GPIO pins used by the device (either in 4-bit or 8-bit mode), as in following example:</p>
<div class="code_block">
<pre class="prettyprint lang-cpp linenums">display::hd44780( RS, E, D0, D1, D2, D3 );
display::hd44780( RS, E, D0, D1, D2, D3, D4, D5, D6, D7 );</pre>
</div>
<p>The class has an internal data buffer, therefore you no need to read the data from the display controller. Remember, however, that you must connect the <strong>RW</strong> pin to the <strong>GND</strong>.</p>
<p><span id="more-5702"></span>Here is a brief description of the class methods:</p>
<ul>
<li><strong><span style="color: #0a86cd;">void</span> init( <span style="color: #0a86cd;">uint8_t</span> cols, <span style="color: #0a86cd;">uint8_t</span> rows, <span style="color: #0a86cd;">bool</span> font = 0 )</strong>: initializes the display.</li>
<li><strong><span style="color: #0a86cd;">void</span> cmd( <span style="color: #0a86cd;">uint8_t</span> data )</strong>: sends a command to the display.</li>
<li><strong><span style="color: #0a86cd;">void</span> putchar( <span style="color: #0a86cd;">uint8_t</span> chr )</strong>: writes a character on the display (low level).</li>
<li><strong><span style="color: #0a86cd;">uint8_t</span> getChar( <span style="color: #0a86cd;">uint8_t</span> x, <span style="color: #0a86cd;">uint8_t</span> y ) const</strong>: reads a character from the buffer.</li>
<li><strong><span style="color: #0a86cd;">void</span> home()</strong>: homes the cursor.</li>
<li><strong><span style="color: #0a86cd;">void</span> clear()</strong>: clears the screen.</li>
<li><strong><span style="color: #0a86cd;">void</span> move( <span style="color: #0a86cd;">uint8_t</span> x, <span style="color: #0a86cd;">uint8_t</span> y )</strong>: sets the position of the cursor on the display.</li>
<li><strong><span style="color: #0a86cd;">void</span> newLine()</strong>: moves the cursor to the new line.</li>
<li><strong><span style="color: #0a86cd;">void</span> write( <span style="color: #0a86cd;">uint8_t</span> chr )</strong>: write a character on the display.</li>
<li><strong><span style="color: #0a86cd;">void</span> write( <span style="color: #0a86cd;">uint8_t</span> x, <span style="color: #0a86cd;">uint8_t</span> y, <span style="color: #0a86cd;">uint8_t</span> chr )</strong>: moves the cursor position and writes a character on the display.</li>
<li><strong><span style="color: #0a86cd;">void</span> write( <span style="color: #0a86cd;">const</span> <span style="color: #00D000;">std::string</span> &#038;text, <span style="color: #0a86cd;">size_t</span> delay = 0 )</strong>: writes a string on the display.</li>
<li><strong><span style="color: #0a86cd;">void</span> write( <span style="color: #0a86cd;">uint8_t</span> x, <span style="color: #0a86cd;">uint8_t</span> y, <span style="color: #0a86cd;">const</span> <span style="color: #00D000;">std::string</span> &#038;text, <span style="color: #0a86cd;">size_t</span> delay = 0 )</strong>: moves the cursor position and writes a string on the display.</li>
<li><strong><span style="color: #0a86cd;">void</span> scrollLeft( <span style="color: #0a86cd;">bool</span> cursor = 1 )</strong>: scrolls the contents of the display to the left.</li>
<li><strong><span style="color: #0a86cd;">void</span> scrollRight( <span style="color: #0a86cd;">bool</span> cursor = 1 )</strong>: scrolls the contents of the display to the right.</li>
<li><strong><span style="color: #0a86cd;">void</span> scrollUp( <span style="color: #0a86cd;">bool</span> cursor = 1 )</strong>: scrolls the contents of the display to the up.</li>
<li><strong><span style="color: #0a86cd;">void</span> scrollDown( <span style="color: #0a86cd;">bool</span> cursor = 1 )</strong>: scrolls the contents of the display to the down.</li>
<li><strong><span style="color: #0a86cd;">void</span> scrollLeftLine( <span style="color: #0a86cd;">uint8_t</span> line, <span style="color: #0a86cd;">bool</span> cursor = 1 )</strong>: scrolls a line to the left.</li>
<li><strong><span style="color: #0a86cd;">void</span> scrollRightLine( <span style="color: #0a86cd;">uint8_t</span> line, <span style="color: #0a86cd;">bool cursor = 1 )</strong>: scrolls a line to the right.</li>
<li><strong><span style="color: #0a86cd;">void</span> defChar( <span style="color: #0a86cd;">uint8_t</span> index, <span style="color: #0a86cd;">const uint8_t</span> *data )</strong>: defines a custom character.</li>
<li><strong><span style="color: #0a86cd;">void</span> setCursor( <span style="color: #0a86cd;">uint8_t</span> mode )</strong>: sets the cursor mode.</li>
<li><strong><span style="color: #0a86cd;">void</span> setAutoscroll( <span style="color: #0a86cd;">uint8_t</span> mode )</strong>: sets the autoscroll mode.</li>
</ul>
<p>In the next days we will see how to use each of these methods, but for now you can see the examples included in the source code.</p>
<div class="wp-caption aligncenter" style="width: 371px"><a href="/img/hd44780.png" target="_blank"><img title="Hitachi HD44780 interfacing - Circuit" src="/img/hd44780_preview.png" alt="Raspberry Pi GPIO" width="361" height="235" /></a>
<p class="wp-caption-text">Hitachi HD44780 interfacing (8-bit mode) &#8211; Circuit</p>
</div>
<p>The following example show you how to print &#8220;Hello world!&#8221; on the display:</p>
<div class="code_block">
<pre class="prettyprint lang-cpp linenums">#include &lt;rpi-hw.hpp&gt;
#include &lt;rpi-hw/display/hd44780.hpp&gt;

// Use the Rpi-hw namespace
using namespace rpihw;

int
main( int argc, char *args[] ) {

	// Create the display controller
	display::hd44780 dev( 14, 18, 4, 17, 21, 22 );

	// Initialize the 20x4 display
	dev.init( 20, 4 );

	// Move the cursor position
	dev.move( 3, 0 );

	// Write the string at cursor position
	dev.write( &quot;Hello World!&quot; );

	return 0;
}</pre>
</div>
<p>The init method must be called before using the instance. It takes the size of the display (for example: 16&#215;2, 20&#215;4, etc.) and it starts the initialization sequence.</p>
<p>For more information about the <a class="extern" href="https://en.wikipedia.org/wiki/Hitachi_HD44780_LCD_controller" target="_blank">Hitachi HD44780 driver</a> you can see the following links:</p>
<ul>
<li><a class="extern" href="https://en.wikipedia.org/wiki/Hitachi_HD44780_LCD_controller" target="_blank">https://en.wikipedia.org/wiki/Hitachi_HD44780_LCD_controller</a></li>
<li><a class="extern" href="http://www.itisrn.it/et/Tesi/teoria/lcd.html" target="_blank">http://www.itisrn.it/et/Tesi/teoria/lcd.html</a> (italian)</li>
<li><a class="extern" href="https://it.wikipedia.org/wiki/HD44780" target="_blank">https://it.wikipedia.org/wiki/HD44780</a> (italian)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.hackyourmind.org/blog/rpi-hw-interfacing-the-raspberry-pi-with-hitachi-hd44780/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rpi-hw: interfacing the Raspberry Pi with matrix keypad</title>
		<link>http://www.hackyourmind.org/blog/rpi-hw-interfacing-the-raspberry-pi-with-matrix-keypad/</link>
		<comments>http://www.hackyourmind.org/blog/rpi-hw-interfacing-the-raspberry-pi-with-matrix-keypad/#comments</comments>
		<pubDate>Thu, 01 Nov 2012 22:47:25 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Elettronica]]></category>
		<category><![CDATA[Progetti]]></category>
		<category><![CDATA[Programmazione]]></category>
		<category><![CDATA[Raspberry Pi]]></category>
		<category><![CDATA[Rpi-hw]]></category>

		<guid isPermaLink="false">http://www.hackyourmind.org/blog/?p=5526</guid>
		<description><![CDATA[This is my first post in English, so please be understanding. Today we will see how to interfacing the Raspberry Pi with a matrix keypad using the Rpi-hw library. The library provides the class &#8220;keypad::matrix&#8220;, defined in the header file &#8220;keypad/matrix.hpp&#8221;, with which it is possible to manage keypads of any size. Its constructor method [...]]]></description>
				<content:encoded><![CDATA[<p>This is my first post in English, so please be understanding. <img src='http://www.hackyourmind.org/blog/wp-content/plugins/smilies-themer/tango/face-smile.png' alt=':)' class='wp-smiley' /> </p>
<p>Today we will see how to interfacing the <a class="extern" href="http://www.raspberrypi.org/faqs" target="_blank">Raspberry Pi</a> with a matrix keypad using the <a href="http://www.hackyourmind.org/blog/progetti/rpi-hw/">Rpi-hw</a></strong> library.</p>
<div class="wp-caption aligncenter" style="width: 410px">
<iframe width="400" height="240" src="https://www.youtube-nocookie.com/embed/2M-zW6Wrg-8?rel=0" frameborder="0" allowfullscreen></iframe></p>
<p class="wp-caption-text">Matrix keypad interfacing &#8211; Video</p>
</div>
<p>The library provides the class &#8220;<em>keypad::matrix</em>&#8220;, defined in the header file &#8220;keypad/matrix.hpp&#8221;, with which it is possible to manage keypads of any size. Its constructor method takes two ordered lists containing the <a class="extern" href="https://en.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a> pins used by the device.</p>
<div class="code_block">
<pre class="prettyprint lang-cpp linenums">keypad::matrix( /* Column pins */ { COL0, COL1, COL2, ... }, /* Rows pins */ { ROW0, ROW1, ROW2, ... } )</pre>
</div>
<p>Once it is instantiated, the object has several methods to control the keypad:</p>
<ul>
<li><strong><span style="color: #0a86cd;">bool</span> state( <span style="color: #0a86cd;">size_t</span> index ) <span style="color: #0a86cd;">const</span></strong>: returns a button state.</li>
<li><strong><span style="color: #0a86cd;">bool</span> pressed( <span style="color: #0a86cd;">size_t</span> index ) <span style="color: #0a86cd;">const</span></strong>: checks if a button is pressed.</li>
<li><strong><span style="color: #0a86cd;">bool</span> released( <span style="color: #0a86cd;">size_t</span> index ) <span style="color: #0a86cd;">const</span></strong>: checks if a button is released.</li>
<li><strong><span style="color: #0a86cd;">const</span> <span style="color: #00D000;">bitset</span> &#038;state() <span style="color: #0a86cd;">const</span></strong>: returns the bitset of button states.</li>
<li><strong><span style="color: #0a86cd;">size_t</span> numOfKeys() <span style="color: #0a86cd;">const</span></strong>: returns the number of keys.</li>
</ul>
<p>The argument &#8220;index&#8221; refers to the button index of keypad. All buttons are numbered from left-to-right and top-to-bottom, so that first button is at top-left and last button is at bottom-right.</p>
<p><span id="more-5526"></span>Let&#8217;s take an example. The following image shows how to connect the <a class="extern" href="http://www.raspberrypi.org/faqs" target="_blank">Raspberry Pi</a> with a standard 12-key keypad:</p>
<div class="wp-caption aligncenter" style="width: 420px"><a href="/img/keypad12keys.png" target="_blank"><img title="Matrix keypad interfacing - Circuit" src="/img/keypad12keys_preview.png" alt="Matrix keypad interfacing - Circuit" width="410" height="263" /></a>
<p class="wp-caption-text">Matrix keypad interfacing &#8211; Circuit</p>
</div>
<p>We used the following GPIO pins: <strong>21</strong>, <strong>10</strong>, and <strong>4</strong> for columns; <strong>22</strong>, <strong>14</strong>, <strong>15</strong>, and <strong>17</strong> for rows.<br />
And this is the internal circuit diagram of the keypad (where pin names refer to the keypad connector):</p>
<div class="wp-caption aligncenter" style="width: 255px"><a href="/img/keypad12keys_circuit.png" target="_blank"><img title="Matrix keypad interfacing - Circuit" src="/img/keypad12keys_circuit.png" alt="Matrix keypad interfacing - Circuit" width="245" height="235" /></a>
<p class="wp-caption-text">Matrix keypad interfacing &#8211; Circuit</p>
</div>
<p>The instance of &#8220;<em>keypad::matrix</em>&#8221; checks periodically what buttons are pressed, looking for connection between rows and columns. The control algorithm can be summarized as follows:</p>
<ol>
<li>Set GPIOs of the rows as input.</li>
<li>Set GPIOs  of the column as output (low).</li>
<li>Set a column pin to high.</li>
<li>If one of rows reads a high value, then the button between the column and the row is pressed.</li>
<li>Set the previous column to low.</li>
<li>Repeat from line #3 with another column, until there are no more.</li>
</ol>
<div class="wp-caption aligncenter" style="width: 255px"><a href="/img/keypad12keys_anim.gif" target="_blank"><img title="Matrix keypad interfacing - Possible connections" src="/img/keypad12keys_anim.gif" alt="Matrix keypad interfacing - Possible connections" width="245" height="235" /></a>
<p class="wp-caption-text">Matrix keypad interfacing &#8211; Possible connections</p>
</div>
<p>And finally, here is a sample code that shows you how to read the state of some buttons of the 12-key keypad:</p>
<div class="code_block">
<pre class="prettyprint lang-cpp linenums">/* 
    Title --- 12keys0.cpp [examples]

    Copyright (C) 2012 Giacomo Trudu - wicker25[at]gmail[dot]com

    This file is part of Rpi-hw.

    Rpi-hw is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation version 3 of the License.

    Rpi-hw is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Rpi-hw. If not, see &lt;http://www.gnu.org/licenses/&gt;.
*/


#include &lt;iostream&gt;

#include &lt;rpi-hw.hpp&gt;
#include &lt;rpi-hw/keypad/time.hpp&gt;
#include &lt;rpi-hw/keypad/matrix.hpp&gt;

// Use the Rpi-hw namespace
using namespace rpihw;

int
main( int argc, char *args[] ) {

   // Matrix keypad controller
   keypad::matrix dev( { 21, 10, 4 }, { 22, 14, 15, 17 } );

   // Main loop
   for ( ;; ) {

      // Check some keys state
      if ( dev.pressed(0) )
         std::cout &lt;&lt; &quot;You have pressed button 0!\n&quot;;

      if ( dev.released(2) )
         std::cout &lt;&lt; &quot;You have released button 2!\n&quot;;

      if ( dev.pressed(1) &amp;&amp; dev.pressed(4) )
         std::cout &lt;&lt; &quot;You have pressed buttons 1 and 4!\n&quot;;

      // Wait some time
      time::msleep( 100 );
   }

   return 0;
}</pre>
</div>
<p>That&#8217;s all, folks! Feel free to comment my work!</p>
<p><strong>[Updated to version 0.4.0]</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackyourmind.org/blog/rpi-hw-interfacing-the-raspberry-pi-with-matrix-keypad/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rpi-hw: interfacciare il Raspberry Pi ad un altro dispositivo</title>
		<link>http://www.hackyourmind.org/blog/rpi-hw-interfacciare-il-raspberry-pi-ad-un-altro-dispositivo/</link>
		<comments>http://www.hackyourmind.org/blog/rpi-hw-interfacciare-il-raspberry-pi-ad-un-altro-dispositivo/#comments</comments>
		<pubDate>Wed, 10 Oct 2012 20:26:04 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Elettronica]]></category>
		<category><![CDATA[Progetti]]></category>
		<category><![CDATA[Programmazione]]></category>
		<category><![CDATA[Raspberry Pi]]></category>
		<category><![CDATA[Rpi-hw]]></category>

		<guid isPermaLink="false">http://www.hackyourmind.org/blog/?p=5243</guid>
		<description><![CDATA[E&#8217; ormai da qualche giorno che sto lavorando ad una libreria C++ con cui poter gestire l&#8217;interfaccia GPIO della mia scheda Raspberry Pi: l&#8217;ho chiamata Rpi-hw (leggi &#8220;raspberry pi hardware&#8221;). Confesso che questa è la prima volta che lavoro ad un driver di una periferica, ma con molta pazienza alla fine credo di essere riuscito [...]]]></description>
				<content:encoded><![CDATA[<p>E&#8217; ormai da qualche giorno che sto lavorando ad una libreria C++ con cui poter gestire l&#8217;interfaccia <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a> della mia scheda <a class="extern" href="http://www.raspberrypi.org/faqs" target="_blank">Raspberry Pi</a>: l&#8217;ho chiamata <a href="http://www.hackyourmind.org/blog/progetti/rpi-hw/"><strong>Rpi-hw</strong></a> (leggi &#8220;raspberry pi hardware&#8221;). Confesso che questa è la prima volta che lavoro ad un driver di una periferica, ma con molta pazienza alla fine credo di essere riuscito a produrre qualcosa di interessante. (A chiunque interessasse dico solo che mi è bastato seguire attentamente il datasheet del <a class="extern" href="http://www.broadcom.com/products/BCM2835" target="_blank">SoC BCM2835</a>, nella parte relativa al funzionamento del controller <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a>.)</p>
<p>Allo stato attuale la libreria ha assunto caratteristiche leggermente diverse da quelle che mi ero prefissato all&#8217;inizio e non si limita più alla sola gestione dell&#8217;interfaccia <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a>. Ho deciso, infatti, di ampliarla e farla diventare una vera e propria &#8220;libreria di collegamento&#8221; (o <em>wiring library</em>), che renda più semplice la comunicazione tra la <a class="extern" href="http://www.raspberrypi.org/faqs" target="_blank">Raspberry Pi</a> ed altri dispositivi digitali. Per intenderci, vorrei riuscire a gestire questa scheda più o meno come si fa con <a class="extern" href="https://it.wikipedia.org/wiki/Arduino_%28hardware%29" target="_blank">Arduino</a>.</p>
<p>Purtroppo (o per fortuna?) non ho una grande confidenza con quest&#8217;ultimo dispositivo e quindi ho dovuto lavorare parecchio d&#8217;immaginazione per poter sviluppare qualcosa che si rivelasse utile per la sua amica da <em>25$</em>. Il risultato è stata una libreria basata su &#8220;<em>interfacce</em>&#8220;, di ingresso e di uscita, con le quali è possibile manipolare i <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a> della <a class="extern" href="http://www.raspberrypi.org/faqs" target="_blank">Raspberry Pi</a>. I dispositivi di livello più astratto, come vedremo più avanti, saranno costituiti appunto da un&#8217;insieme di queste interfacce, con le quali essi potranno elaborare i segnali di ingresso e di uscita della scheda.</p>
<p><span id="more-5243"></span>Per farvi capire meglio di che cosa si tratta passiamo ad un esempio concreto, immaginando di voler pilotare un semplice <a class="extern" href="https://it.wikipedia.org/wiki/Display_a_sette_segmenti" target="_blank">display a 7 segmenti</a> collegato alla nostra scheda.</p>
<p><a class="extern" href="http://www.raspberrypi.org/faqs" target="_blank">Raspberry Pi</a> mette a nostra disposizione ben 17 pin <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a>: </p>
<div class="wp-caption aligncenter" style="width: 445px"><a href="/img/gpio_pins.png" target="_blank"><img title="Raspberry Pi GPIO" src="/img/gpio_pins_preview.png" alt="Raspberry Pi GPIO" width="435" height="209" /></a>
<p class="wp-caption-text">Raspberry Pi GPIO</p>
</div>
<p>Per interfacciarci al display avremo bisogno di almeno 7 uscite, quindi scegliamo altrettanti <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a> da utilizzare per questo scopo: <strong>1</strong> (segmento <em>a</em>), <strong>4</strong> (<em>b</em>), <strong>18</strong> (<em>c</em>), <strong>15</strong> (<em>d</em>), <strong>14</strong> (<em>e</em>), <strong>0</strong> (<em>f</em>) e <strong>17</strong> (<em>g</em>).</p>
<p>Il circuito di pilotaggio avrà all&#8217;incirca questo aspetto:</p>
<div class="wp-caption aligncenter" style="width: 338px"><a href="/img/display7seg_single_circuit.png" target="_blank"><img title="Display a 7 segmenti - Circuito" src="/img/display7seg_single_circuit.png" alt="Display a 7 segmenti - Circuito" width="328" height="136" /></a>
<p class="wp-caption-text">Display a 7 segmenti &#8211; Circuito</p>
</div>
<p>A questo punto non ci resta che scrivere il programma che azionerà il display. Tutto quello che dobbiamo fare è istanziare la classe <strong>display::s7seg</strong> (<em>single 7 segment</em>) definita nell&#8217;header <em>&#8220;rpi-hw/display/s7seg.hpp&#8221;</em> della nostra libreria.</p>
<div class="code_block">
<pre class="prettyprint lang-cpp linenums">/* 
    Title --- s7seg.cpp [examples]

    Copyright (C) 2012 Giacomo Trudu - wicker25[at]gmail[dot]com

    This file is part of Rpi-hw.

    Rpi-hw is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation version 3 of the License.

    Rpi-hw is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Rpi-hw. If not, see &lt;http://www.gnu.org/licenses/&gt;.
*/


#include &lt;iostream&gt;

#include &lt;rpi-hw.hpp&gt;
#include &lt;rpi-hw/display/time.hpp&gt;
#include &lt;rpi-hw/display/s7seg.hpp&gt;

using namespace rpihw;

int
main( int argc, char *args[] ) {

   // Gestore del display a 7 segmenti
   display::s7seg disp( 1, 4, 18, 15, 14, 0, 17 );

   // Iteratore
   size_t i = 0;

   // Ciclo principale
   while ( 1 ) {

      // Imposto la nuova cifra
      disp.set( i++ );

      // Aspetto un po&#039; di tempo
      time::msleep( 500 );
   }

   return 0;
}</pre>
</div>
<p>L&#8217;esempio è davvero banale e non credo ci sia bisogno di dilungarci troppo. Il metodo costruttore accetta come parametri i nomi dei sette <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a> collegati al display, ordinati secondo il nome del segmento a cui essi sono associati. I metodi <strong>set</strong> e <strong>get</strong>, invece, servono rispettivamente per impostare e per ricavare il valore del display a cui l&#8217;istanza è associata.</p>
<p>Le cose si fanno decisamente più interessanti quando vogliamo utilizzare più di un <a class="extern" href="https://it.wikipedia.org/wiki/Display_a_sette_segmenti" target="_blank">display a 7 segmenti</a> contemporaneamente, in modo da ottenere un output &#8220;composto&#8221;.</p>
<p>Prendiamo in considerazione il seguente circuito, in cui un certo numero di display sono collegati all&#8217;interfaccia <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a>:</p>
<div class="wp-caption aligncenter" style="width: 343px"><a href="/img/display7seg_circuit.png" target="_blank"><img title="Multiplex dei display a 7 segmenti - Circuito" src="/img/display7seg_circuit_preview.png" alt="Multiplex dei display a 7 segmenti - Circuito" width="333" height="245" /></a>
<p class="wp-caption-text">Multiplex dei display a 7 segmenti &#8211; Circuito</p>
</div>
<p>Come potete notare, ad ogni display (a catodo comune) è associato un <a class="extern" href="https://it.wikipedia.org/wiki/Transistor_a_giunzione_bipolare" target="_blank">transistor NPN</a> che ne determina il funzionamento attraverso la chiusura o l&#8217;apertura del circuito. Ognuno di questi transistor è a sua volta controllato da una particolare uscita del controller <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a>. Questa configurazione è necessaria affinche si possa utilizzare la tecnica del <a class="extern" href="https://it.wikipedia.org/wiki/Multiplexing" target="_blank">multiplexing</a>.</p>
<p>Sarebbe infatti sconveniente, e anche impraticabile dal punto di vista fisico, collegare ogni segmento dei display ad un <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a> indipendente. Al contrario utilizziamo un unica configurazione per tutti i display (la stessa vista nell&#8217;esempio precedente), ma ne attiviamo solo uno alla volta, ad una frequenza sufficientemente alta da ingannare l&#8217;occhio umano e farci credere che tutti i display siano illuminati contemporaneamente. Per rendere più chiaro il concetto osservate la seguente animazione che descrive il funzionamento del circuito (ovviamente ad una velocità molto inferiore):</p>
<div class="wp-caption aligncenter" style="width: 343px"><a href="/img/display7seg_anim.gif" target="_blank"><img title="Multiplex dei display a 7 segmenti - Animazione" src="/img/display7seg_anim_preview.gif" alt="Multiplex dei display a 7 segmenti - Animazione" width="333" height="245" /></a>
<p class="wp-caption-text">Multiplex dei display a 7 segmenti &#8211; Animazione</p>
</div>
<p>Ora immaginiamo di voler collegare due display utilizzando il circuito appena descritto. Dovremmo scegliere altri due <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a> con cui poter abilitare/disabilitare i display per mezzo dei transistor: noi useremo il <strong>22</strong> per il display di sinistra (cifra con maggiore significato) e il <strong>21</strong> per il display di destra (cifra con minore significato). Inoltre scegliamo un ultimo <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a> con cui poter controllare il punto decimale dei display, un ulteriore segmento utilizzato per rappresentare i numeri con la virgola: <strong>23</strong> (segmento <em>dp</em>).</p>
<p>Il nostro circuito, adesso rappresentato in modo leggermente più realistico, dovrebbe assomigliare al seguente:</p>
<div class="wp-caption aligncenter" style="width: 461px"><a href="/img/display7seg.png" target="_blank"><img title="Multiplex di due display a 7 segmenti" src="/img/display7seg_preview.png" alt="Multiplex di due display a 7 segmenti" width="451" height="220" /></a>
<p class="wp-caption-text">Multiplex di due display a 7 segmenti</p>
</div>
<p>Per quanto riguarda la parte software, questa volta dovremmo ricorrere ad un&#8217;altra classe chiamata <strong>display::m7seg</strong> (<em>multi 7 segment</em>), che deriva da quella vista precedentemente ed è definita nell&#8217;header <em>&#8220;rpi-hw/display/m7seg.hpp&#8221;</em> della libreria.</p>
<div class="code_block">
<pre class="prettyprint lang-cpp linenums">/* 
    Title --- m7seg.cpp [examples]

    Copyright (C) 2012 Giacomo Trudu - wicker25[at]gmail[dot]com

    This file is part of Rpi-hw.

    Rpi-hw is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation version 3 of the License.

    Rpi-hw is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Rpi-hw. If not, see &lt;http://www.gnu.org/licenses/&gt;.
*/


#include &lt;iostream&gt;

#include &lt;rpi-hw.hpp&gt;
#include &lt;rpi-hw/time.hpp&gt;
#include &lt;rpi-hw/iface/decoder-out.hpp&gt;
#include &lt;rpi-hw/display/m7seg.hpp&gt;

using namespace rpihw;

int
main( int argc, char *args[] ) {

   // Gestore del display a 7 segmenti
   display::m7seg disp( 1, 4, 18, 15, 14, 0, 17, 23 );

   // Creo l&#039;interfaccia per l&#039;abilitazione dei display
   iface::decoderOut enabler( { 21, 22 } );

   // Imposto il numero del display e il relativo abilitatore
   disp.setDisplays( 2, enabler );

   // Imposto la frequenza di aggiornamento del display (in Hz)
   disp.setFreq( 100.0 );

   // Imposta la formattazione
   disp.format( 1, false );


   // Iteratore
   float i = 0.0;

   // Ciclo principale
   while ( 1 ) {

      // Imposto la nuova cifra
      disp.set( i );

      // Incremento il numero nel display
      i += 0.1;

      // Aspetto un po&#039; di tempo
      time::msleep( 500 );
   }

   return 0;
}
</pre>
</div>
<p>Il metodo costruttore accetta gli stessi parametri della classe genitore (anche se in questo caso abbiamo aggiunto il <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a> del punto decimale); inoltre sono presenti anche i metodi <strong>set</strong> e <strong>get</strong> con le medesime funzioni.</p>
<p>Questa volta, tuttavia, dovremo scegliere anche un&#8217;<em>interfaccia d&#8217;uscita</em> con cui poter gestire l&#8217;attivazione dei singoli display (attraverso i <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a> <strong>21</strong> e <strong>22</strong>, scelti in precedenza). La classe <strong>display::m7seg</strong> si limiterà a passare a quest&#8217;interfaccia il numero del display da abilitare ed essa tradurra il parametro in una precisa combinazione di uscite che andranno a sollecitare i <a class="extern" href="https://it.wikipedia.org/wiki/Transistor_a_giunzione_bipolare" target="_blank">transistor NPN</a> del nostro circuito.</p>
<p>Come avrete intuito, l&#8217;interfaccia di cui stiamo parlando è il <a class="extern" href="https://it.wikipedia.org/wiki/Decoder_%28elettronica%29" target="_blank">decoder</a>, già definita per noi come classe <strong>iface::decoderOut</strong> nell&#8217;header <em>&#8220;rpi-hw/iface/decoder-out.hpp&#8221;</em>. Il metodo costruttore di quest&#8217;ultima accetta come unico parametro una lista contenente i <a class="extern" href="https://it.wikipedia.org/wiki/General_Purpose_Input/Output" target="_blank">GPIO</a> che saranno usati come uscite del decoder. Una volta istanziata la nuova interfaccia di uscita potremo collegarla a quella del display attraverso il metodo <strong>setDisplays( NUMERO_DEI_DISPLAY, INTERFACCIA )</strong> di quest&#8217;ultima. Esistono poi altri metodi che ci consentono di impostare la frequenza di lavoro del display e la formattazione del numero rappresentato.</p>
<div class="wp-caption aligncenter" style="width: 410px">
<iframe width="400" height="240" src="http://www.youtube-nocookie.com/embed/7jFYHLrgp_U?rel=0" frameborder="0" allowfullscreen></iframe></p>
<p class="wp-caption-text">Multiplex di due display a 7 segmenti &#8211; Video</p>
</div>
<p>Allo stesso modo avremmo potuto scegliere di utilizzare un&#8217;interfaccia di uscita generica <strong>iface::output</strong> e utilizzare un <a class="extern" href="https://it.wikipedia.org/wiki/Decoder_%28elettronica%29" target="_blank">decoder</a> &#8220;fisico&#8221; nel nostro circuito, in questo modo:</p>
<div class="wp-caption aligncenter" style="width: 316px"><a href="/img/display7seg_anim2.gif" target="_blank"><img title="Display a 7 segmenti - Decoder" src="/img/display7seg_anim2_preview.gif" alt="Display a 7 segmenti - Decoder" width="306" height="245" /></a>
<p class="wp-caption-text">Multiplex dei display a 7 segmenti &#8211; Decoder</p>
</div>
<p>Ma ovviamente la prima soluzione resta la più conveniente, in quanto, come abbiamo appena visto, possiamo emulare con estrema semplicità tutto l&#8217;hardware necessario alla gestione del display.</p>
<p>Queste sono le caratteristiche principali della mia libreria, <a href="http://www.hackyourmind.org/blog/progetti/rpi-hw/"><strong>Rpi-hw</strong></a>, che spero quanto prima di riuscire ad ampliare. Tra i miei primi obiettivi ci saranno sicuramente il supporto per i display LCD, per qualche periferica di ingresso e la creazione di nuove interfacce che simulino il comportamento dei circuiti integrati più comuni.</p>
<p>Ovviamente non ho alcuna pretesa particolare in merito al successo del progetto, visto che ho iniziato a lavorarci per pura passione personale, ma accetterò volentieri qualunque critica o consiglio da chiunque volesse farmi sapere le sue impressioni.</p>
<p>Alla prossima! <img src='http://www.hackyourmind.org/blog/wp-content/plugins/smilies-themer/tango/face-wink.png' alt=';)' class='wp-smiley' /> </p>
<p><strong>[Aggiornato alla versione 0.4.0]</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackyourmind.org/blog/rpi-hw-interfacciare-il-raspberry-pi-ad-un-altro-dispositivo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Raspberry Pi: consigli per gli acquisti</title>
		<link>http://www.hackyourmind.org/blog/raspberry-pi-consigli-per-gli-acquisti/</link>
		<comments>http://www.hackyourmind.org/blog/raspberry-pi-consigli-per-gli-acquisti/#comments</comments>
		<pubDate>Thu, 09 Aug 2012 13:50:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Elettronica]]></category>
		<category><![CDATA[Raspberry Pi]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.hackyourmind.org/blog/?p=5069</guid>
		<description><![CDATA[Stai pensando di acquistare una Raspberry Pi Model B? Ecco di cosa hai bisogno! Fondamentali: Una scheda SD da 4GB o superiore Un alimentatore Micro-USB da 5V a 1A (da manuale sarebbero 700mA, ma è meglio abbondare) Un case (anche autocostruito) Un hub usb (fortemente consigliato) Audio e video su monitor ad alta definizione: Un [...]]]></description>
				<content:encoded><![CDATA[<p>Stai pensando di acquistare una <a class="extern" href="http://www.raspberrypi.org/faqs" target="_blank">Raspberry Pi Model B</a>? Ecco di cosa hai bisogno!</p>
<div class="wp-caption aligncenter" style="width: 409px"><a href="/img/raspberry_pi.png" target="_blank"><img title="Raspberry Pi Model B" src="/img/raspberry_pi.png" alt="" width="399" height="259" /></a>
<p class="wp-caption-text">Raspberry Pi Model B</p>
</div>
<p><strong>Fondamentali</strong>:</p>
<ul>
<li>Una <a class="extern" href="https://it.wikipedia.org/wiki/Secure_Digital" target="_blank">scheda SD</a> da 4GB o superiore</li>
<li>Un <a class="extern" href="https://it.wikipedia.org/wiki/Micro-USB" target="_blank">alimentatore Micro-USB</a> da 5V a 1A (da manuale sarebbero 700mA, ma è meglio abbondare)</li>
<li>Un <a class="extern" href="https://encrypted.google.com/search?q=raspberry+pi+case&#038;hl=it&#038;safe=off&#038;prmd=imvns&#038;source=lnms&#038;tbm=isch&#038;sa=X&#038;ei=Jt8iUM_9K-ip0QWM4oCoCw&#038;ved=0CFYQ_AUoAQ&#038;biw=1364&#038;bih=661&#038;sei=KN8iUO_0Fsj80QXb1YCQCw" target="_blank">case</a> (anche autocostruito)</li>
<li>Un <a class="extern" href="https://encrypted.google.com/search?q=hub+usb&#038;hl=it&#038;safe=off&#038;prmd=imvns&#038;source=lnms&#038;tbm=isch&#038;sa=X&#038;ei=GN4iUIyMLq6A0AWtxoDgDA&#038;ved=0CFwQ_AUoAQ&#038;biw=1364&#038;bih=661&#038;sei=JN4iUI2ELsGm0AXl8IGgDQ#hl=it&#038;safe=off&#038;tbm=isch&#038;sa=1&#038;q=usb+hub+&#038;oq=usb+hub+&#038;gs_l=img.3..0j0i24l9.2761.2761.8.3064.1.1.0.0.0.0.123.123.0j1.1.0...0.0...1c.0dAB4WzngZs&#038;pbx=1&#038;bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&#038;fp=3c93e59ae6d6df4a&#038;biw=1364&#038;bih=661" target="_blank">hub usb</a> (fortemente consigliato)</li>
</ul>
<p><span id="more-5069"></span></p>
<p><strong>Audio e video su monitor ad alta definizione</strong>:</p>
<ul>
<li>Un <a class="extern" href="https://it.wikipedia.org/wiki/High-Definition_Multimedia_Interface#Connettori" target="_blank">cavo HDMI</a></li>
</ul>
<p><strong>Audio e video su monitor analogici</strong>:</p>
<ul>
<li>Un <a class="extern" href="https://it.wikipedia.org/wiki/Video_composito" target="_blank">cavo RCA</a> per il video composito</li>
<li>Un <a class="extern" href="https://encrypted.google.com/search?q=convertitore+mini-jack+rca&#038;hl=it&#038;safe=off&#038;prmd=imvns&#038;source=lnms&#038;tbm=isch&#038;sa=X&#038;ei=eNsiUI6ILIGn0QX2mYD4Cw&#038;ved=0CFwQ_AUoAQ&#038;biw=1364&#038;bih=661&#038;sei=jdsiUJKhGoi_0QXY3YHYDA#hl=it&#038;safe=off&#038;tbm=isch&#038;sa=1&#038;q=mini-jack+stereo+to+rca&#038;oq=mini-jack+stereo+to+rca&#038;gs_l=img.3...1384.2879.2.3025.9.8.1.0.0.1.135.869.3j5.8.0...0.0...1c.qOt3IWgX300&#038;pbx=1&#038;bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&#038;fp=3c93e59ae6d6df4a&#038;biw=1364&#038;bih=661" target="_blank">convertitore da mini-jack stereo a RCA</a> per l&#8217;audio</li>
<li>Un eventuale <a class="extern" href="https://encrypted.google.com/search?q=convertitore+mini-jack+rca&#038;hl=it&#038;safe=off&#038;prmd=imvns&#038;source=lnms&#038;tbm=isch&#038;sa=X&#038;ei=eNsiUI6ILIGn0QX2mYD4Cw&#038;ved=0CFwQ_AUoAQ&#038;biw=1364&#038;bih=661&#038;sei=jdsiUJKhGoi_0QXY3YHYDA#hl=it&#038;safe=off&#038;tbm=isch&#038;sa=1&#038;q=rca+to+scart+adaptor&#038;oq=rca+to+scart+ada&#038;gs_l=img.3.0.0i19.18063.18931.2.20255.4.1.0.3.3.0.97.97.1.1.0...0.0...1c.g2_3vF4MCtA&#038;pbx=1&#038;bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&#038;fp=3c93e59ae6d6df4a&#038;biw=1364&#038;bih=661" target="_blank">adattatore da RCA a SCART</a></li>
</ul>
<p><strong>Input</strong>:</p>
<ul>
<li>Una tastiera e un mouse USB</li>
</ul>
<p><strong>Rete</strong>:</p>
<ul>
<li>Un semplice <a class="extern" href="https://it.wikipedia.org/wiki/Cavo_ethernet_incrociato" target="_blank">cavo ethernet</a> o un <a class="extern" href="https://encrypted.google.com/search?hl=it&#038;safe=off&#038;biw=1364&#038;bih=661&#038;noj=1&#038;tbm=isch&#038;sa=1&#038;q=dongle+usb&#038;oq=dongle+usb&#038;gs_l=img.3..0j0i24l9.576.4248.0.4502.18.14.0.2.2.0.204.1492.4j9j1.14.0...0.0...1c.QLYaFFlPZbs">dongle WiFi</a> compatibile</li>
</ul>
<h3>Installare Raspbian sulla scheda SD</h3>
<p><a class="extern" href="http://www.raspbian.org/" target="_blank">Raspbian</a> è il sistema operativo consigliato per <a class="extern" href="http://www.raspberrypi.org/faqs" target="_blank">Raspberry Pi</a>. E&#8217; una distro linux basata su <a class="extern" href="http://www.debian.org/" target="_blank">Debian</a> ottimizzata per girare su <a class="extern" href="https://it.wikipedia.org/wiki/Architettura_ARM" target="_blank">architetture ARM</a> ed in particolare su <a class="extern" href="http://www.raspberrypi.org/faqs" target="_blank">Raspberry Pi</a>.<br />
Per utilizzare questo sistema operativo dovrete scaricare l&#8217;ultima versione dal sito ufficiale, a <a class="extern" href="http://www.raspberrypi.org/downloads" target="_blank">questo indirizzo</a>. Quindi estraete l&#8217;immagine dall&#8217;archivio e scrivetela sulla vostra <a class="extern" href="https://it.wikipedia.org/wiki/Secure_Digital" target="_blank">SD</a>, dando come <strong>root</strong> il seguente comando (modificando, ovviamente, il percorso al <a class="extern" href="https://it.wikipedia.org/wiki/Dispositivo_a_blocchi" target="_blank">device file</a>):</p>
<div class="code_block"><code># dd if=wheezy-raspbian.img of=/dev/sdb bs=1M</code></div>
<p>L&#8217;operazione potrebbe richiedere alcuni minuti. Una volta copiata l&#8217;immagine del nuovo sistema operativo, potrete ridimensionarne le partizioni utilizzando un gestore delle partizioni a vostra scelta (ad esempio <a class="extern" href="http://gparted.sourceforge.net/" target="_blank">gparted</a>).</p>
<h3>Primo avvio del sistema operativo</h3>
<p>Per iniziare a lavorare con la vostra <a class="extern" href="http://www.raspberrypi.org/faqs" target="_blank">Raspberry Pi</a> inserite la <a class="extern" href="https://it.wikipedia.org/wiki/Secure_Digital" target="_blank">scheda SD</a> nel lettore e collegate tutte le periferiche, quindi alimentate la board: il sistema operativo sarà caricato automaticamente. Salvo modifiche, l&#8217;utente predefinito sarà &#8220;pi&#8221; e la sua password &#8220;raspberry&#8221; (idem per l&#8217;utente <strong>root</strong>).</p>
<p>Per passare alla modalità grafica sarà sufficente impartire il comando &#8220;<em>startx</em>&#8220;.</p>
<h3>Configurazioni generali</h3>
<p>Dopo aver avviato il nuovo sistema operativo dovremo cambiare la lingua e il layout della tastiera. Possiamo farlo direttamente da terminale dando questi due semplici comandi:</p>
<div class="code_block"><code>$ sudo dpkg-reconfigure locales<br />
$ sudo dpkg-reconfigure keyboard-configuration</code></div>
<p>Inoltre modifichiamo il fuso orario in questo modo:</p>
<div class="code_block"><code>$ sudo dpkg-reconfigure tzdata</code></div>
<p>Al termine dell&#8217;operazione riavviamo il sistema per rendere effettive le modifiche:</p>
<div class="code_block"><code>$ sudo reboot</code></div>
<p>Come ultima cosa modifichiamo la password dell&#8217;utente &#8220;pi&#8221; e quella di <strong>root</strong> dando rispettivamente i seguenti comandi:</p>
<div class="code_block"><code>$ passwd<br />
$ sudo passwd</code></div>
<h3>Utilizzare Raspberry Pi da remoto tramite SSH</h3>
<p><a class="extern" href="http://www.raspbian.org/" target="_blank">Raspbian</a> è distribuito con un <a class="extern" href="https://it.wikipedia.org/wiki/Secure_shell" target="_blank">server ssh</a> preinstallato. Questo significa che potremo fin da subito collegarci alla board da remoto, tramite un <a class="extern" href="https://it.wikipedia.org/wiki/Secure_shell" target="_blank">client SSH</a>, senza doverci trascinare dietro tutte le periferiche ogni volta che dobbiamo connettere <a class="extern" href="http://www.raspberrypi.org/faqs" target="_blank">Raspberry Pi</a> alla rete fissa.<br />
Se doveste avere dei problemi a riguardo, provate a leggere <a class="extern" href="http://www.hackyourmind.org/blog/creiamo-il-nostro-muletto-debian-openssh-deluge-web/" target="_blank">questo vecchio post</a> nella parte relativa alla configurazione del <a class="extern" href="https://it.wikipedia.org/wiki/Secure_shell" target="_blank">server ssh</a>.</p>
<h3>Aggiornare il sistema operativo e il firmware</h3>
<p>Essendo un sistema debian-based, <a class="extern" href="http://www.raspbian.org/" target="_blank">Raspbian</a> può essere aggiornata attraverso l&#8217;utility <a class="extern" href="https://it.wikipedia.org/wiki/Advanced_Packaging_Tool" target="_blank">apt</a> con i seguenti comandi:</p>
<div class="code_block"><code>$ sudo apt-get update<br />
$ sudo apt-get dist-upgrade</code></div>
<p>Per aggiornare il kernel ed il firmware, invece, possiamo utilizzare l&#8217;apposito strumento <a class="extern" href="https://github.com/Hexxeh/rpi-update/" target="_blank">rpi-update</a>:</p>
<div class="code_block"><code>$ sudo rpi-update</code></div>
<p>Se l&#8217;utility non dovesse essere presente nella vostra versione di <a class="extern" href="http://www.raspbian.org/" target="_blank">Raspbian</a> potrete scaricarla ed installarla manualmente dando come amministratore un veloce:</p>
<div class="code_block"><code># wget http://goo.gl/1BOfJ -O /usr/bin/rpi-update &amp;&amp; chmod +x /usr/bin/rpi-update</code></div>
<h3>Note finali</h3>
<p>Una cosa che sicuramente noterete è che (allo stato attuale) il <a class="extern" href="https://it.wikipedia.org/wiki/X_Window_System" target="_blank">server grafico</a> non supporta l&#8217;accelerazione hardware. Questa è una bella rottura, ma i produttori ci rassicurano che questa caratteristica sarà presto implementata. Per cui.. <em>Keep Calm and Carry On</em>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackyourmind.org/blog/raspberry-pi-consigli-per-gli-acquisti/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cerberus: crack archives rar, zip, 7z with bash</title>
		<link>http://www.hackyourmind.org/blog/cerberus-crack-archives-rar-zip-7z-with-bash/</link>
		<comments>http://www.hackyourmind.org/blog/cerberus-crack-archives-rar-zip-7z-with-bash/#comments</comments>
		<pubDate>Thu, 31 May 2012 17:32:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Programmazione]]></category>
		<category><![CDATA[Script]]></category>
		<category><![CDATA[Sicurezza]]></category>

		<guid isPermaLink="false">http://www.hackyourmind.org/blog/?p=4812</guid>
		<description><![CDATA[Lo script seguente cerca la password di un archivio 7z, rar o zip, attraverso metodi di forza bruta e attacchi con dizionario. Per la serie &#8220;che cosa possiamo fare con Bash&#8220;. #!/bin/bash #===================================================================================== # # Title: cerberus # Author: Giacomo Trudu aka `Wicker25` - wicker25 [at] gmail [dot] com # Site: http://www.hackyourmind.org/ # License: GNU [...]]]></description>
				<content:encoded><![CDATA[<p>Lo script seguente cerca la password di un archivio <strong>7z</strong>, <strong>rar</strong> o <strong>zip</strong>, attraverso <a class="extern" href="https://it.wikipedia.org/wiki/Metodo_forza_bruta" target="_blank">metodi di forza bruta</a> e <a class="extern" href="https://it.wikipedia.org/wiki/Attacco_a_dizionario" target="_blank">attacchi con dizionario</a>. Per la serie &#8220;<em>che cosa possiamo fare con <a class="extern" href="https://it.wikipedia.org/wiki/Bash" target="_blank">Bash</a></em>&#8220;.</p>
<div class="code_block">
<pre class="prettyprint bash-js linenums">#!/bin/bash
#=====================================================================================
#
#          Title: cerberus
#         Author: Giacomo Trudu aka `Wicker25` - wicker25 [at] gmail [dot] com
#           Site: http://www.hackyourmind.org/
#        License: GNU Lesser General Public License v3 (LGPL3)
#        Version: 0.6.3
#
#  = Version 0.6.3 =
#   + improved analysis resuming
#
#  = Version 0.6.2 =
#   + changed speed unit to pwds/s
#
#  = Version 0.6.1 =
#   + fixed spinner animation
#
#  = Version 0.6 =
#   + improved statistics output
#
#  = Version 0.5.4 =
#   + improved performance with large dictionary files
#
#=====================================================================================

# Versione
name=&#039;cerberus&#039;;
version=&#039;0.6.3&#039;;

# Informazioni sull&#039;attacco
mode=&#039;incremental&#039;;
mode_opt=&#039;&#039;;
mode_format=&#039;&#039;;
mode_resume=false;
mode_length=6;
mode_jobs=( 1 1 );
decrypt=&#039;&#039;;

# Decrittatore
decrypt_7z=&#039;7z t -y -p%s %s&#039;;
decrypt_rar=&#039;unrar t -y -p%s %s&#039;;
decrypt_zip=&#039;7z t -y -p%s %s&#039;;

# Risposta affermativa del decrittatore
password_found=&quot;Everything is Ok|All Ok&quot;;

# Alfabeto
spinner_chars=( &#039;\&#039; &#039;|&#039; &#039;/&#039; &#039;-&#039; );
spinner=0;

# Unità del tempo
time_factors=( 31536000 2628000 604800 86400 3600 60 1 );
time_names=( &#039;years&#039; &#039;months&#039; &#039;weeks&#039; &#039;days&#039; &#039;hours&#039; &#039;minutes&#039; &#039;seconds&#039; );

# Stato dell&#039;analisi (none, found or interrupted)
status=&#039;none&#039;;

# Contatore delle password analizzate
count=0;

# Parametri usati per le statistiche
stats_speed=&#039;-&#039;;
stats_eta=&#039;-&#039;;
last_count=0;
last_time=`date +%s`;


# Aggiorna le statistiche dell&#039;analisi
function update_stats {

   # Calcolo la velocità di analisi
   speed=`echo &quot;scale = 3; ( $count - $last_count ) / ( $time - $last_time )&quot; | bc`;

   # Converto la velocità in passwords/minuto
   stats_speed=&quot;${speed/.*} pwds/s&quot;;

   # Calcolo il tempo rimanente alla fine dell&#039;analisi
   eta=`echo &quot;scale = 3; ( $combinations - $count ) / $speed&quot; | bc`;
   stats_eta=&#039;&#039;;

   # Costruisco la stringa del tempo trascorso
   elapsed=&quot;${eta/.*}&quot;;

   let &#039;precision = 2&#039;;

   for k in `seq 0 6`;
   do
      let &#039;value = elapsed / time_factors[k]&#039;;

      if [ $value -ne 0 ];
      then
         if [ $value -gt 1 ]; 
         then
            stats_eta=&quot;$stats_eta$value ${time_names[$k]} &quot;;
         else
            stats_eta=&quot;$stats_eta$value ${time_names[$k]%?} &quot;;
         fi;

         if [ $precision -gt 1 ];
         then
            let &#039;precision--&#039;;
         else
            break;
         fi;
      fi;

      let &#039;elapsed %= time_factors[k]&#039;;
   done;

   if [ -n &quot;$stats_eta&quot; ];
   then
      stats_eta=&quot;${stats_eta%?}&quot;;
   else
      stats_eta=&#039;-&#039;;
   fi;

   let &#039;last_count = count&#039;;
}


# Prova la password sull&#039;obiettivo
function test_password {

   # Incremento il contatore delle password testate
   let &#039;count++&#039;;

   # Formatto la password
   if [ -n &quot;$mode_format&quot; ];
   then
      password=`echo &quot;$password&quot; | sed -e &quot;$mode_format&quot;`;
   fi;

   # Controllo che siano passati almeno 3 secondi
   time=`date +%s`;

   if [ `expr $time - $last_time` -ge 1 ];
   then
      # Aggiorna le statistiche dell&#039;analisi
      update_stats;

      # Controllo se un altro processo ha già trovato la password
      if [ -s &quot;$meta_password&quot; ];
      then
         password=`cat &quot;$meta_password&quot;`;
         status=&#039;found&#039;;
      fi;

      # Memorizzo i progressi dell&#039;analisi
      echo -e &quot;$mode\n$mode_opt\n$mode_length\n$mode_format\n$i $to&quot; &gt; &quot;$meta&quot;;

      # Memorizzo l&#039;istante corrente per il prossimo controllo
      let &#039;last_time = time&#039;;

      # Scelgo il carattere dello spinner
      spinner_current=&quot;${spinner_chars[`expr $spinner % 4`]}&quot;;

      # Stampo i progressi dell&#039;analisi
      printf &quot;\r\033[K%s Checking &#039;%s&#039;... (%d checked, speed %s, eta %s)&quot; &quot;$spinner_current&quot; &quot;$password&quot; $count &quot;$stats_speed&quot; &quot;$stats_eta&quot;;

      # Modifico il carattere dello spinner
      let &#039;spinner++&#039;;
   fi;

   # Provo a decrittare l&#039;archivio usando la password corrente
   printf -v password &quot;%q&quot; $password;

   if `printf &quot;$decrypt&quot; &quot;$password&quot; &quot;$target&quot;` 2&gt; /dev/null | grep -Eiq &quot;$password_found&quot;;
   then
      echo &quot;$password&quot; &gt; &quot;$meta_password&quot;;
      status=&#039;found&#039;;
   fi;
}


# Cattura il segnale di uscita
function control_attack {

   read -s -n1 -t0.001 key;

   if [ &quot;$key&quot; == $&#039;\x1b&#039; ];
   then
      status=&#039;interrupted&#039;;
   fi;
}


# Attacco forza bruta
function bruteforce_attack {

   # Costruisco l&#039;alfabeto per l&#039;attacco
   if [ -z $mode_opt ];
   then
      mode_opt=&#039;alnum&#039;;
   fi;

   case $mode_opt in
      num)      symbols=( {0..9} );;
      alpha)    symbols=( {a..z} );;
      alcase)   symbols=( {a..z} {A..Z} );;
      alpun)    symbols=( {a..z} &#039; &#039; &#039;(&#039; &#039;)&#039; &#039;.&#039; &#039;;&#039; &#039;:&#039; &#039;!&#039; &#039;?&#039; &#039;/&#039; &#039;\&#039; );;
      alcpun)   symbols=( {a..z} {A..Z} &#039; &#039; &#039;(&#039; &#039;)&#039; &#039;.&#039; &#039;;&#039; &#039;:&#039; &#039;!&#039; &#039;?&#039; &#039;/&#039; &#039;\&#039; );;
      alnum)    symbols=( {a..z} {0..9} );;
      alcnum)   symbols=( {a..z} {A..Z} {0..9} );;
      pun)      symbols=( &#039; &#039; &#039;(&#039; &#039;)&#039; &#039;.&#039; &#039;;&#039; &#039;:&#039; &#039;!&#039; &#039;?&#039; &#039;/&#039; &#039;\&#039; );;
      all)      symbols=( {a..z} {A..Z} {0..9} &#039; &#039; &#039;(&#039; &#039;)&#039; &#039;.&#039; &#039;;&#039; &#039;:&#039; &#039;!&#039; &#039;?&#039; &#039;/&#039; &#039;\&#039;  );;
   esac;

   symbols_l=${#symbols[*]};

   # Calcolo il numero delle combinazioni da provare
   if [ $mode == &#039;incremental&#039; ];
   then
      let &#039;combinations = 0&#039;;

      for i in `seq 1 $mode_length`;
      do
         let &#039;combinations += symbols_l ** i&#039;;
      done;
   else
      let &#039;combinations = symbols_l ** mode_length&#039;;
   fi;

   # Carico eventuali configurazioni preesistenti
   if [ $mode_resume == false ];
   then
      total=`echo &quot;scale = 2; $combinations / ${mode_jobs[1]} + 1&quot; | bc`;
      total=${total/.*};

      let &#039;from += ( mode_jobs[0] - 1 ) * total&#039;;
      let &#039;to = from + total&#039;;
   fi;

   # Aggiusto i valori in modo da non uscire dalle combinazioni previste
   if [ $from -lt 0 ];
   then
      let &#039;from = 0&#039;;
   fi;

   if [ $to -gt $combinations ];
   then
      let &#039;to = combinations&#039;;
   fi;

   # Calcolo le combinazioni restanti
   let &#039;combinations = to - from&#039;;

   # Informazioni sull&#039;attacco
   echo &quot;Combinations: $combinations (from `expr $from + 1` to $to)&quot;;

   # Ciclo principale
   let &#039;i = from&#039;;

   while [ $i -lt $to ];
   do
      # Catturo il segnale di uscita
      control_attack;

      # Controllo se la ricerca è terminata
      if [ $status != &#039;none&#039; ];
      then
         break;
      fi;

      # Se è stata richiesta, applico la ricerca incrementale
      let &#039;current = i&#039;;

      if [ $mode == &#039;incremental&#039; ];
      then
         for j in `seq 1 $mode_length`;
         do
            let &#039;val = symbols_l ** j&#039;;

            if [ $current -ge $val ];
            then
               let &#039;current -= val&#039;;
            else
               break;
            fi;
         done;

         let &#039;password_l = j - 1&#039;;
      else
         let &#039;password_l = mode_length - 1&#039;;
      fi;

      # Costruisco la nuova password
      password=&#039;&#039;;

      for j in `seq 0 $password_l`;
      do
         let &#039;val = current % symbols_l&#039;;

         if [ $val -ge 0 ];
         then
            printf -v password &quot;%s%s&quot; &quot;${symbols[$val]}&quot; &quot;$password&quot;;
         fi;

         let &#039;current /= symbols_l&#039;;

         if [ $current -lt 0 ];
         then
            break
         fi;
      done;

      # Provo la nuova password sull&#039;obiettivo
      test_password;

      # Passo alla prossima password
      let &#039;i++&#039;;
   done;
}


# Attacco con dizionario
function dictionary_attack {

   # Leggo il numero delle parole presenti nel dizionario
   combinations=`wc -l &quot;$mode_opt&quot; | awk &#039;{ print $1 }&#039;`;

   # Carico eventuali configurazioni preesistenti
   if [ $mode_resume == false ];
   then
      total=`echo &quot;scale = 2; $combinations / ${mode_jobs[1]} + 1&quot; | bc`;
      total=${total/.*};

      let &#039;from = ( mode_jobs[0] - 1 ) * total&#039;;
      let &#039;to = from + total&#039;;
   fi;

   # Aggiusto i valori in modo da non uscire dal dizionario
   if [ $from -lt 0 ];
   then
      let &#039;from = 0&#039;;
   fi;

   if [ $to -gt $combinations ];
   then
      let &#039;to = combinations&#039;;
   fi;

   # Calcolo le combinazioni restanti
   let &#039;combinations = to - from&#039;;

   # Informazioni sull&#039;attacco
   echo &quot;Combinations: $combinations (from `expr $from + 1` to $to)&quot;;

   # Provo le parole contenute nel dizionario
   exec 3&lt; &quot;$mode_opt&quot;;

   let &#039;i = 0&#039;;

   while read -u 3 line;
   do
      # Catturo il segnale di uscita
      control_attack;

      # Controllo se la ricerca è terminata
      if [ $status != &#039;none&#039; ];
      then
         break;
      fi;

      # Ignoro le password già testate
      if [ $i -ge $from ];
      then
         # Provo la nuova password sull&#039;obiettivo
         password=&quot;`echo $line | sed &#039;s/[\n\r]//g&#039;`&quot;;

         test_password;
      fi;

      let &#039;i++&#039;;
   done;
}


# Processo i parametri
usage=&quot;Usage: `basename $0` [-b &lt;num|...|all&gt;|-i &lt;num|...|all&gt;|-d &lt;file&gt;] [-l &lt;length&gt;] [-j &lt;current,total&gt;] [-p &lt;format&gt;] [-f &lt;type&gt;] [-r] [-h] -t &lt;target&gt;&quot;;

if [ $# -eq 0 ];
then
   echo $usage;
   exit 1;
fi;

while getopts &#039;b:i:d:f:l:j:p:t:rvh&#039; opt;
do
   case $opt in

      b) mode=&#039;bruteforce&#039;;

         if [[ ! &quot;$OPTARG&quot; =~ ^(num|alpha|alcase|alpun|alcpun|alnum|alcnum|pun|all)$ ]];
         then
            echo &quot;Invalid brute force attack!&quot;;
            echo $usage;
            exit 1;
         fi;

         mode_opt=&quot;$OPTARG&quot;;;

      i) mode=&#039;incremental&#039;;

         if [[ ! &quot;$OPTARG&quot; =~ ^(num|alpha|alcase|alpun|alcpun|alnum|alcnum|pun|all)$ ]];
         then
            echo &quot;Invalid incremental brute force attack!&quot;;
            echo $usage;
            exit 1;
         fi;

         mode_opt=&quot;$OPTARG&quot;;;

      d) mode=&#039;dictionary&#039;;

         if [ ! -r &quot;$OPTARG&quot; ];
         then
            echo &quot;Invalid dictionary file!&quot;;
            echo $usage;
            exit 1;
         fi;

         directory=`dirname $OPTARG`;
         name=`basename $OPTARG`;
         mode_opt=&quot;`cd &quot;$PWD&quot;; cd &quot;$directory&quot;; pwd`/$name&quot;;;

      f) case $OPTARG in
            7z)    decrypt=$decrypt_7z;;
            rar)   decrypt=$decrypt_rar;;
            zip)   decrypt=$decrypt_zip;;
         esac;;

      r) mode_resume=true;;

      l) if [[ ! &quot;$OPTARG&quot; =~ ^[0-9]*$ ]];
         then
            echo &quot;Invalid length!&quot;;
            echo $usage;
            exit 1;
         fi;

         mode_length=&quot;$OPTARG&quot;;;

      p) mode_format=&quot;$OPTARG&quot;;;

      j) if [[ ! &quot;$OPTARG&quot; =~ ^([1-9]+),([1-9]+)$ ]] || [ ${BASH_REMATCH[1]} -gt ${BASH_REMATCH[2]} ];
         then
            echo &quot;Invalid process splitting!&quot;;
            echo $usage;
            exit 1;
         fi;

         mode_jobs=( &quot;${BASH_REMATCH[1]}&quot; &quot;${BASH_REMATCH[2]}&quot; );;

      t) target=&quot;$OPTARG&quot;;;

      v) echo &quot;$name v$version&quot;;
         exit 0;;

      h|?)  echo -e &quot;$usage\n&quot;;
            echo &#039;  -b &lt;num|alpha|alcase|alpun|alcpun|alnum|alcnum|pun|all&gt;     Brute force attack&#039;;
            echo &#039;  -i &lt;num|alpha|alcase|alpun|alcpun|alnum|alcnum|pun|all&gt;     Incremental brute force attack&#039;;
            echo &#039;  -d &lt;file&gt;                                                   Dictionary attack&#039;;
            echo &#039;  -f &lt;7z|rar|zip&gt;                                             Target format&#039;;
            echo &#039;  -l                                                          Length of passwords&#039;;
            echo &#039;  -p &lt;format&gt;                                                 Format passwords&#039;;
            echo &#039;  -j &lt;current,total&gt;                                          Split process&#039;;
            echo &#039;  -r                                                          Resume previous attack&#039;;
            echo &#039;  -v                                                          Print version&#039;;
            echo &#039;  -h                                                          Print this message&#039;;
            echo;
            exit 0;;
   esac;
done;

# Controllo la validità dell&#039;obiettivo
if [ -r &quot;$target&quot; ];
then
   # Costruisco i percorsi ai file d&#039;appoggio
   meta=&quot;$target.meta${mode_jobs[0]}&quot;;
   meta_password=&quot;$target.password&quot;;

   # Controllo se la password è già stata trovata
   if [ -s &quot;$meta_password&quot; ];
   then
      password=`cat &quot;$meta_password&quot;`;
      echo &quot;Password already found: $password&quot;;
      exit 1;
   fi;

   # Se non è stato scelto il decrittatore imposto quello più adatto al file
   if [ -z &quot;$decrypt&quot; ];
   then
      format=`file -ib &quot;$target&quot;`;

      if [[ &quot;$format&quot; =~ ^application/.*7z ]];
      then
         decrypt=$decrypt_7z;

      elif [[ &quot;$format&quot; =~ ^application/.*rar ]]
      then
         decrypt=$decrypt_rar;

      elif [[ &quot;$format&quot; =~ ^application/.*zip ]]
      then
         decrypt=$decrypt_zip;
      else
         echo &quot;Unknown target format!&quot;;
         exit 1;
      fi;
   fi;

   # Continuo l&#039;attacco iniziato in precedenza
   if [ $mode_resume == true ];
   then
      echo &quot;Resuming...&quot;;

      if [ -r &quot;$meta&quot; ];
      then
         mode=`head -1 &quot;$meta&quot;`;
         mode_opt=`sed -n &quot;2p&quot; &quot;$meta&quot;`;
         mode_length=`sed -n &quot;3p&quot; &quot;$meta&quot;`;
         mode_format=`sed -n &quot;4p&quot; &quot;$meta&quot;`;
         from=`tail -1 &quot;$meta&quot; | awk &#039;{ print $1 }&#039;`;
         to=`tail -1 &quot;$meta&quot; | awk &#039;{ print $2 }&#039;`;
      else
         echo &quot;Invalid meta file!&quot;;
         exit 1;
      fi;
   fi;

   # Inizio l&#039;attacco sull&#039;obiettivo
   case $mode in
      bruteforce|incremental)   bruteforce_attack;;
      dictionary)               dictionary_attack;;
   esac;

   # Memorizzo i progressi dell&#039;analisi
   echo -e &quot;$mode\n$mode_opt\n$mode_length\n$mode_format\n$i $to&quot; &gt; &quot;$meta&quot;;

   # Mostro all&#039;utente i risultati dell&#039;elaborazione
   case $status in
      none)          echo -e &quot;\nPassword not found! ($count checked)&quot;;;
      found)         echo -e &quot;\nPassword found: &#039;$password&#039; ($count checked)&quot;;;
      interrupted)   echo -e &quot;\nInterrupted. ($count checked)&quot;;;
   esac;
else
   echo &quot;Invalid target!&quot;;
fi;</pre>
</div>
<div class="downloads"><a href="http://www.hackyourmind.org/highlighter.php?file=cerberus&amp;lang=bash" target="_blank">Scarica il sorgente</a></div>
<p><span id="more-4812"></span></p>
<p>Per scaricare ed installare <strong>cerberus</strong> sul nostro sistema operativo sarà sufficiente dare (come amministratore) i seguenti comandi:</p>
<div class="code_block"><code># cd /usr/bin<br />
# wget "http://www.hackyourmind.org/downloads/sources/cerberus"<br />
# chmod +x cerberus</code></div>
<p>Quindi recuperiamo alcune dipendenze con un ultimo comando:</p>
<div class="code_block"><code>$ sudo apt-get install unrar p7zip-full</code></div>
<h3>Attacco con forza bruta</h3>
<p>Se avviamo <strong>cerberus</strong> usando solo l&#8217;opzione <strong>-t</strong> seguita dal nome dell&#8217;archivio bersaglio, verrà avviato un <a class="extern" href="https://it.wikipedia.org/wiki/Metodo_forza_bruta" target="_blank">attacco con forza bruta</a> che utilizza caratteri alfanumerici minuscoli.</p>
<div class="code_block"><code>$ cerberus -t archivio.7z</code></div>
<p>Tuttavia possiamo scegliere quali simboli utilizzare nell&#8217;analisi attraverso l&#8217;opzione <strong>-b</strong>, in questo modo:</p>
<div class="code_block"><code>$ cerberus -b &lt;simboli&gt; -t archivio.7z</code></div>
<p>Dove il parametro <em>simboli</em> può assumere uno dei seguenti valori:</p>
<ul>
<li><strong>num</strong>, per soli caratteri numerici
<li><strong>alpha</strong>, per caratteri alfabetici minuscoli
<li><strong>alcase</strong>, per caratteri alfabetici minuscoli e maiuscoli
<li><strong>alpun</strong>, per caratteri alfabetici minuscoli e simboli di punteggiatura
<li><strong>alnum</strong>, per caratteri alfanumerici minuscoli
<li><strong>alcnum</strong>, per caratteri alfanumerici minuscoli e maiuscoli
<li><strong>pun</strong>, per simboli di punteggiatura
<li><strong>alpha</strong>, per tutti i caratteri possibili, minuscoli e maiuscoli, compresi i simboli di punteggiatura
</ul>
<p>Con l&#8217;opzione <strong>-l</strong>, invece, possiamo impostare la lunghezza delle password generate:</p>
<div class="code_block"><code>$ cerberus -b &lt;simboli&gt; -l 6 -t archivio.7z </code></div>
<h3>Attacco con forza bruta incrementale</h3>
<p>Nel caso in cui volessimo utilizzare come password tutte le combinazioni di caratteri con lunghezza minore o uguale a quella specificata, sarebbe sufficiente ricorrere all&#8217;opzione <strong>-i</strong>, che supporta gli stessi parametri di quella vista in precedenza:</p>
<div class="code_block"><code>$ cerberus -i &lt;simboli&gt; -t archivio.7z</code></div>
<p>Ecco ad esempio come potremmo fare per provare tutte le password numeriche inferiori ai 4 caratteri di lunghezza, ossia quelle della sequenza <em>0</em>, <em>1</em>, <em>2</em>, &#8230;, <em>9</em>, <em>00</em>, <em>01</em>, <em>02</em>, &#8230;, <em>09</em>, <em>10</em>, <em>11</em>, &#8230;, <em>000</em>, <em>001</em>, <em>002</em>, &#8230;, <em>998</em>, <em>999</em>:</p>
<div class="code_block"><code>$ cerberus -i num -l 3 -t archivio.7z</code></div>
<h3>Attacco con dizionario</h3>
<p>Per cercare di forzare un archivio usando un elenco di parole contenute in un file di testo utilizziamo il parametro <strong>-d</strong> seguito dal percorso al file del dizionario:</p>
<div class="code_block"><code>$ cerberus -d &lt;dizionario&gt; -t archivio.7z</code></div>
<p>Le parole presenti nel dizionario dovranno essere disposte una su ogni riga.</p>
<h3>Attacco distribuito</h3>
<p>Supponiamo di avere a disposizione un certo numero di calcolatori e di voler ripartire su di essi il carico di lavoro generato dall&#8217;analisi del file, in modo tale da incrementarne la velocità complessiva. A questo scopo possiamo utilizzare il parametro <strong>-j</strong>, che permette di suddividere le operazioni svolte per la ricerca in parti uguali rispetto al numero dei calcolatori:</p>
<div class="code_block"><code>$ cerberus -j &lt;corrente&gt;,&lt;totale&gt; -b num -l 4 -t archivio.7z</code></div>
<p>Dove &#8220;<em>corrente</em>&#8221; va sostituito con il numero del pc sul quale stiamo avviando <strong>cerberus</strong> e &#8220;<em>totale</em>&#8221; con il numero totale dei calcolatori su cui è stato distribuito l&#8217;attacco.<br />
Se per esempio volessimo dar inizio ad un attacco distribuito su 3 computer diversi, potremmo usare la seguente configurazione:</p>
<p><em>Computer #1</em>:</p>
<div class="code_block"><code>$ cerberus -j 1,3 -b num -l 4 -t archivio.7z</code></div>
<p><em>Computer #2</em>:</p>
<div class="code_block"><code>$ cerberus -j 2,3 -b num -l 4 -t archivio.7z</code></div>
<p><em>Computer #3</em>:</p>
<div class="code_block"><code>$ cerberus -j 3,3 -b num -l 4 -t archivio.7z</code></div>
<h3>Formattare una password</h3>
<p>Attraverso l&#8217;opzione <strong>-p</strong> è possibile post-formattare le password utilizzate per l&#8217;analisi:</p>
<div class="code_block"><code>$ cerberus -b num -p &lt;regexp&gt; -t archivio.rar</code></div>
<p>L&#8217;opzione deve essere seguita da un&#8217;espressione regolare secondo la sintassi dell&#8217;utility <a class="extern" href="https://en.wikipedia.org/wiki/Sed" target="_blank">sed</a>.</p>
<p>Se ad esempio conoscessimo uno o più caratteri della password che stiamo cercando, potremmo includerli nella nostra ricerca in questo modo:</p>
<div class="code_block"><code>$ cerberus -b num -l 2 -p 's/.*/carla&amp;/' -t archivio.rar</code></div>
<p>Così facendo verrebbero provate tutte le combinazioni di caratteri composte dalla parola &#8220;carla&#8221; e seguite da due cifre decimali (<em>carla00</em>, <em>carla01</em>, <em>carla02</em>, &#8230;, <em>carla99</em> ).</p>
<p>Utilizzando la medesima tecnica potremmo rendere maiuscole tutte le password prelevate da un dizionario:</p>
<div class="code_block"><code>$ cerberus -d dict.txt -p 's/.*/\U&amp;/' -t archivio.rar</code></div>
<h3>Continuazione e conclusione di un attacco</h3>
<div class="wp-caption aligncenter" style="width: 610px"><a href="/img/cerberus.png" target="_blank"><img title="Schermata di cerberus" src="/img/cerberus.png" alt="" width="600" height="95" /></a>
<p class="wp-caption-text">Schermata di cerberus</p>
</div>
<p>Quando diamo inizio ad un attacco su un archivio viene generato automaticamente un metafile dal nome &#8220;<em>archivio.ext.meta</em>&#8220;, in cui verranno memorizzati i progressi compiuti durante l&#8217;analisi dell&#8217;archivio.<br />
In questo modo è possibile riprendere un attacco precedentemente interrotto semplicemente utilizzando come parametri di <strong>cerberus</strong> il nome del bersaglio seguito dall&#8217;opzione <strong>-r</strong>, così come segue:</p>
<div class="code_block"><code>$ cerberus -t archivio.rar -r </code></div>
<p>Per riprendere un attacco distribuito, invece, è necessario aggiungere anche l&#8217;opzione <strong>-j</strong> con i parametri usati nell&#8217;attacco.</p>
<div class="code_block"><code>$ cerberus -j 1,2 -t archivio.rar -r </code></div>
<p>Una volta trovata la password dell&#8217;archivio, l&#8217;attacco verrà interrotto e la password trovata verrà memorizzata in un secondo metafile dal nome &#8220;<em>archivio.ext.password</em>&#8220;.</p>
<h3>Attacco multi-core</h3>
<p>Un interessante stratagemma applicabile alle macchine <a class="extern" href="https://it.wikipedia.org/wiki/Multi_core" target="_blank">multi-core</a> è quello di assegnare ad ogni core della CPU un distinto processo di ricerca, ad esempio utilizzando uno script come il seguente:</p>
<div class="code_block">
<pre class="prettyprint bash-js linenums">#!/bin/bash
target='archivio.7z';
cores=`grep -c ^processor /proc/cpuinfo`;
console=&#039;urxvt -e&#039;;

for i in `seq 1 $cores`;
do
   taskset -c `expr $i - 1` $console cerberus -j $i,$cores -b num -l 2 -t &quot;$target&quot; &amp;
done;

for job in `jobs -p`;
do
   wait $job;
done;

if [ -r &quot;$target.password&quot; ];
then
   echo -e &quot;\nPassword: `cat &quot;$target.password&quot;`&quot;;
fi;</pre>
</div>
<p>Se lo desiderate potete verificare le prestazioni di quest&#8217;ultimo metodo attraverso quest&#8217;altro script:</p>
<div class="code_block">
<pre class="prettyprint bash-js linenums">#!/bin/bash
target='archivio.7z';

echo &quot;- Single -&quot;;

start_time=`date +%s`;
cerberus -b num -l 2 -t "$target";
finish_time=`date +%s`;

echo -e &quot;Time duration: `expr $finish_time - $start_time` secs.\n&quot;;

echo &quot;- Multi-core -&quot;;

cores=`grep -c ^processor /proc/cpuinfo`;
console=&#039;urxvt -e&#039;;

start_time=`date +%s`;

for i in `seq 1 $cores`;
do
   taskset -c `expr $i - 1` $console cerberus -j $i,$cores -b num -l 2 -t "$target" &amp;
done;

for job in `jobs -p`;
do
   wait $job;
done;

finish_time=`date +%s`;

echo -e &quot;Time duration: `expr $finish_time - $start_time` secs.&quot;;
</pre>
</div>
<h3>Analizzare più archivi alla volta</h3>
<p>Se vogliamo analizzare più di un archivio in un colpo solo possiamo dare da terminale un rapido:</p>
<div class="code_block"><code>$ ls *.rar | xargs -n 1 cerberus -b num -l 2 -t</code></div>
<p>Oppure usare un classico ciclo <em>for</em> in uno script bash:</p>
<div class="code_block">
<pre class="prettyprint bash-js linenums">#!/bin/bash
for target in `ls -1 *.rar`;
do
   echo "Analizzo '$target'...";
   cerberus -b num -l 2 -t "$target";
   echo;
done;</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.hackyourmind.org/blog/cerberus-crack-archives-rar-zip-7z-with-bash/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Javascript: a flexible module pattern</title>
		<link>http://www.hackyourmind.org/blog/javascript-a-flexible-module-pattern/</link>
		<comments>http://www.hackyourmind.org/blog/javascript-a-flexible-module-pattern/#comments</comments>
		<pubDate>Fri, 04 May 2012 16:43:55 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Programmazione]]></category>
		<category><![CDATA[Script]]></category>

		<guid isPermaLink="false">http://www.hackyourmind.org/blog/?p=4620</guid>
		<description><![CDATA[La programmazione modulare è un paradigma di programmazione che permette di definire un programma come l&#8217;insieme di più unità indipendenti tra di loro, chiamate appunto &#8220;moduli&#8220;. In questo contesto è possibile sviluppare un software lavorando singolarmente sulle sue componenti, isolando funzioni e strutture tra loro affini e favorendo la riusabilità del codice stesso. Inoltre diventa [...]]]></description>
				<content:encoded><![CDATA[<p>La <a class="extern" href="https://it.wikipedia.org/wiki/Programmazione_modulare" target="_blank">programmazione modulare</a> è un paradigma di programmazione che permette di definire un programma come l&#8217;insieme di più unità indipendenti tra di loro, chiamate appunto &#8220;<a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">moduli</a>&#8220;.<br />
In questo contesto è possibile sviluppare un software lavorando singolarmente sulle sue componenti, isolando funzioni e strutture tra loro affini e favorendo la riusabilità del codice stesso.<br />
Inoltre diventa estremamente semplice estendere le funzionalità del programma con la creazione di nuovi moduli o la modifica di quelli già esistenti.</p>
<p><a class="extern" href="https://it.wikipedia.org/wiki/JavaScript" target="_blank">Javascript</a> non ha un supporto nativo alla <a class="extern" href="https://it.wikipedia.org/wiki/Programmazione_modulare" target="_blank">programmazione modulare</a>, ma grazie alla sua estrema flessibilità è possibile attuare questo paradigma seguendo il cosidetto &#8220;<a class="extern" href="https://en.wikipedia.org/wiki/Module_pattern" target="_blank">module pattern</a>&#8220;. Quest&#8217;ultimo prevede la creazione di una classe <a class="extern" href="https://it.wikipedia.org/wiki/Singleton" target="_blank">singleton</a>, con una propria visibilità (o <a class="extern" href="https://it.wikipedia.org/wiki/Visibilit%C3%A0" target="_blank">scope</a>) che garantisce il principio dell&#8217;<a class="extern" href="https://it.wikipedia.org/wiki/Incapsulamento_%28informatica%29" target="_blank">information hiding</a>.</p>
<p>Il seguente codice è una mia personale implementazione del <a class="extern" href="https://en.wikipedia.org/wiki/Module_pattern" target="_blank">module pattern</a>.</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">/** Modulo per la gestione di un veicolo **/
( function ( BASE, NAME ) {

BASE[ NAME ] = ( function () {

   /** PRIVATO **/
   var fuel = 0;

   /** PUBBLICO **/
   var setFuel = function ( value ) { fuel = value; };
   var getFuel = function () { return fuel; };
   var move = function () { fuel -= 1; };

   // Restituisco i membri e i metodi pubblici
   return {

      setFuel: setFuel,
      getFuel: getFuel,
      move: move
   };

}() );

}( window, 'Vehicle' ) );</pre>
</div>
<p><span id="more-4620"></span>Si tratta di un modulo per la gestione di un veicolo, con tre <em>metodi pubblici</em> ed un <em>membro privato</em> (<strong>fuel</strong>).</p>
<p>Analizzando il sorgente possiamo distinguere due funzioni anonime autoeseguite (<em>anonymous self-executing function</em>). La funzione esterna richiede due argomenti: la <strong>BASE</strong>, ossia il modulo genitore a cui sarà agganciato il nuovo modulo, e il <strong>NAME</strong>, l&#8217;identificativo di quest&#8217;ultimo.</p>
<p>Nell&#8217;esempio, la <strong>BASE</strong> è l&#8217;istanza <em>window</em> e il <strong>NAME</strong> è la stringa &#8220;Vehicle&#8221;. Questo significa che sarà creato un <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">sottomodulo</a> dell&#8217;istanza <em>window</em> con il nome &#8220;Vehicle&#8221;. In realtà, quando si crea un nuovo membro dell&#8217;istanza <em>window</em>, si ha una struttura con visibilità globale, per cui il <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a> resterà indipendente.</p>
<p>La funzione interna, invece, è quella che restituisce l&#8217;istanza <a class="extern" href="https://it.wikipedia.org/wiki/Singleton" target="_blank">singleton</a> del <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a>. Da notare, infatti, che l&#8217;istanza assegnata al <strong>BASE[NAME]</strong> non è la funzione anonima, bensì l&#8217;oggetto che viene restituito da quest&#8217;ultima. Questo espediente è fondamentale perché permette di isolare i membri e i metodi privati della classe, in modo che non siano accessibili all&#8217;esterno del <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a>. Per cui solo le strutture presenti nel dizionario saranno considerate pubbliche.</p>
<p>Questo è un esempio di utilizzo del <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a> appena creato:</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">Vehicle.setFuel( 100 );

document.write( 'Vehicle - carburante iniziale: ' + Vehicle.getFuel() + '&lt;br&gt;' );

Vehicle.move();
Vehicle.move();
Vehicle.move();

document.write( 'Vehicle - carburante dopo 3 movimenti: ' + Vehicle.getFuel() + '&lt;br&gt;' );

document.write( Vehicle.fuel ); // Non è definito!
</pre>
</div>
<p>A questo punto estendere il <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a> precedente diventa semplicissimo. E&#8217; sufficiente introdurre un terzo argomento <strong>PARENT</strong> nella funzione esterna, che riferirà al <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a> genitore.</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">/** Modulo per la gestione di un robot (estende il modulo precedente) **/
( function ( BASE, NAME, PARENT ) {

BASE[ NAME ] = ( function () {

   /** PUBBLICO **/
   var fly = function () {

      PARENT.setFuel( PARENT.getFuel() - 2 );
   };

   // Restituisco i membri e i metodi pubblici
   return {

      setFuel: PARENT.setFuel,
      getFuel: PARENT.getFuel,
      move: PARENT.move,
      fly: fly
   };

}() );

}( window, 'Robot', Vehicle ) );</pre>
</div>
<p>In questo modo il nuovo <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a> avrà accesso ai membri pubblici del genitore e potrà, se necessario, esportarli nella sua istanza <a class="extern" href="https://it.wikipedia.org/wiki/Singleton" target="_blank">singleton</a>.</p>
<p>Nell&#8217;esempio precedente viene creato un <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a> per la gestione di un robot, che eredita i metodi pubblici del <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a> <strong>Vehicle</strong> e, inoltre, introduce il nuovo metodo <strong>fly</strong>.</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">Robot.setFuel( 100 );

document.write( 'Robot - carburante iniziale: ' + Robot.getFuel() + '&lt;br&gt;' );

Robot.move();
Robot.move();
Robot.move();

document.write( 'Robot - carburante dopo 3 movimenti: ' + Robot.getFuel() + '&lt;br&gt;' );

Robot.fly()
Robot.fly()
Robot.fly()

document.write( 'Robot - carburante dopo 3 voli: ' + Robot.getFuel() + '&lt;br&gt;' );</pre>
</div>
<p>Ecco un altro esempio che mostra la creazione di un <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">sottomodulo</a> per la gestione di un cannone, che viene agganciato al <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a> <strong>Robot</strong>.</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">/** Modulo per la gestione di un cannone **/
( function ( BASE, NAME ) {

BASE[ NAME ] = ( function () {

   /** PRIVATO **/
   var bullets = 0;

   /** PUBBLICO **/
   var setBullets = function ( value ) { bullets = value; };
   var getBullets = function () { return bullets; };
   var shoot = function () { bullets -= 1; };

   // Restituisco i membri e i metodi pubblici
   return {

      setBullets: setBullets,
      getBullets: getBullets,
      shoot: shoot
   };

}() );

}( Robot, 'Gun' ) );</pre>
</div>
<p>E questo è il suo utilizzo:</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">Robot.Gun.setBullets( 10 );

document.write( 'Robot.Gun - proiettili iniziali: ' + Robot.Gun.getBullets() + '&lt;br&gt;' );

Robot.Gun.shoot();
Robot.Gun.shoot();
Robot.Gun.shoot();

document.write( 'Robot.Gun - proiettili rimasti: ' + Robot.Gun.getBullets() + '&lt;br&gt;' );</pre>
</div>
<p>E&#8217; anche possibile creare degli <a class="extern" href="https://it.wikipedia.org/wiki/Aliasing_%28programmazione%29" target="_blank">alias</a> interni al <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a> che si riferiscono a delle librerie esterne (ad esempio <a class="extern" href="https://it.wikipedia.org/wiki/JQuery" target="_blank">jQuery</a>), al fine di evitare conflitti con i nomi.</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">/** Modulo che usa la libreria jQuery **/
( function ( $, BASE, NAME ) {

BASE[ NAME ] = ( function () {

   /** PUBBLICO **/
   var fun = function () { 

      alert( 'Titolo della pagina: ' + $('head title').text() );
   };

   // Restituisco i membri e i metodi pubblici
   return { fun : fun };

}() );

}( jQuery, window, 'Modulo' ) );</pre>
</div>
<p>Infine, questo paradigma di programmazione si rivela molto pratico quando si ha la necessità di passare il metodo di un <a class="extern" href="https://it.wikipedia.org/wiki/Modulo_%28programmazione%29" target="_blank">modulo</a> ad una funzione, ad esempio alle funzioni <em>setTimeout()</em> e <em>setInterval()</em>.</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">/** Modulo che usa la libreria jQuery **/
( function ( BASE, NAME ) {

BASE[ NAME ] = ( function () {

   /** PRIVATO **/
   var helloNum = function () { alert( 'Hello world ' + getNum() + '!' ); };
  
   /** PUBBLICO **/
   var getNum = function () { return 21; };

   var fun = function () { 

      setTimeout( helloNum, 3000 );
   };

   // Restituisco i membri e i metodi pubblici
   return { fun : fun };

}() );

}( window, 'Modulo' ) );</pre>
</div>
<p>Come si può notare, infatti, non è stato necessario inserire la parola chiave &#8220;<em>this</em>&#8221; prima del metodo e, anche quando si richiama un secondo metodo dentro al primo, non si va incontro a problemi di <a class="extern" href="https://it.wikipedia.org/wiki/Visibilit%C3%A0" target="_blank">scope</a> che solitamente affliggono <a class="extern" href="https://it.wikipedia.org/wiki/JavaScript" target="_blank">Javascript</a>. Provare per credere&#8230;</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">/** Istanza di prova **/
var obj = new function () {

   /** PRIVATO **/
   var helloNum = function () { alert( 'Hello world ' + this.getNum() + '!' ); };

   /** PUBBLICO **/
   this.getNum = function () { return 21; };

   this.fun = function () { 

      setTimeout( function ( obj ) { obj.getNum() }, 3000, this );
      setTimeout( helloNum, 3000 ); // ERRORE!!!
      // La funzione `helloNum` cerca di richiamare il metodo `this.getNum` dell'istanza
      // ma il `this` al suo interno ora si riferisce a tutt'altro contesto!!!
   }
};

obj.fun();</pre>
</div>
<p>Questo è tutto. Alla prossima! <img src='http://www.hackyourmind.org/blog/wp-content/plugins/smilies-themer/tango/face-wink.png' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackyourmind.org/blog/javascript-a-flexible-module-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Javascript: formatting date like PHP</title>
		<link>http://www.hackyourmind.org/blog/javascript-formatting-date-like-php/</link>
		<comments>http://www.hackyourmind.org/blog/javascript-formatting-date-like-php/#comments</comments>
		<pubDate>Thu, 19 Apr 2012 17:49:56 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Programmazione]]></category>
		<category><![CDATA[Script]]></category>

		<guid isPermaLink="false">http://www.hackyourmind.org/blog/?p=4581</guid>
		<description><![CDATA[Un&#8217;implementazione Javascript della funzione date di PHP. /* Title --- formatdate.js Copyright (C) 2012 Giacomo Trudu - wicker25[at]gmail[dot]com This script is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation version 3 of the License. This script is [...]]]></description>
				<content:encoded><![CDATA[<p>Un&#8217;implementazione <a class="extern" href="https://it.wikipedia.org/wiki/JavaScript" target="_blank">Javascript</a> della funzione <a class="extern" href="http://php.net/manual/en/function.date.php" target="_blank">date</a> di <a class="extern" href="https://it.wikipedia.org/wiki/PHP" target="_blank">PHP</a>.</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">/*
    Title --- formatdate.js

    Copyright (C) 2012 Giacomo Trudu - wicker25[at]gmail[dot]com

    This script is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation version 3 of the License.

    This script is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this script. If not, see &lt;http://www.gnu.org/licenses/&gt;.

	= Version 1.1 =
	 + improved performance
*/

/** Formatta un timestamp o un&#039;oggetto Date  **/
var formatDate = function ( format, time, r ) {

   // Preparo i parametri
   r = ( typeof( r ) != &#039;undefined&#039; &amp;&amp; r );
   var date = ( typeof( time ) != &#039;undefined&#039; ) ? ( time instanceof Date ? time : new Date( time * 1000 ) ) : new Date;

   // Calcolo il numero dei secondi dall&#039;inizio dell&#039;anno
   var yearSecs = ( date - new Date( date.getFullYear(), 0, 1 ) ) / 1000;

   // Estraggo alcune informazioni dalla formattazione standard
   var meta = String( date ).match( /^.*?([A-Z]{1,4})([\-+]\d{4}) \(([A-Z]+)\).*$/ );

   // Estraggo le informazioni
   date = {

      d : date.getDate(),
      D : date.getDay(),
      m : date.getMonth(),
      y : date.getFullYear(),
      l : ( new Date( date.getFullYear(), 1, 29 ).getMonth() === 1 | 0 ),
      h : date.getHours(),
      M : date.getMinutes(),
      s : date.getSeconds(),
      u : date.getMilliseconds(),
      t : date.getTime(),
      z : date.getTimezoneOffset()
   };

   // Stringa della data formattata
   var str = &#039;&#039;;

   // Riempie di zeri le cifre alla sinistra di un numero
   var pad = function ( value, len ) {

      return ( &#039;000000000&#039; + String( value ) ).slice( -len );
   };

   // Parametri della formattazione
   var fmt_values = {

      d : function () { return pad( date.d, 2 ); },
      D : function () { return [ &#039;Sun&#039;, &#039;Mon&#039;, &#039;Tue&#039;, &#039;Wed&#039;, &#039;Thu&#039;, &#039;Fri&#039;, &#039;Sat&#039; ][ date.D ]; },
      j : function () { return date.d; },
      l : function () { return [ &#039;Sunday&#039;, &#039;Monday&#039;, &#039;Tuesday&#039;, &#039;Wednesday&#039;, &#039;Thursday&#039;, &#039;Friday&#039;, &#039;Saturday&#039; ][ date.D ]; },
      N : function () { return date.D + 1; },
      S : function () { return [ &#039;th&#039;, &#039;st&#039;, &#039;nd&#039;, &#039;rd&#039; ][ date.d % 10 &gt; 3 ? 0 : ( date.d &lt; 10 || date.d &gt; 20 ) * date.d % 10 ]; },
      w : function () { return date.D; },
      z : function () { return Math.ceil( yearSecs / 86400 ); },
      W : function () { return Math.ceil( yearSecs / 604800 ); },
      F : function () { return [ &#039;Jan&#039;, &#039;Feb&#039;, &#039;Mar&#039;, &#039;Apr&#039;, &#039;May&#039;, &#039;Jun&#039;, &#039;Jul&#039;, &#039;Aug&#039;, &#039;Sep&#039;, &#039;Oct&#039;, &#039;Nov&#039;, &#039;Dec&#039; ][ date.m ]; },
      m : function () { return pad( date.m + 1, 2 ); },
      M : function () { return [ &#039;January&#039;, &#039;February&#039;, &#039;March&#039;, &#039;April&#039;, &#039;May&#039;, &#039;June&#039;, &#039;July&#039;, &#039;August&#039;, &#039;September&#039;, &#039;October&#039;, &#039;November&#039;, &#039;December&#039; ][ date.m ]; },
      n : function () { return date.m + 1; },
      t : function () { return [31, (date.l ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][ date.m ]; },
      L : function () { return date.l; },
      Y : function () { return date.y; },
      y : function () { return String( date.y ).slice( -2 ); },
      a : function () { return ( date.h &lt; 12 ? &#039;am&#039; : &#039;pm&#039; ); },
      A : function () { return ( date.h &lt; 12 ? &#039;AM&#039; : &#039;PM&#039; ); },
      g : function () { return date.h % 12 || 12; },
      G : function () { return date.h; },
      h : function () { return pad( date.h % 12 || 12, 2 ); },
      H : function () { return pad( date.h, 2 ); },
      i : function () { return pad( date.M, 2 ); },
      s : function () { return pad( date.s, 2 ); },
      u : function () { return date.u * 1000; },
      I : function () { return ( date.m &gt; 2 &amp;&amp; date.m &lt; 10 || ( date.m == 2 &amp;&amp; date.D - date.d &gt;= 8 - 1 ) ); },
      O : function () { return meta[2]; },
      P : function () { return meta[2].slice( 0, -2 ) + &#039;:&#039; + meta[2].slice( -2 ); },
      T : function () { return meta[3]; },
      Z : function () { return -date.z * 60; },
      c : function () { return ( !r ? formatDate( &#039;Y-m-d\\TH:i:sP&#039;, time, true ) : null ); },
      r : function () { return ( !r ? formatDate( &#039;D, d M Y H:i:s O&#039;, time, true ) : null ); },
      U : function () { return Math.floor( date.t / 1000 ); }
   };

   // Divido la stringa di formattazione in token tenendo conto dei caratteri di escape
   var tokens = format.match( /(\\.|.)/gi );

   // Costruisco la stringa del tempo
   for ( var i = 0; i &lt; tokens.length; i++ )
      str += ( tokens[i] in fmt_values ? fmt_values[ tokens[i] ]() : ( tokens[i].length == 1 ? tokens[i] : tokens[i][1] ) );

   return str;
};</pre>
</div>
<div class="downloads"><a href="http://www.hackyourmind.org/highlighter.php?file=formatdate.js&amp;lang=javascript" target="_blank">Scarica il sorgente</a></div>
<p>Esempio di utilizzo:</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">formatDate( 'j, n, Y' ); // => '10, 3, 2001'
formatDate( 'F j, Y, g:i a' ); // => 'March 10, 2001, 5:16 pm'
formatDate( 'd/m/Y', 1230000000 ); // => '23/12/2008'
formatDate( 'H:i', new Date() ); // => '19:52'
formatDate( 'c' ); // => '2012-04-20T19:12:35+02:00'
formatDate( '\\i\\t \\i\\s \\t\\h\\e jS \\d\\a\\y.' ); // => 'it is the 20th day.'</pre>
</div>
<p>Oppure si può integrare direttamente al tipo <a class="extern" href="http://www.w3schools.com/jsref/jsref_obj_date.asp" target="_blank">Date</a>:</p>
<div class="code_block">
<pre class="prettyprint lang-js linenums">Date.prototype.format = function ( format ) { return formatDate( format, this ); };

// Esempio:
var timestr = new Date().format( 'd/m/Y' );</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.hackyourmind.org/blog/javascript-formatting-date-like-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Load dynamically MathJax with JQuery.getScript()</title>
		<link>http://www.hackyourmind.org/blog/load-dynamically-mathjax-with-jquery-getscript/</link>
		<comments>http://www.hackyourmind.org/blog/load-dynamically-mathjax-with-jquery-getscript/#comments</comments>
		<pubDate>Sat, 10 Mar 2012 15:31:56 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Matematica]]></category>
		<category><![CDATA[Programmazione]]></category>
		<category><![CDATA[Script]]></category>

		<guid isPermaLink="false">http://www.hackyourmind.org/blog/?p=4525</guid>
		<description><![CDATA[Un problema che mi ha dato del filo da torcere&#8230; Maledetti percorsi assoluti. &#60;html&#62; &#60;head&#62; &#60;script type="text/javascript" src="lib/jquery.js"&#62;&#60;/script&#62; &#60;title&#62;Titolo della pagina&#60;/title&#62; &#60;/head&#62; &#60;body&#62; &#60;div&#62;\[ \left [ - \frac{\hbar^2}{2 m} \frac{\partial^2}{\partial x^2} + V \right ] \Psi = i \hbar \frac{\partial}{\partial t} \Psi \]&#60;/div&#62; &#60;a id="loadMathJax" href="#"&#62;Carica MathJax&#60;/a&#62; &#60;script type="text/javascript"&#62; &#60;!-- // Percorso alla libreria var [...]]]></description>
				<content:encoded><![CDATA[<p>Un problema che mi ha dato del filo da torcere&#8230; Maledetti percorsi assoluti.</p>
<div class="code_block">
<pre class="prettyprint linenums">&lt;html&gt;
&lt;head&gt;
    &lt;script type="text/javascript" src="lib/jquery.js"&gt;&lt;/script&gt;
    &lt;title&gt;Titolo della pagina&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div&gt;\[ \left [ - \frac{\hbar^2}{2 m} \frac{\partial^2}{\partial x^2} + V \right ] \Psi
= i \hbar \frac{\partial}{\partial t} \Psi \]&lt;/div&gt;

&lt;a id="loadMathJax" href="#"&gt;Carica MathJax&lt;/a&gt;

&lt;script type="text/javascript"&gt;
&lt;!--

    // Percorso alla libreria
    var MathJax_path = 'lib/mathjax/';

    // Carico MathJax alla pressione del link
    $('#loadMathJax').click( function () {

        // Creo la configurazione di MathJax
        var config =

            "MathJax.Ajax.config.root = '" + MathJax_path + "';" + // &lt;- Importante
            "MathJax.Hub.Config( { " +
            "    extensions: [ 'tex2jax.js' ], " +
            "    jax: [ 'input/TeX', 'output/HTML-CSS' ], " +
            "    tex2jax: { " +
            "      inlineMath: [ ['\[', '\]'] ], " +
            "      processEscapes: true " +
            "    }, " +
            "});";

        $('head').append( $('&lt;script&gt;&lt;/script&gt;').attr( 'type', 'text/x-mathjax-config' ).text( config ) );

        // Carico la libreria
        $.getScript( MathJax_path + 'MathJax.js?config=TeX-AMS-MML_HTMLorMML', function () {

            // Modifico il pulsante
            $('#loadMathJax').unbind( 'click' ).css( 'text-decoration', 'line-through' );
        } );
    } );

--&gt;
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.hackyourmind.org/blog/load-dynamically-mathjax-with-jquery-getscript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Debian + Awesome WM + Conky</title>
		<link>http://www.hackyourmind.org/blog/debian-awesome-wm-conky/</link>
		<comments>http://www.hackyourmind.org/blog/debian-awesome-wm-conky/#comments</comments>
		<pubDate>Sun, 27 Nov 2011 17:02:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Altro]]></category>
		<category><![CDATA[GNU/Linux]]></category>
		<category><![CDATA[Grafica]]></category>

		<guid isPermaLink="false">http://www.hackyourmind.org/blog/?p=4511</guid>
		<description><![CDATA[awesome is a highly configurable, next generation framework window manager for X. It is very fast, extensible and licensed under the GNU GPLv2 license. [...]]]></description>
				<content:encoded><![CDATA[<p><a class="extern" href="http://awesome.naquadah.org/" target="_blank">awesome</a> is a highly configurable, next generation framework window manager for X. It is very fast, extensible and licensed under the GNU GPLv2 license. [<a href="http://awesome.naquadah.org/" target="_blank">...</a>]</p>
<div class="wp-caption aligncenter" style="width: 360px"><a href="/img/awesome0.png" target="_blank"><img title="Desktop vuoto" src="/img/awesome0_ico.png" alt="" width="350" height="200" /></a>
<p class="wp-caption-text">Desktop vuoto</p>
</div>
<div class="wp-caption aligncenter" style="width: 360px"><a href="/img/awesome1.png" target="_blank"><img title="Firefox, Thunar e VLC in una vista a piastrelle" src="/img/awesome1_ico.png" alt="" width="350" height="200" /></a>
<p class="wp-caption-text">Firefox, Thunar e VLC in una vista a piastrelle</p>
</div>
<div class="wp-caption aligncenter" style="width: 360px"><a href="/img/awesome2.png" target="_blank"><img title="GEdit, Thunar e Eterm in una vista a piastrelle" src="/img/awesome2_ico.png" alt="" width="350" height="200" /></a>
<p class="wp-caption-text">GEdit, Thunar e Eterm in una vista a piastrelle</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.hackyourmind.org/blog/debian-awesome-wm-conky/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
