SeaMonkey: cambiare ricerca da a

Ho di recente installato il browser SeaMonkey perché a mio parere è più veloce e meno pesante di Firefox, sebbene sia basato sullo stesso “motore” Mozilla. Eseguendo le ricerche dalla barra di esplorazione, ricevevo sempre risultati da e mi interessava, invece, riceverli da Esplorando la cartella di installazione del programma C:\Program Files (x86)\SeaMonkey\ ho trovato una sottocartella chiamata searchplugins e all’interno di questa il file google.xml . A questo punto ho trascinato tale file sul desktop (richiede il permesso da amministratore) e con un editor di testo (io uso Geany) ho modificato le tre occorrenze di esistenti nel testo in ; ho quindi salvato il file modificato e dal desktop l’ho nuovamente trascinato sulla cartella searchplugins (anche qui viene richiesto il permesso da amministratore). Al successivo lancio di SeaMonkey, digitando una richiesta, il browser l’ha correttamente inviata a anziché a

Nota: oggi ho fatto una modifica alle impostazioni di SeaMonkey (edit – preferences – languages) aggiungendo l’italiano ai due linguaggi di default (inglese US e UK) ed ho visto che la ricerca veniva ancora indirizzata a, ma i risultati erano quelli relativi ad un utente “internazionale”. Alla fine ho deciso di rimuovere sia l’italiano che l’inglese (US e UK) lasciando il riquadro dei linguaggi completamente vuoto e così ricevo i risultati corretti. Non ho notato problemi in altre fasi di navigazione web.

Activate relays with your smartphone (no BT or WiFi, just sounds)

Old smartphones (Pocket PC, Windows Mobile 5 and 6) can be purchased at very low price, and even if old, are really powerful. In addition, you can write and distribute your own applications / games for free, being not in the slavery of “App Markets” of any sort.

In 2009 summer (August and September), I was in France for a “sabbatic” time. I was in city of Albi, relatively far from the sea and the “usual” way to spend summer time (swimming or walking or looking for funny alternatives). France is fantastic for restaurants, aperitives and wine, so that period was very creative for me. The best “fuel” for brain are good food and wines ; if you add that I was are completely alone and without any job duty, you can understand that such condition was very near to the perfection.
Obviously, a minimal “worklab” was part of my baggage: just few things… a solder iron, soldering wire, some indispensable electronic components, a small netbook PC and my smartphone (Samsung SGH-i600). Note that the smartphones like Android and iPhone wasn’t available in that period and the Windows Mobile (5 or 6) was the “modern” OS (surely less intrusive in your privacy than the ones you’re running today). Some time before this journey, I purchased a software tool called PPL (as alternative to Embedded Visual C) and downloaded a free IDE called FBA Creator (you can find a reference to this software gem under my favourite links). I started to realize applications for WM5 / WM6 in the quiet afternoons time, a little step every day. One of the interesting things produced in this learning time, was a program to turn ON/OFF relays using simply DTMF tones played by the phone (under keyboard control). The main idea was to put the phone on a simple “rover” and then write a small webserver to receive commands by any browser, and produce DTMF tones (related to HTTP GET commands) to activate relays, so left and right motors could move the rover and photos taken after every move could be sent via the Internet to my netbook PC. I realized a video that was posted, initially, on youtube. After monster G (Google) acquired youtube, I decided to remove all my videos, ‘cause I was negatively impressed by the growing power of that company, with all the new terms of use of their services ; shorting it, I removed my pages on google space and the videos from youtube. Recently I reloaded some videos on DailyMotion (hoping that this will not be eaten by monster G). If you want take a look at this video, click the player below here and sorry for my horrible english pronuntiation and also for my tragic english writing (NO google translator help, here).

dtmf_remote di robotop

Now, here is the electric diagram of this device. There are 3 relays, the microcontroller (ATMEL ATtiny2313) , one serial interface for  PC connection and analog circuitry to get sounds (thru microphone) and convert them to digital data, by means of specialized decoder IC.

click to enlarge ; PDF copy is included in the downloadable zip

click to enlarge ; PDF copy is included in the downloadable zip

