Sunday, December 29, 2013

Update on the GIF creator (sharpGIFs 2.0)

Okay, so the last bit of code i wrote had the flaw of not letting the gif's loop.
It seems that for a gif to automatically loop you need to set some custom metadata for the file containing "NETSCAPE 2.0" for some reason. This probably dates back to looping gif's being first introduced in that very browser (GIF89a support).


The most intuitive fix for my program would be to just add this metadata to the GifBitmapEncoder before saving the file. However, for some reason this throws an exception "The designated BitmapEncoder does not support global metadata." Ironically it seems the GifBitmapEncoder is the only BitmapEncoder that doesn't support metadata.

So i was unable to actually fix my program. But luckily i found some code that works, using a different aproach to the problem (using MemoryStream and BinaryWriter).
The original code bit was found here, i haven't really done much in terms of changing anything. Just removing a reference to Response out and changing the delay time to something reasonable. Then i threw in the resizing bit from the last project.

So anyways, here are the code zipped as usual.
sharpGIFs 2.0.zip

And here are the final gif (same images as the post below, just looping this time around):


Thursday, December 26, 2013

Create animated GIF's with C#

I got a brand new camera this christmas, a GoPro Hero3+. The camera shoots amazing Full HD video at action-enabling framerates. And the waterproof casing and small form factor makes this the best damned piece of gear i own.

And after spending hours on hours of tumbling in the snow videoing myself fighting with the dog and jumping off cliffs skiing i started exploring the various other functions the camera has.

One of wich is the ability to take 30 pictures in 3 seconds.
Combined with a handy wifi-remote makes for alot of fun shots.

Then after having 500+ still frames of action recorded on the SD card i realized it would be fun making animated GIF's with them. A quick google search gave me lots of online-sites for just this purpose, but the first one i tried gave me a "picture too large" -error.

And being  the programmer i am, and having a few hours of post-christmas tranquility i immediately decided that i would rather make my own GIF-converter than manually resize my images to fit the online-converter.

Granted, the next few search results would probably solved my problem, but im allways trying to keep my coding skills from decay, and this presented it self as a good opurtunity.

So here is the result of a couple hours of dabbeling i Visual Studio:
The VisualStudio project can be downloaded as a .zip from this link

And a .gif example:


For some reason the gif will not loop, but im working on a fix for that.

Sunday, September 8, 2013

Finally got Skype to stop quoting my conversations

For many years i used MSN Messenger for instant messages. And with it i have tried alot of the alternative programs that connected with the MSN protocol, like Kopete, Pidgin and aMSN. Microsofts client was always full of ads and banners and retarded popup's. Along with unwanted features like nudges that made the whole screen vibrate and was particulary annoying if you had friends running any of the competing clients that had a reduced nudge-delay allowing them to spam your computer with shaky windows and twelve dosin doorbells going off.

All the competing clients worked well, had added functionality and no ads. But none of them ever got the emoticons right And while that's not a big deal for me now, it was very important when i was 13 and ended every line with a corresponding facial expression. Kopete had such bad smileys for a while that i got unsure about my friends actual attitude in the conversation. Like, "is he really smiling, or is that sarcasm. Shit that smiley lookin like John fuckin waterhead Kerry".

Microsoft then introduced Windows Live Messenger. A great example of shitty software.
First off all, the program it self was just a rebranded MSN Messenger. No added/fixed nothing.
New commercials now using Flash instead of gifs providing another 50mb of wasted RAM.
The installer was a new Windows Live installer. Wich was a great improvement. This way you would get 5 pieces of rubbish with every install, and shitty toolbars and bookmarks with your shitty Messenger.
The new installer also featured the ability to waste upward of 10 minutes on the install process, even with quad core computers. The installer also managed to rise to a size just shy of 120mb. Amazing, simply amazing.

