Archive for the ‘Uncategorized’ Category

Interacting with the Arduino with C#

3. June 2010

No Comments »

There are times where you may want to build a nice user interface for your Arduino program to monitor input/output. In this tutorial, I will show you how to use C# to send data to and receive data from the Arduino. This tutorial assumes basic knowledge of Arduino programming and C#. For testing purposes, we will create a vary basic “echo” program that takes an input and outputs the input.

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  while(Serial.available()) {
      Serial.write(Serial.read());
  }
}

While there is data available, we read it, then write it to the output. Now open Visual Studio and create a new Windows Forms Application. I will name it ArduinoSerial.

From your toolbox, add two Label’s, two ComboBox’s, and a SerialPort. I have named them lblCOM, lblBaud, cboPorts, cboBaud, and serialPort1 respectively. ComboBox’s cboPorts and cboBaud which will allow the user to select which COM port the Arduino is using and the correct Baud rate to use.

To get the available serial ports, use the GetPortNames() method from System.IO.Ports.SerialPort. You can then add this array to cboPorts.

string[] serialPorts = System.IO.Ports.SerialPort.GetPortNames();
cboPorts.Items.AddRange(serialPorts);

For the Baud rate ComboBox I am simply going to enumerate the values.

cboBaud.Items.Add(2400);
cboBaud.Items.Add(4800);
cboBaud.Items.Add(9600);
cboBaud.Items.Add(14400);
cboBaud.Items.Add(19200);
cboBaud.Items.Add(28800);
cboBaud.Items.Add(38400);
cboBaud.Items.Add(57600);
cboBaud.Items.Add(115200);

The final constructor takes the following form:

public ArduinoSerial()
{
    InitializeComponent();

    string[] serialPorts = System.IO.Ports.SerialPort.GetPortNames();
    cboPorts.Items.AddRange(serialPorts);

    cboBaud.Items.Add(2400);
    cboBaud.Items.Add(4800);
    cboBaud.Items.Add(9600);
    cboBaud.Items.Add(14400);
    cboBaud.Items.Add(19200);
    cboBaud.Items.Add(28800);
    cboBaud.Items.Add(38400);
    cboBaud.Items.Add(57600);
    cboBaud.Items.Add(115200);

    cboPorts.SelectedIndex = 0;
    cboBaud.SelectedIndex = 2;
}

Next we are going to create a button called btnStart. This button will initiate the connection to the Arduino. In the code for the buttons click event, we first need to get the port from cboPorts. Then are are going to assign this value to the PortName attribute of the SerialPort object.

serialPort1.PortName = cboPorts.SelectedItem.ToString();

We are going to do the same for the BaudRate attribute.

serialPort1.BaudRate = Convert.ToInt32(cboBaud.SelectedItem.ToString());

Then we are going to open the connection (and toggle the Start/Stop buttons)

if (!serialPort1.IsOpen)
{
    btnStart.Enabled = false;
    btnStop.Enabled = true;
    serialPort1.Open();
}

In the btnStop click event is very similar to the above.

private void btnStop_Click(object sender, EventArgs e)
{
    if (serialPort1.IsOpen)
    {
        btnStart.Enabled = true;
        btnStop.Enabled = false;
        serialPort1.Close();
    }
}

Now we can create a TextBox and a Button called txtInput and btnSend. These two controls will be responsible for sending data to the Arduino. In the btnSend click event add the following code.

if (!serialPort1.IsOpen) return;
serialPort1.Write(txtInput.Text + "\n");

The rest of the magic takes place in the SerialPorts DataReceived event. To get the data from the serial port we simply call the ReadExisting() function on the SerialPort object. Then we just need to append that text to a text box. However, we must make this thread safe to prevent any dead locks.

/**
 * http://msdn.microsoft.com/en-us/library/ms171728(VS.80).aspx
 */