Using this circuit, you can activate / deactivate 3 relays with the DTMF tones emitted by your smartphone / PocketPC. In the downloadable file you can find:
– schematic.pdf , the electric diagram
– dtmf.hex , the Intel-Hex formatted file to burn the micro
– fuses.txt , the fuses configuration used for microcontroller in this application

If you want to take a look at the C source file, click this link
Someone asked me how to indepently control two motors (running CW and CCW) with 3 relays, so here is a state table:

ABC | motor status (0=relay off,as shown in figure; 1=relay ON)
--- | ---------------------------------------------------------
000 | M1 & M2 stop
001 | M1 stop, M2 run clockwise
010 | M1 run clockwise, M2 stop
011 | M1 & M2 run clockwise
100 | M1 & M2 run counterclockwise
101 | M1 run counterclockwise, M2 stop
110 | M1 stop, M2 run counterclockwise
111 | M1 & M2 stop

and a MAD (manually assisted design) schematic…

twomotorsYou can generate DTMF tones directly with your phone keyboard (setting DTMF as default sound for keys) or can use my own program This one is supplied as CAB compressed in ZIP with a password. Such strange arrangment comes from limitations of the hoster to uploading of executable files. When you download the file, you have to unzip it (the password is: eficara) and then you have the that can be directly installed on your WM5 or WM6 device. Note that my Samsung WM6 phone has a full qwerty keyboard, but not a touch screen, so all the commands are activated using the cursor keys and the OK button. You can also activate a sequence of pre-recorded commands ; such sequence has to be stored in a file called sequence.txt , that must reside on the same working directory of the executable. You can create / edit such file with the default Notepad. On every text row there are two numbers, comma separated (no spaces, please). First number is the bitmap of the 3 relays, so can be a number from 0 to 7 ; a number greater than 7 indicates the end of the sequence (it will loop again from the first row). The second number is the time to wait after setting the relays, prior to jump to next sequence step. This number is expressed in mS (milliSeconds) and can range from 100 to 9999. Lower numbers can’t work, ‘cause the DTMF tone needs for a minimal time to be correctly decoded by hardware.
I also wrote another program to play DTMF, using the free tool FBA Creator ; this application is called (as usual, is a zipped CAB with password ; you must unzip it using password eficara and have your ready to be installed on WM5 or WM6 device). The only difference with the previous program (written in PPL) is that the sequence player isn’t included, but the whole working directory, with sources (LUA language) can be downloaded and modified with the FBA tool. IMPORTANT NOTE: if you download and install “FBA the Creator” on Win7 or newer, please create a shortcut to the executable and set this shortcut to be executed by default as administrator. If you don’t do that and launch the executable without administrator rights, you can experience a recursive pop-up error window, that’s very hard to stop. This is just a little problem in a big, genial software, written by an italian author some years ago (in the times of WinXP). Note that all the IDE sources for FBA are also downloadable from the main site. If you look in the forum, you can find some old post by user robotop ; it’s me…

Here is a short presentation video for the FBA IDE I made some time ago for my friends. It’s in Italian, but may be useful just to take a look at the working environment and how it’s easy and powerful (and free…)

FBA-Video_2011-11-23 di robotop

Finally, here is the full working folder (sources and resources) of the DTMF program written under the FBA environment. After downloading the file, you must expand it in a directory ; I suggest a new folder under documents, named FBA with subfolders for this and (may be) your future apps. At this point, if you have the FBA environment installed on your PC, just click the file dtmfrem.fbp to start the IDE and… happy mobile phone programming 🙂

View a short video of this application running in the IDE default emulator…

dtmfrem di robotop

Suoneria per un telefono che non suona più

Mia cognata ha un bel telefono, ormai un oggetto “vintage”, disegnato sul modello delle famose labbra di Mae West nell’allestimento di Salvador Dalì. Purtroppo, il telefono non suona più e siccome io sono considerato “uno che ci capisce”, mi è stato dato il prezioso oggetto, con la preghiera di farlo suonare ancora. Dopo una rapida occhiata mi sono reso conto della totale assenza di sistemi “umani” per smontare l’involucro. Viti nascoste, punti difficili da raggiungere, probabilità altissima di rigare o comunque rovinare la preziosa e lucidissima plastica rossa. Ho deciso quindi di affrontare il problema sotto un altro punto di vista, cioè smontare solo la spina telefonica ed installare una suoneria alternativa lì dentro. La cosa ha funzionato. Propongo qui sotto lo schema, nel caso in cui qualcuno dovesse trovarsi con lo stesso problema (ci sono milioni di cognate al mondo).