I quote some random dude:
"Anyway, went to install this Windows Live messenger thing on there and it took absolutely AGES to install, and by the way I mean ages, nearly half an hour in fact it was so slow"

To compare, the latest version of pidgin is 9.1mb, supports 14 other protocols and installs in about the same time is takes to sneeze.

So as a last "fuck you" from Microsoft they terminated the entire Live Messenger and bought Skype as a replacement so they could ruin that as well.

Now i never really used Skype in the past, but i do now, and yes. It does kinda suck.

But now to the point of all this:
As i frequently discuss code with people on Skype i have been really annoyed by Skype's shitty attitude towards me copying text from my messages. Skype obviously thinks im a real journalist, and not just a dipshit blogger, and therefore types up the text as a quote like: "08:30 Sunday: Dick says: #1c3923 " when im really only after the color green.
I have been going on rants about this for weeks, thoroughly giving this software the finger, but then...
Turns out, it is possible to change this


Fuck i feel stupid.

Saturday, August 24, 2013

Surgon simulator 2013



Just recently tried out this game. It's available from Steam for download.
This is not a good game, but an amazing joke!

Experience the thrill of doing doubble kidney transplants and heart transplants while in the back of a speeding ambulance!


Thursday, June 6, 2013

Create .ico icons easy

In my last post a presented some work i did, and there is one thing i thaught i would shed a bit of light on, and that is icons.
I used mspaint to create my graphix this time, i'm a fan of Photoshop but for creating a simple icon like mine paint is a ok enough. And of course, Photoshop cost at least an arm and a leg, meaning less money for keg.

However, mspaint cannot simply save your image as a .ico file. And no, you cannot simply rename your .jpeg's either.


But there is a web service for just this, and it's free. It's http://convertico.com/ I have used it alot, and it's just great. And again.. FREE.
So, just save your file as .png and slam those .png's onto the webpage. And it will return you your .ico file within seconds, simple as that.

Wednesday, June 5, 2013

cAlarm

I just finished a project of mine. I ended up calling it cAlarm. It's and alarm clock capable of multiple alarms with repeat function for specific days of the week. When an alarm goes off it plays off a playlist of media files using winmm.dll, meaning it plays the media file as the form, but using whatever codecs you have on your system.


cAlarm implements a method for copying the files in a playlist to a folder. A feature i use all the time for copying music from my playlist in foobar2000 over to the USB drive i use in my car stereo. Foobar2000 is a great musicplayer btw.


The project also contains an example of serialization. Serialization is a way to save objects to files, and i have found it to be very useful and easy to implement. Im using it to save the list of alarms to a file, so the user can exit the program without loosing his alarms.


I have also tinkered around with some simple design features, like making a new-random color button that changes the layout's color to a random new one. Making all the forms have the same color when opened was something i didnt even consider untill now. Took abit of typing to get that integrated as well.


Tray icon is also in place. Alot more code than you would imagine.



So im putting this project up here so people can read the code, use the program, copy code, whatever really.

I still find faults and minor bug's every ten minutes i use this app, so what i upload here will probably be changed again in a few days and so on. The code is also rather sparse on comments at the moment, i might also fix that.

You can download the entire projectfolder as a .zip from this link.

Thursday, May 9, 2013

Controlling your Android phone through USB


There is an Android debugging tool called ADB that among other things lets you emulate keystrokes on your phone. For this to work your phone needs to be connected to your pc via USB, with your phone set to USB debugging mode:

Settings -> Developer options -> USB debugging -> On

You will also need to install drivers for your phone, in the case you (like me) have an HTC phone, you will need to install HTC Sync to get the driver.

ADB tools is part of the Android ADT bundle for windows or you can download it as a .zip file from my Google Drive here.

ADB is a command line program, so you'll run it through cmd.
An example:
adb shell input keyevent 66 - Will emulate pressing the enter-key

Now if you combine this with the ability to start intents (like the sms-dialog) you can make some useful scripts that you can automate in a regular .bat file.