delegate void SetTextCallback(string text);
private void SetText(string text)
{
    if (this.txtOutput.InvokeRequired)
    {
        SetTextCallback d = new SetTextCallback(SetText);
        this.BeginInvoke(d, new object[] { text });
    }
    else
    {
        txtOutput.AppendText(text);
    }
}

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    try
    {
        SetText(serialPort1.ReadExisting());
    }

    catch (Exception ex)
    {
        SetText(ex.ToString());
    }

}

atime, mtime, and ctime

7. March 2010

No Comments »

On traditional Unix-style file systems three timestamps are associated with each file. These timestamps are atime, ctime, and mtime. Most people understand atime as “access time.” A file is accessed when its content is viewed or is executed. ctime and mtime generate confusion since “change time” and “modification time” seem synonymous. However, what you need to focus on is what is being changed. The mtime value is updated when the actual contents of the file are changed. However, updating mtime, also updates ctime. This does not mean an update to ctime will cause an update to mtime. The ctime value is updated when the files inode or change to the files content are made. For example:

# cat foo
Hello, World

Will update the files atime, but it will not effect the ctime or mtime.

# chmod 777 foo

Will update the files ctime but not the files atime or mtime.

# echo “Goodbye, World!” > foo

Will update the files ctime and mtime but not the files atime.

SEF URLs with out mod_rewrite

29. November 2009

2 Comments »

If you have done any web development, passing requests becomes an integral part of your code. Whether it is a session id, data to validate, or a view file to load you will most definitely end up passing one request or another. While working on my framework (which uses the model-view-controller design pattern), I decided to pass the controller, which the framework will load, through the URL. Since the controller’s primary purpose is to handle incoming http requests, I also passed a “view” parameter through the URL (which the controller will delegate accordingly). At this point, my URLs became unattractive index.php?module=Blog&view=index, which in todays world, of Web 2.0 sex appeal and search engine optimization, is just unacceptable. To circumvent the unsightly link, many developers choose to use mod_rewrite and define expressions in a .htaccess file. This is a perfectly legitimate practice for those of you who have mod_rewrite enabled on their server (and actually understand the rules). As an alternative, PHP’s $_SERVER['REQUEST_URI'] provides a cleaver solution.

What does $_SERVER['REQUEST_URI'] provide us with? Essentially, everything after the domain name. So if our URL is http://www.example.com/index.php?module=Blog&view=index, our URI is index.php?module=Blog&view=index. Moreover, if our URL is http://www.example.com/index.php/Blog/index, our URI is index.php/Blog/index. Using this, we can simply manipulate the URI to process incoming requests. First, we want to explode the URI at the file name, in my case it is index.php.

$requests = explode("/index.php/", $_SERVER['REQUEST_URI']);

$request is now an array whose first element is everything before and including index.php, and whose second element is everything after index.php. By manipulating $requests[1] we can use that data as our data.

$requests = explode("/index.php/", $_SERVER['REQUEST_URI']);
$uri = explode('/', $requests[1]);

The $uri array now contains all our disguised requests, which we can use in the same way as a $_GET request (with the exception of a sexier URL).

With three lines of code we have transformed a ugly looking URL http://www.example.com/index.php?module=Blog&view=index to http://www.example.com/index.php/Blog/index (a URL the most avid Web 2.0 gurus would find acceptable).

The Laplace Transform

27. November 2009

No Comments »

Pierre-Simon De Laplace (23 March 1749 – 5 March 1827) was a French mathematician and astronomer. In 1796 he formulated a nebular hypothesis of cosmic origin and was one of the first scientists to postulate the existence of black holes. He later proposed a solution to irregularities in Newton’s calculations and presented them in a work called Mécanique céleste. According to legend, when asked by Napoleon why God did not appear in his discussion, Laplace replied “I had no need of that hypothesis.” Among many discoveries, Laplace is most notable for the Laplace Transform which aids in solving differential equations by allowing for the transformation of an equation from the time domain to the frequency domain.

For a signal x(t), its Laplace transform X(s) is defined by
[latex]\mathrm{X(s)=}\int\limits_{-\infty}^{\infty}\mathrm{x(t)}e^{-st}dt[/latex]

Example: For a signal x(t) = e-atu(t) find the Laplace transform X(s).