ATTENZIONE ! Quando il telefono squilla, sui fili c'è alta tensione !

ATTENZIONE ! Quando il telefono squilla, sui fili c’è alta tensione ! Isolate il circuito in modo adeguato !!!

Il buzzer utilizzato emette un suono con frequenza pari a circa 1KHz quando viene alimentato. L’alimentazione, proveniente dal ponte di diodi, è costituita da una doppia semionda raddrizzata, ma non livellata, e così la frequenza di 1KHz del buzzer è modulata dalla frequenza dello squillo sulla linea telefonica. Il segnale risultante è un trillo semplice, ma efficace. Se occorre un volume acustico particolarmente alto, sarà opportuno utilizzare un buzzer con buona resa acustica. Io ho usato un PKM44EP perché l’avevo a disposizione e il volume del suono è “decente”, comunque si deve scegliere un modello “attivo”, cioè un modello provvisto di oscillatore interno.

Lcd controller; connect 20×4 character LCD to parallel port

I use the Alix-1D motherboard for embedded applications, with Puppy Linux OS and Gambas2 visual Basic IDE. It’s very easy to connect an LCD character display to the parallel port of the motherboard. There is a PIN STRIP connector, named J14, that provides all the signals for the parallel port. In my application I used the Hitachi LM044L display connected to the board in this way:

schematic diagram of display connections

schematic diagram of display connections

  • DB7..DB0 – Data bus, connected to ‘D7..D0’ of LCD
  • /STB – Strobe, connected to ‘E’ of LCD
  • /SCI – Slct-in, connected to ‘WE’ of LCD
  • /AFD – Auto-LF, connected to ‘RS’ of LCD
  • GND – Signal ground, connected to ‘VSS’ of LCD
  • The +5V supply can be taken from pin 4 of connector J15

lcd20x4picThe downloadable file puppy_gambas_lcd.tar.gz contains the whole project folder with sources for Gambas2. This is a minimal working implementation; you have two buttons on the form: the first is for display initialization / clear, the second writes an incrementing character each time you click it, every time moving to next available LCD cursor position.

Clock with binary display / Orologio con display in binario

Binary Clock, built with Microchip PIC16F676 (or PIC16F630).
The hours are displayed with 4 LEDs which are (from left to right) 8,4,2,1; so hours are shown from 1 to 12 (no am and pm).
The minutes are displayed with 5 LEDs that are (from left to right) 40,20,10,5,0; in practice, they show in 5 to 5 way and the exact hour (minute 00) turns ON led 0, because I don’t like to have the minutes row completely OFF.
For viewing the time, press shortly the button. Hours and minutes are shown for 3 seconds, then the LEDs are off.
To adjust the time, press and hold down the button until the top row only turns ON and leds begin a binary counting from 1 to 12.
When you reach the desired time, release the button. After a time of 5 seconds, the display automatically shows the minutes and pressing the button, they advance with the binary counting (5 min steps). When you reach the desired minutes, release the button.
Again, after a time of 5 seconds both the led rows turns ON to show hours and minutes (the seconds are cleared automatically), and everything is shut down. The time has been set. The file contains the wiring diagram in PDF format and the object file (Hex) to program the micro.

The C source was compiled with CC5X Version 3.2I, Copyright (c) B Knudsen Data,Norway 1992-2005 (free edition). If you want to take a look at C source code, click this link.

The prototype: back and front views

This is the PCB diagram (just small image, but a link to PDF 1:1 scale is provided)

For a full size 1:1 PDF, click this link

Note that the circuit uses conductive vias.