adb shell am start -a android.intent.action.SENDTO -d sms: PHONENUMBER --es sms_body MESSAGE --ez exit_on_sent true  - This will open the sms-dialog, just swap insert a phonenumber and message.

And if you follow that by keyevent 22 (pad right to select the "send" button) and keyevent 66 (pressing enter to actually send the message) you now have the ability to send sms messages from you computer.
I do admit this is a rather flaky experience, since selecting the right button using predetermined keystrokes might fail on runtime if you for example have an app open on you phone when the script is executed. Or if your phone enters sleep and the screen locks before running the script.
But atleast it looks abit cool/scary seeing you phone type stuff without you touching it.

This is the full list of keyevents :
0 --> "KEYCODE_UNKNOWN"
1 --> "KEYCODE_MENU"
2 --> "KEYCODE_SOFT_RIGHT"
3 --> "KEYCODE_HOME"
4 --> "KEYCODE_BACK"
5 --> "KEYCODE_CALL"
6 --> "KEYCODE_ENDCALL"
7 --> "KEYCODE_0"
8 --> "KEYCODE_1"
9 --> "KEYCODE_2"
10 --> "KEYCODE_3"
11 --> "KEYCODE_4"
12 --> "KEYCODE_5"
13 --> "KEYCODE_6"
14 --> "KEYCODE_7"
15 --> "KEYCODE_8"
16 --> "KEYCODE_9"
17 --> "KEYCODE_STAR"
18 --> "KEYCODE_POUND"
19 --> "KEYCODE_DPAD_UP"
20 --> "KEYCODE_DPAD_DOWN"
21 --> "KEYCODE_DPAD_LEFT"
22 --> "KEYCODE_DPAD_RIGHT"
23 --> "KEYCODE_DPAD_CENTER"
24 --> "KEYCODE_VOLUME_UP"
25 --> "KEYCODE_VOLUME_DOWN"
26 --> "KEYCODE_POWER"
27 --> "KEYCODE_CAMERA"
28 --> "KEYCODE_CLEAR"
29 --> "KEYCODE_A"
30 --> "KEYCODE_B"
31 --> "KEYCODE_C"
32 --> "KEYCODE_D"
33 --> "KEYCODE_E"
34 --> "KEYCODE_F"
35 --> "KEYCODE_G"
36 --> "KEYCODE_H"
37 --> "KEYCODE_I"
38 --> "KEYCODE_J"
39 --> "KEYCODE_K"
40 --> "KEYCODE_L"
41 --> "KEYCODE_M"
42 --> "KEYCODE_N"
43 --> "KEYCODE_O"
44 --> "KEYCODE_P"
45 --> "KEYCODE_Q"
46 --> "KEYCODE_R"
47 --> "KEYCODE_S"
48 --> "KEYCODE_T"
49 --> "KEYCODE_U"
50 --> "KEYCODE_V"
51 --> "KEYCODE_W"
52 --> "KEYCODE_X"
53 --> "KEYCODE_Y"
54 --> "KEYCODE_Z"
55 --> "KEYCODE_COMMA"
56 --> "KEYCODE_PERIOD"
57 --> "KEYCODE_ALT_LEFT"
58 --> "KEYCODE_ALT_RIGHT"
59 --> "KEYCODE_SHIFT_LEFT"
60 --> "KEYCODE_SHIFT_RIGHT"
61 --> "KEYCODE_TAB"
62 --> "KEYCODE_SPACE"
63 --> "KEYCODE_SYM"
64 --> "KEYCODE_EXPLORER"
65 --> "KEYCODE_ENVELOPE"
66 --> "KEYCODE_ENTER"
67 --> "KEYCODE_DEL"
68 --> "KEYCODE_GRAVE"
69 --> "KEYCODE_MINUS"
70 --> "KEYCODE_EQUALS"
71 --> "KEYCODE_LEFT_BRACKET"
72 --> "KEYCODE_RIGHT_BRACKET"
73 --> "KEYCODE_BACKSLASH"
74 --> "KEYCODE_SEMICOLON"
75 --> "KEYCODE_APOSTROPHE"
76 --> "KEYCODE_SLASH"
77 --> "KEYCODE_AT"
78 --> "KEYCODE_NUM"
79 --> "KEYCODE_HEADSETHOOK"
80 --> "KEYCODE_FOCUS"
81 --> "KEYCODE_PLUS"
82 --> "KEYCODE_MENU"
83 --> "KEYCODE_NOTIFICATION"
84 --> "KEYCODE_SEARCH"
85 --> "TAG_LAST_KEYCODE"