By definition
[latex]\mathrm{X(s)=}\int\limits_{-\infty}^{\infty}e^{-at}u(t)e^{-st}dt[/latex]

Since u(t) = 0 for t < 0 and u(t) = 1 for t ≥ 0,
[latex]\mathrm{X(s)=}\int\limits_{0}^{\infty}e^{-at}e^{-st}dt = \mathrm{X(s)=}\int\limits_{0}^{\infty}e^{-(s+a)t}dt = -\frac{1}{s+1}e^{-(s+a)t}\big|_{0}^{\infty}[/latex]

Thus we can conclude
[latex]\mathrm{X(s)=}\frac{1}{s + a} \mathrm{for Re(s + a) > 0}[/latex]

Growing A Language

21. October 2009

No Comments »

I watched this video in its entirety. I found it very interesting how he got his point across.

Guy Steele’s keynote at the 1998 ACM OOPSLA conference on “Growing a Language” discusses the importance of and issues associated with designing a programming language that can be grown by its users.

Slow Network Transfer with Vista

26. June 2009

No Comments »

The Windows Vista TCP/IP stack came packed with a multitude of new features, one being Receive Window Auto-Tuning. The TCP receive window size is the amount of data that a TCP receiver allows a TCP sender to send before having to wait for an acknowledgment. After the connection is established, the receive window size is advertised in each TCP segment. Advertising the maximum amount of data that the sender can send is a receiver-side flow control mechanism that prevents the sender from sending data that the receiver cannot store. A sending host can only send at a maximum the amount of data advertised by the receiver before waiting for an acknowledgment and a receive window size update.

While the intention of this feature is to enhance user experience, this has certainly not been the case for me. Rather than improving network transfers it caped mine at 50kb/s. To disable Receive Window Auto-Tuning open up an elevated command prompt and issue the command:

netsh interface tcp set global autotuninglevel=disable

Computer Science vs. Computer Engineering

23. May 2009

11 Comments »

When I was a high school student the whole notion of college seemed abstract – somewhere way off in the not-so-distant future. I had an idea of where I wanted to be in ten years, but the path that would lead me there was dark. My high school advisor did the best job she could do, but there were numerous technical questions she was unable to answer. For example: What is the difference between computer science and computer engineering? In an effort to decide what I wanted to major in, and thus which schools I would apply to, I googled it. I found a few resources and ultimately decided I would major in computer engineering, even though what computer engineering would entail was still very unclear.

In 2007 I started my freshman year at SUNY Buffalo as a computer engineer. My first and second semesters were mostly filled with general education requirements (English, American pluralism, ect…). However, like most curriculums I took two basic programming classes where I learned Java. I was suppose to learn other more important things like the concept behind object oriented design and other software development methodologies, but for some reason they did not become apparent until much later. My third and fourth semesters were filled with mostly general engineering classes which included calculus, differential equations, physics, and chemistry as well as a few others and one computer science class – algorithms and data structures and one electrical engineering class – [analog] circuit analysis. At the end of my fourth semester I finally made an appointment with my academic advisor. We went over my success path for the remaining four semesters which were mostly filled with electrical engineering classes. I felt like I was in a difficult position. I enjoy programming and I enjoy computer science. However, there were very few computer science classes in my schedule. Moreover, I am not particularly fond of the typical computer-science-type-of-job stereo type. You know… the one where some geek with a pocket protector sits in a small four foot by four foot cubicle office with no window. Yeah… that’s not really my cup of tea. I want something more hands-on. It was at this point where I took some time to evaluate what I really wanted to learn and what really wanted to do after college. The questions I asked myself were the similar to the ones I had in high school. Should I switch to a computer science? Should I switch to electrical engineering? Should I do nothing and remain a computer engineer? After some deep consideration I concluded I had no effing clue. Thus I decided to play it safe double major in computer science and electrical engineering and get the best (and worst) of both worlds.

Computer engineering provided me with some computer science and some electrical engineering, and although on average, a newly graduated computer engineer will make more money than a computer scientist due to their variety of knowledge, a computer scientist with a specialization is likely to make more money than the average computer engineer as with a specialized electrical engineer. A computer engineer is a “jack of all trades,” and thus the curriculum made it difficult to specialize in any particular field.