Orologio con display binario, realizzato con Microchip PIC16F676 (oppure PIC16F630).
Le ore vengono visualizzate con 4 led che valgono (da sinistra a destra) 8,4,2,1; vengono mostrate quindi le ore da 1 a 12 (niente am e pm). I minuti sono visualizzati con 5 led che valgono (da sinistra a destra) 40,20,10,5,0 . In pratica i minuti vengono mostrati di 5 in 5 e lo scoccare dell’ora (minuti 00) fa accendere il solo led 0, questo perché mi sembra brutto lasciare del tutto spenta la riga dei minuti. Per ottenere la visualizzazione dell’orario, si preme brevemente il pulsantino. Le cifre vengono mostrate per 3 secondi, quindi i led vengono spenti. Per regolare l’ora si tiene premuto a lungo il pulsante fino a quando si accende solo la riga superiore (ore) e i led cominciano un conteggio binario da 1 a 12. Quando si raggiunge l’ora desiderata, si lascia il pulsante.
Trascorso un tempo di 5 secondi, il display mostra automaticamente i minuti e premendo nuovamente il pulsante, questi avanzano con il conteggio binario (si regola, quindi di 5 min in 5 min). Quando si raggiunge il minuto desiderato, lasciare il pulsante. Dopo un tempo di 5 secondi i led si accendono a mostrare ore e minuti (i secondi vengono azzerati automaticamente) e infine tutto si spegne. L’orario è stato regolato.
Il file contiene lo schema elettrico ed il file oggetto .hex per programmare il micro.

Il codice sorgente in C è stato compilato con CC5X Version 3.2I, Copyright (c) B Knudsen Data,Norway 1992-2005 (free edition). Se desiderate dare un’occhiata al codice sorgente in C dell’applicazione, cliccate questo link.


schematic diagram ; click the image to enlarge. A PDF version is included in the downloadable ZIP file


“Fast Reading” teacher’s tool

This program has been developed as a teacher’s tool for “Fast Reading” technique. The purpose is to show on video some random numbers at a specific time. The user can modify the number of digits (tipically 3 to 6), the persistence of the digits on the screen (in 100 mS steps) and the interval from a number to the next (in 100 mS steps).  There is also the possibility to activate (with a checkbox) the sound, that is a metronome tick that is played every time a new number appears on the screen. Here is a screenshot :

fastread_ssI wrote this program with VB6 and tested on WinXP, but I think it will also run on newer Windows versions. The request for such tool comes from my son that is involved in PNL and similar (strange) things 🙂

Disclaimer : this is a demo program and has no warranties, nor support. I’m not responsible for any damage it can create to you and your computer if you try to install it, so use at your own risk…

I agreed with disclaimer terms and want to download the installation file clicking this link.

Update: I tried to install the application under Win7_64 and it worked. When executing the setup.exe you can see a warning like this :

awarningIt’s normal ; close all running applications and click OK.

Roman numerals clock : orologio LCD con numeri romani

Questo circuito che vi propongo, basato su micro ATtiny2313, realizza un orologio LCD con numeri romani.

Il prototipo del circuito, realizzato su una scheda millefori.

Il prototipo del circuito, realizzato su una scheda millefori (segna le 17:20)

Alla prima accensione mostra una schermata lampeggiante con la scritta “Tempera tempus” per ricordare che si deve effettuare la regolazione.

Le fasi della regolazione dell'ora

Il display in fase di richiesta regolazione (prima riga) e nelle fasi di visualizzazione (ultime due righe). La scritta “et” lampeggia con cadenza 1 secondo.

La regolazione si effettua mediante questa procedura :

1) Premere e tenere premuto il pulsante per circa 3 secondi ; sullo schermo appaiono le ore ; rilasciare il pulsante.
2) Premere nuovamente il pulsante e tenerlo premuto ; le ore avanzano da “I” a “XXIV” ; rilasciare il pulsante sull’ora giusta.
3) Attendere circa 3 secondi ; sullo schermo appaiono i minuti.
4) Premere nuovamente il pulsante e tenerlo premuto ; i minuti avanzeranno da “nulla” a “LIX” ; rilasciare il pulsante sui minuti giusti.

Non essendoci una batteria, l’orologio non mantiene l’ora se va via la corrente. Ogni volta che si stacca l’alimentazione, alla riaccensione verrà visualizzato il messaggio che ricorda di effettuare la regolazione. Nella figura sottostante potete vedere lo schema elettrico. Per una visione più dettagliata, scaricate il PDF dal link indicato nella didascalia.