Saturday, March 9, 2013

Linux is so intuitive!

Messing about with my linux desktop, i find myself googling the same stuff over and over again. Like, "how to install .deb files" my linux box is also my mediacenter making SSH my only keyboard-friendly interface.

Im here just dumping some commands, as a dictionary for myself mostly, and for others who might tend to google these things too:


install .deb package: (dpkg much more intuitive word than "install")
    sudo dpkg -i package.deb

remove file:
    rm "filename"

remove directory:
    rmdir "dirname"

remove directory with files in it (whyyyy so retarded?)
    rm -rf "dirname"

navigate to folder:
    cd "folder"

navigate back:
    cd ..

unzip tarballs: (i'm so glad it's not the same command for every extention)
        (zxf is so easy to remember. unzip would make no sense at all)
    tar zxf file.tar.gz
     tar zxf file.tgz
     tar jxf file.tar.bz2
     tar jxf file.tbz2

edit user permissions (and also lock yourself out of your system):
    sudo visudo

add something to startup:
    sudo nano /etc/rc.local
    (then add your command to the file before "exit 0")

Well, atleast there is no long hexadecimal error codes like in windows:



Thursday, February 7, 2013

Access .mdb database file from C#

My newest project requires me to keep a database with the email addresses of my clients, which my program will read and write to. To avoid the hassle of setting up a SQL server, and also since i'm familiar with using Microsoft Access, i decided on going with a database-in-file solution.


This presented the problem of figuring out how to do all this in C#, and after a good bit of googling i hacked together a class that retrieved the contacts list from the .mdb file as a DataTable, that i could show in my DataGridView by setting it as the DataSource:

private void Form1_Load(object sender, EventArgs e)
        {
            // Populate the dataGridView with the database content
            dataGridView1.DataSource = mdb_reader_class.readContactsTable();
            // Set proper column sizes
            dataGridView1.Columns[0].Width = 30;
            dataGridView1.Columns[1].Width = 200;
            dataGridView1.Columns[2].Width = 230;

            // Dont allow the user to resize the form (it's perfect as is)
            this.FormBorderStyle = FormBorderStyle.FixedSingle;

            // This goes for maximize button as well
            this.MaximizeBox = false;
        }
The mdb_reader_class.readContactsTable method:


public static DataTable readContactsTable()
{
    try
    {
        // Variables that will be used 
        string AccessDB = "folder-path\\Contacts.mdb";
        DataTable MyDataTable = new DataTable();

        // using an ridiculously long connection string, 
        // only reluctant to change it since it works
        OleDbConnection lConn;
        lConn = new OleDbConnection(
        "Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=" +
        AccessDB + ";Mode=Share Deny None;Extended Properties='';
        Jet OLEDB:System database='';
        Jet OLEDB:Registry Path='';Jet OLEDB:Engine Type=4;
        Jet OLEDB:Database Locking Mode=0;
        Jet OLEDB:Global Partial Bulk Ops=2;
        Jet OLEDB:Global Bulk Transactions=1;
        Jet OLEDB:Create System Database=False;
        Jet OLEDB:Encrypt Database=False;
        Jet OLEDB:Don't Copy Locale on Compact=False;
        Jet OLEDB:Compact Without Replica Repair=False;
        Jet OLEDB:SFP=False"
        );

        // connect to database
        lConn.Open();

        // using SQL 
        // Where 'Contacts' is the name of the table in the MDB file
        string lSQL = "Select ID, Name, Email from Contacts";  
        
        //This assigns the Select statement and connection of the data adapter
        OleDbDataAdapter dadapt = new OleDbDataAdapter(lSQL, lConn);  
        //This builds the update and Delete-
        //queries for the table in the above SQL. 
        //this only works if the select is a single table.
        OleDbCommandBuilder cb = new OleDbCommandBuilder(dadapt);    

        // populate the dataTable
        dadapt.Fill(MyDataTable);

        //Then save to the MDB file 
        dadapt.Update(MyDataTable);
        lConn.Close();

        // then return the datatable
        //dataGridView1.DataSource = MyDataTable;
        return MyDataTable;
    }
    catch (Exception)
    {
        // if an exception is thrown, a empty table is returned,
        // with one column named "Error"
        DataTable errorTable = new DataTable();
        errorTable.Columns.Add("Error!", typeof(string));
        return errorTable;
    }
}

Thursday, January 31, 2013

Send mail from your gmail account with C#

I'm currently working on a new project. I'm supposed to read from a USB temperature sensor, and log the temperature. And if the temperature is below a certain threshold temperature the application will warn the client thru mail.


And so now i have at least gotten the SendMail class working, and ready for implementation with the rest of the program. So here is the source code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;

namespace TempNET
{
    class SendMail
    {
        public string sendMail(string recieverMailAddress, string recieverName, string messageSubject, string messageBody)
        { // method for sending mail
            try
            {
                // using a GMail account
                var fromAddress = new MailAddress("gmailaccount@gmail.com", "Senders name"); 
                var toAddress = new MailAddress(recieverMailAddress, recieverName);
                const string fromPassword = "gmailaccount password";

                // create smtp client object containing all needed info
                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
                };
                // create mail
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = messageSubject,
                    Body = messageBody
                })
                {
                    smtp.Send(message);
                }
                // mail sendt successfully
                return "Mail sendt";
            }
            catch (Exception ex)
            {
                // something failed, return error message
                return "Error: " + ex.Message;
            }
        }
    }
}

Monday, January 21, 2013

My first Python app for Android, and it works!

I tried making a simple app for controlling the RaspberryPi lights controller i made earlier. It was to be a simple script, only really making a POST to a web-interface hosted on my LAN. However, simple tasks get really complex when the only tool you have is the most alien-ass backwards developing studio kit-SDK i have ever laid my eyes on. Yes im talking about AndroidADT/Eclipse.

God, please explain to me why a simple project template that only displays a blank screen need to consist of 131 Files divided across 66 Folders?!


And why does my 4 core computer, sporting 8Gb of ram and another gig of VRAM load for an amount of time that surely involves the Avogadro constant before it's able to run my simple app (displaying a blank screen). Yea, it... aint great.

So after Android-ADT and Eclipse just pissed me off to no end i decided Java could go fuck itself; my time is better spent on Python.

To run and develop Python on Android you need a Python interpreter installed on your phone. This was the main thing putting me off Python for phones in the first place, as it adds some complexity for the end user. But in my case that's usually just me anyways. Pluss it's really just an app that you need to download:
QPython+ and it's on google play store (for free).

QPython+ has a nice, no bullshit userinterface, and comes with some preinstalled libs, a text-editor and a debugger. Everything you need to develop, debug and run Python on your phone.

This below is my app in Python; 1 file, 0 folders. If my math is correct the complexity dropped by exactly half an infinity:

import urllib
# you need urllib to connect to the url
import androidhelper
# androidhelper is included in QPython+
# gives easy access to lots of android stuff, like GUI

droid = androidhelper.Android() 