However, engineering and more particularly electrical engineering is not for everyone. If you suck at math, do not care about hardware, or just want to write code for a living, then computer science is what you should major in, but from experience, programming gets old, quickly. On the other hand if you hate writing code but enjoy working with computer hardware you probably want electrical engineering. If you enjoy programming and hardware or enjoy how the two abstractions interact, you want computer engineering. However, for all you high school students who are reading this, despite what you think you want to major in, I recommend giving computer engineering a shot. It will give you the best of both worlds, and toward the end of your sophomore year, if you realize you do not like hardware you can easily switch to computer science (as the majority of the curriculum overlaps), or if you are like me and enjoy both stick with it or get more for your money and double up.

Password Guessing

21. May 2009

No Comments »

One of the more common cracking methods used is password guessing. Luckily (or unfortunately) it is one of the least efficient methods used. Password guessing comes in two forms of attacks:

  • Brute force attacks
  • Dictionary attacks

Brute Force Attacks
A brute force attack is exactly as it sounds – brute force. It it is an attack to thwart a cryptographic scheme by guessing all permutations of a particular character set and length. For example, if our cracker knew the password was four digits, the maximum amount of guesses needed would be ten thousand. Since the password is four characters in length, and each character can be a digit we have:

10 10 10 10 = 10,000

Which yields ten thousand passwords. A brute force attack would try each password systematically. For example:

0000
0001
0002
0003

1111

For a human to guess all of these passwords would be impractical, but with today’s technology ten thousand operations can be done in a few seconds on a single processor machine. Two tools which use brute force attacks that I have used are BarsWF and LOphtCrack. BarsWF is incredibly interesting as it uses CUDA which makes use of your GPUs as well as your CPUs to crack an md5 hash. I was computing close to 100,000 hashes per second!

Dictionary Attack

A dictionary attack is similar to a brute force attack, except rather than trying every combination, it only guesses password from a file provided by you. Granted, this method is not guaranteed to work, but it is guaranteed to finish before your grandchildren are born. Remote-exploit.com released a tool called CUPP which allows you to generate personalized dictionaries.

Security

Some of the security I employ to stay safe (from both a client and server perspective) are:

  • Use complex passwords – Not your wifes name or even your wifes name concatinated with her birth year. Use something truly difficult like: 4k!da9dCaF. A dictionary attack will not be able to break this password (unless you are really unlucky) and it will take a brute force program a really long time to crack.
  • Implement a lockout or wait time (or both). A brute force attacker will try thousands of passwords per second. If you can disable the account after five incorrect password attempts, and after a certain time period reactivate the account, the attacker is screwed.

Note that the MySQL client library is not bundled anymore!

9. May 2009

No Comments »

Unable to get PHP configured to my specifications using the Ubuntu repositories, I decided to install it from source. However, I kept getting the error:

Note that the MySQL client library is not bundled anymore!

Not wanting to install MySQL from source, I found a package in the Ubuntu repositories that installed the necessary library files.

sudo apt-get install libmysqlclient15-dev

After I installed that package, PHP was able to install successfully.

Slow connection to Ubuntu repositories

9. May 2009

No Comments »

While attempting to get a fully functional LAMP stack running on my Ubuntu install, I opted to use the repositories for some necessary libraries. The first package I installed was approximately 20MB and it took about three hours. While it was downloading (since I had some spare time), I checked my internet connection. I soon found out that it wasn’t my ISP since I was getting 12Mb/s down. I also scanned the Ubuntu forums for any sign of server maintenance that could be causing the slowness. I didn’t find anything. I then tried changing the repository download location:

System->Administration->Synaptic Package Manager from there Settings->Repositories. From the “Download from” drop down, select “Other.” Click on “Select Best Server” will ping all of the repository locations and select the location with the best ping.

That didn’t help either. After many fruitless attempts I narrowed the fault down to my router. I upgraded its firmware and that fixed it!