il file PDF può essere scaricato da questo link

Cliccare l’immagine per ingrandirla ; il file PDF può essere scaricato da questo link

Il display LCD che ho utilizzato, purtroppo, necessita di una tensione negativa su Vo per ottenere il massimo contrasto. Ho usato un pin del micro per generare un’onda quadra e il circuito in basso a sinistra nello schema (transistor, condensatori e diodi) per ottenere tale tensione. In caso di display LCD “normali”, cioè in grado di funzionare bene anche con sole tensioni positive, tale circuito diventa inutile e può essere eliminato.

Nel file scaricabile a questo link sono contenuti :
– schematic.pdf , lo schema elettrico del circuito
– roman.hex , il file HEX per la programmazione del micro
– fuses.txt , il file di testo con la configurazione dei fusibili del micro per questa applicazione.

Se desiderate dare un’occhiata al codice sorgente in C dell’applicazione, cliccate questo link.

RxMet1 – ricevitore per sensore esterno Hygro-Thermo a 433 MHz

Questo circuito permette di ricevere i dati trasmessi da un sensore Oregon Scientific modello THGR228NF (visibile nella figura sottostante) in radiofrequenza a 433 MHz.

sensor-THGR228NFIl circuito è stato pubblicato (a mio nome) sulla rivista CQ Elettronica nel numero di Settembre 2007 (consultare la rivista per maggiori dettagli).

Il microcontrollore utilizzato è un Atmel ATtiny2313 ; lo schema è visibile qui sotto:

Per una visione nitida, scaricare il PDF da questo link

Cliccare l’immagine per ingrandirla ; il file PDF può essere scaricato da questo link

Nella prossima immagine si può vedere il prototipo del circuito con i componenti montati :

rxmeteoIl circuito stampato è visibile nell’immagine qui sotto ; ovviamente, per realizzare un circuito mediante fotoincisione, bisogna stampare l’immagine in scala 1:1 e pertanto è opportuno scaricare il file PDF raggiungibile tramite il link nella didascalia dell’immagine.


Il file PDF in scala 1:1 può essere scaricato da questo link

Infine, nella prossima immagine si può vedere la disposizione dei componenti sul circuito.


Il file contenente l’elenco dei materiali, il codice HEX da scrivere sul micro ed i batch files per settare il clock esterno e per effettuare la programmazione dell’ATtiny2313 (tramite il programma freeware SP12), può essere scaricato da questo link. Se desiderate dare un’occhiata al codice sorgente in C dell’applicazione, cliccate questo link.

I dati in uscita dal circuito sono “grezzi”, cioè rappresentano in Ascii l’insieme di bits ricevuti dal sensore, raggruppati in notazione esadecimale. Nella figura sottostante, i dati ricevuti dal sensore sono mostrati nel riquadro a sfondo verde (quello in alto, per i daltonici..) mentre la “traduzione” in temperatura e umidità sono nel riquadro a sfondo blu (quello in basso).

Screenshot del programma su PC per la visualizzazione dei dati

Screenshot del programma su PC per la visualizzazione dei dati

Ho realizzato il programma in VB6 ; chi fosse interessato può scaricare il file d’installazione da questo link. Ricordo che il programma è offerto gratuitamente a scopo di test e non ha alcuna clausola di garanzia e nessuna assunzione di responsabilità da parte mia per eventuali danni o malfunzionamenti.

Il “cuore” di questo programma è una DLL (libreria) scritta da me per decodificare il protocollo di trasmissione del sensore. Chi volesse scrivere un proprio programma per visualizzare i dati forniti dal sensore, potrà usare liberamente tale DLL scaricandola da questo link e inserendola nel proprio programma. Di seguito, un esempio di come utilizzare la DLL in un programma VB6 per decodificare la stringa di dati “grezzi” ricevuti dal sensore in valori leggibili di temperatura e umidità:

// declare the convert function
Private Declare Function RawConvert Lib "meteo.dll" (ByVal text As String) As String