def turnLights():
 # This displays a dialog with 3 options
 # Program loops untill user wants to exit
 while True:  
     title = 'Light switch:'
     droid.dialogCreateAlert(title)
     droid.dialogSetItems(['On', 'Off', 'Exit'])
     droid.dialogShow() 
     response = droid.dialogGetResponse().result['item']
     if response == 0:
            # The app connects to one of two url's
            # The web server at that url determines what
            # to do based on the page requested
            urlon = "http://192.168.1.6:8080/?turn=on"
            sock = urllib.urlopen(urlon)
            content = sock.read() 
            sock.close()
            print content
     elif response == 1:
            urloff = "http://192.168.1.6:8080/?turn=off"
            sock = urllib.urlopen(urloff)
            content = sock.read() 
            sock.close()
            print content
     elif response == 2: 
            # The user pressed Exit
            break 
# Run the app    
turnLights()

Python for Android is just awesome. Each app starts out as just one simple .py file. Easy as that. My app takes up 699 bytes. And i did bug-fixes and debugging on my phone and used the on-screen keyboard to add a couple of missing indents.

 My simple, beautiful app; a functioning light switch:


Sunday, January 20, 2013

Add a python script to startup

Im rather new to linux, and this was the first time ever that i had to get a python script running at boot, and with root privileges.
Have to say it was rather straight forward. Nothing special for python, just had to add a line of code in
/etc/local.rc
Just opened it in nano:
sudo nano /etc/local.rc

 
and added to the file:
sudo python /home/pi/turn.py


Wednesday, January 16, 2013

C# code to switch lights thru web-interface

Using the WebBrowser controll in Visual Studio 2010 it's really easy to make a interface to access the web and send data.

The code below is what makes up the desktop app that uses my python web interface to switch lights.

private void button1_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://192.168.1.6:8080/?turn=on");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://192.168.1.6:8080/?turn=off");
        }

The app is just a web browser that navigates to my web-interface with the click of the buttons. Displaying the web interface in the small browser window.

Tuesday, January 15, 2013

Flatcables, saves you from soldering to pins



Old HDD flatcables or floppydrive cables go perfect for the GPIO pins on the Pi.
No need to buy any expensive special connectors when you can just use left-over junk, right?
It's a messy setup i know, but it works, and with time it will be neatly wrapped and polished.

Raspberry Pi GPIO web interface using webpy

Finally made a web-interface for the GPIO on my Raspberry Pi that controlls the lights in my living room.
The script uses webpy, and starts hosting a webpage on port 8080 that listens for visitors and parameters:
If i open the page:
http://192.168.1.6:8080/?turn=on
Lights will be switched on.
And this next one switches them off again:
http://192.168.1.6:8080/?turn=off

I put the source together after reading this guide to webpy:
http://cloud101.eu/blog/2012/04/24/python-for-the-web-with-webpy/#more-

webpy is installed easy from apt-get:
       sudo apt-get install python-webpy

Here is the script:

#!/usr/bin/env python
# first line points to path for python

# we import the webpy library
import web

import RPi.GPIO as GPIO

#dont bug me with warnings
GPIO.setwarnings(False)

# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)

# set up GPIO output channels
GPIO.setup(18, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)

urls = ('/','root')
app = web.application(urls,globals())
 
class root:
 
    def __init__(self):
        self.hello = "snakes on a pie!"
 
    def GET(self):
        getInput = web.input(turn="")
        kommando = str(getInput.turn)
        if kommando == "on":
            #    set RPi board pins high
            GPIO.output(18, GPIO.HIGH)
            GPIO.output(16, GPIO.HIGH)
            return "Lights on"
        if kommando == "off":
            #    set RPi board pins low
            GPIO.output(18, GPIO.LOW)
            GPIO.output(16, GPIO.LOW)
            return "Lights off"
 
if __name__ == "__main__":
        app.run()