// use the function
//  rxraw contains the full ascii string received from RxMet1
//  rxd contains the decoded Temperature and Hygro
dim rxd as string
dim rxraw as string

    rxd = RawConvert(rxraw)

Nota: questo materiale fu già pubblicato su un mio vecchio sito (ora cancellato) e venne citato da “Hack-a-day” nel settembre del 2007.

One button, two leds using single GPIO on RPi

Once again, a “superused” GPIO… This time, the RPi I/O is used for driving two leds (one blue, one red) and a pushbutton. The schematic is simple, look at the pic below:

tri-schAnd here is the prototype realized on perfboard:

tri-picNote: pictures are taken with leds off, red led on, blue led on.

There is also a new Python script named :

import RPi.GPIO as GPIO
import time
from subprocess import call

cnt = 0  # reset counter for pushbutton pressed
toggle = 0  # reset toggle flag
GPIO.setmode(GPIO.BCM)  # set GPIO mode
while True:  # main loop
    GPIO.setup(4, GPIO.OUT)  # GPIO.4 set as output
    GPIO.output(4, False)  # GPIO.4 output set at low level (red led ON)
    time.sleep(0.2)  # 200mS pause with red led ON
    if toggle != 0:  # if toggle flag set
        GPIO.output(4, True)  # GPIO.4 output set at high level (blue led ON)
        time.sleep(0.2)  # 200mS pause with blue led ON
    GPIO.setup(4, GPIO.IN, pull_up_down = GPIO.PUD_OFF)  # GPIO.4 set as input, no pull-ups (both leds OFF)
    for n in range(0,2):  # exec twice
        time.sleep(0.1)  # wait for 100 mS prior to read pushbutton status
        if GPIO.input(4):  # if GPIO.4 is high (button NOT pressed)
            if cnt >= 4 and cnt <= 6:  # if was pressed for 2-3 sec
                 toggle ^= 1  # invert toggle flag
                 if toggle == 0:  # if changed to 0
                     call("sudo killall x11vnc", shell=True)  # terminate x11vnc server
                 else:  # if changed to 1
                     call("sudo x11vnc", shell=True)  # start x11vnc server
             cnt = 0  # reset counter for pushbutton pressed
         else:  # if GPIO.4 is low (button pressed)
             cnt += 1  # increment counter for pushbutton pressed
     if cnt >= 10:  # if continuously pressed for 5 seconds (cnt increments 2 times in a second)
        GPIO.setup(4, GPIO.OUT)  # GPIO.4 set as output
        GPIO.output(4, False)  # GPIO.4 output set at low level (fix red led ON as signal for user)
        call("sudo poweroff", shell=True)  # terminate and shutdown
    if toggle != 0:  # if toggle flag set
        time.sleep(0.4)  # (blue blinked for 0.2 Sec) wait the remaining time for 1 Sec main cycle
        time.sleep(0.6)  # (blue off) wait the remaining time for 1 Sec main cycle

How it works:

Normally, the red led is lighted for 200 mS, then the button is sampled for pressed state. If the button is pressed for a time between 2 and 3 seconds, then the variable toggle is inverted. When toggle is “1”, after the red led turns off, the blue one turns on for 200 mS. If the button is pressed again for 2-3 Sec, the variable toggle is inverted again and at next cycle the blue led will no more turn on. When the toggle variable changes, there are two actions performed by the script : if toggle is 0 (off) then a call to “killall x11vnc” is performed, while if is 1 (on) a call to “x11vnc” is done. This means that I can control the start or stop of x11vnc server with my pushbutton. If I press the button for a time over 5 seconds, there is a call to the “poweroff” and the board will turn off. Please, note that when the pushbutton is pressed the blue led can’t turn on, while the red one will be forced on (at low current, 1mA).

Here is a video of circuit and program running:

tri-film di robotop

Hope this will be useful for someone… 🙂

Double function GPIO on RPi

I’m using the Raspberry Pi board in some projects. Many of these needs to run 24/7, so the hardware has battery backup in case of power fail. Sometimes, the device controlled by RPi board has to be powered off for maintenance, so it’s also necessary to turn off the control board, but there’s no video, no keyboard, neither mouse attached. The operator must connect all of these to perform a clean shutdown. Ok, that’s unacceptable: I decided to add a blinking led to inform the operator that the board is running and a switch to manually perform the shutdown, without the need for keyboard, mouse and video.
There was a problem: I just had ONE single GPIO free, the GPIO.4 , so I decided to use it for both led driving and pushbutton input. The principle is very simple: change the port direction and use it alternatively for led and for pushbutton. Here is the schematic:

rpi-led-sw-schAnd this is the prototype circuit mounted for testing purposes:

rpi-led-sw-picThe 1K resistor limits the current from GPIO.4 to about 1.5mA (the red led lights well) and the 470 Ohm resistor limits the current from the pin in case of software error (it happens, sometime) that sets the GPIO.4 as output and its value as high (3.3v). In such case, even if you press the pushbutton switch, the GPIO.4 is loaded with max 7mA (3.3V / 470 Ohm) that is acceptable for the output. When you press the button, the led turns ON even if the GPIO is in input mode, but the current that flows in the led is smaller than in case of GPIO is output-low, being the resistor value 1K + 470 Ohm (approx 1mA will flow thru the led). Note that the resistor values are important : you can’t decrease significantly the value of 470 Ohm, ‘cause the current drawn from GPIO in case of “output high” will be out of GPIO current limits and you also can’t increase that value, ‘cause the partition with led and 1K resistor will supply a voltage out of specs when pressing the pushbutton while the port is in input mode. With actual values, the voltage at GPIO pin when in input and with switch closed is about 0.5V that is in range for being read as logical “0”. Voltage over 0.8V may create unstable “0” reads or can be interpreted as “1” (switch open). Similarly, you can’t increase the value of 1K, ‘cause the current that flows in the led (and its brightness) will proportionally decrease. So, the values proposed in the schematic are “well balanced”…

Now, we have a double function pin. Here is the listing of a Python script I realized to make all this principle working : it’s named “”.

import RPi.GPIO as GPIO
import time
from subprocess import call

# reset counter for pushbutton pressed
cnt = 0
# set GPIO mode
# main loop
while True:
	# GPIO.4 set as output
	GPIO.setup(4, GPIO.OUT)
	# GPIO.4 output set at low level (led ON)
	GPIO.output(4, False)
	# 200mS pause with led ON
	# GPIO.4 set as input with pull-up (led OFF)
	GPIO.setup(4, GPIO.IN, pull_up_down = GPIO.PUD_UP)
	# wait for 100 mS prior to read pushbutton status
	if GPIO.input(4):
		# if GPIO.4 is high (button NOT pressed)
		# reset counter for pushbutton pressed
		cnt = 0
		# if GPIO.4 is low (button pressed)
		# increment counter for pushbutton pressed
		cnt += 1
	# repeat pushbutton read after 100 mS (ensure isn't a spike)
	if GPIO.input(4):
		cnt = 0
		cnt += 1
	if cnt >= 10:
		# if continuously pressed for 5 seconds (cnt increments 2 times in a second)
		# GPIO.4 set as output
		GPIO.setup(4, GPIO.OUT)
		# GPIO.4 output set at low level (fix led ON as signal for user)
		GPIO.output(4, False)
		# terminate and shutdown
		call("sudo poweroff", shell=True)
	# if not terminated, wait the remaining time for 1 Sec main cycle

The main loop has 1 Sec total time : led turns ON for 200mS (so the GPIO is used as output and value is 0) then turns off when the port mode changes to input. After a delay of 100mS the pushbutton state is tested (twice) and a counter is incremented if the switch is closed; if the switch opens, the counter is reset to zero. When the counter reaches 10, so the button was continuously pressed for 5 seconds, the led is forced ON putting the GPIO in output mode with value 0. The shutdown command is then sent to the OS and the Raspberry turns off. At end of shutdown the led that was fixed ON will turn off, obviously.

Note: when you push the button, the led will turn ON ‘cause you connect the cathode to gnd via 1K + 470 Ohm resistence, but you still can see the 200mS blinks due to difference of current flowing in the led when the GPIO is in input state and in output state with value = low (gnd).

Hope this will be useful for someone. It was for me 🙂