Saturday, January 12, 2013

How to display code on the web properly

When i started this blog, one of the problems i soon ran into was: how to display highlighted source code on my blog. You cant just copy it, because then the syntax-colors disapear and  it's unreadable.


blogspot.com has a [code] tag you can use, but it doesnt really do much, just changes the font really.

But i have found the solution:
http://tohtml.com/
It is a great site! It takes source code in pretty much any language and spits out HTML with beautiful highlighting that you can just copy and paste right to you blog.
Job done in short of a second.
http://tohtml.com/



C# method for printing ASCI images to console

Im currently taking a course in C# and the introductory is mostly console apps.
Console app are a nice, to-the-point programs, but after spending hours piecing it together its mind-rapingly terrible to watch such a dull interface.
So to spice things up abit and make the app truly your own it's nice to implement some ASCI art.


So you go download some ASCI image, for example here:
http://www.chris.com/ascii/index.php?art=cartoons/felix%20the%20cat
You copy paste it to a text file, lets call it felix.txt
Now problem is: how do you implement felix.txt into your console app?

So here is a C# method i wrote for just that. And it also implements delay. So you can make it look like a old school terminal, typing one char at a time (set timeout to 0 to just print the image)


static void printASCI_img(string file, int timeout)
        // prints ASCI text file to console
        // pause between every char given in milliseconds
        {
            try
            {
                byte[] img1;
                img1 = File.ReadAllBytes(file);

                foreach (byte i in img1)
                {
                    Console.Write(Convert.ToChar(i));
                    System.Threading.Thread.Sleep(timeout);
                }
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

Raspberry Pi GPIO example code in python

Im building a system for controlling the lights in my home from my raspberry pi.
So i've hooked up two solid state relays to the gpio pins om my RPi and i've made this python script for controlling it.

This script requires that you have installed RPi.GPIO
http://code.google.com/p/raspberry-gpio-python/
download the .deb file here

And you need to run the script as root since that's a requirement for access to the GPIO pins.

So currently i can run this script from my computer or phone via SSH, wich is alot better than walking around hitting switches, but im on a mission to develop a web-interface so it will be even more easy to use. Since not everyone in my household is tech savvy enough to make easy use of things like SSH.









# GPIO-OnOff.py
# written by fredrik 12.january.2013
#
# raspberry pi GPIO extentions
# requires root for access to the GPIO pins
import RPi.GPIO as GPIO

#dont bug me with warnings
GPIO.setwarnings(False)

# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)

# set up GPIO output channels
GPIO.setup(18, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)


x = 0
def on():
    print ("Lights On")
#    set RPi board pins high
    GPIO.output(18, GPIO.HIGH)
    GPIO.output(16, GPIO.HIGH)
 
def off():
    print ("Lights Off")
#    set RPi board pins low
    GPIO.output(18, GPIO.LOW)
    GPIO.output(16, GPIO.LOW)
 
menu = [off,on]
 
while x < len(menu) :
    print "Lights",menu[x].__name__,", press","["+str(x)+"]"
    x += 1
 
c = input()
menu[c]()




Wednesday, January 9, 2013

Is there a caffeinated cereal out there?!?

I woke up today after about 4 hours of sleep. Brain barely functioning, mixing milk in my cereal while chugging my third cup of coffee when i realize; "Hey! This is too many operations! I should be able to simplify this!" (or preferably someone else should simplify it for me)

milk + cereal = food
coffee = water + caffeine + black
milk = water + white

See how water for example is repeated several times. And those colors. I cant even see colors in the morning! So what i need is a cereal that contains my daily vitamins, my required 300mg caffeine. Even better if it contained dried milk also, so i could just add cold water!

morning_diet = food + vitamins + (3 * coffee)

Im so pissed off at this box being an aprils fool. Goddamn, it's been months, they could at least removed the link!
                                              Spazztroids - Caffeinated Breakfast Cereal