Wednesday, August 24, 2011

The RC Car Hack - Appendix A - Reference Code



The RC Car Hack - Appendix A
Code used


Summary

This is the working code used for the project.


Tutorial Contents

     This tutorial is broken into many parts/posts as there is plenty of content to show.

  1. Introduction
  2. Description of items/stuff used
  3. Getting inside your RC Car
  4. More soon...
  5. Code used (Reference)

Code in C#:

When starting a new winforms project, the following would be used in the main form. 


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace CIS169_SerialDemo
{
    public partial class frmSerial : Form
    {
        // Create a new instance of the clsSerial class
        clsSerial mySerial = new clsSerial();

        public frmSerial()
        {
            InitializeComponent();
        }

        // When a key is pressed, respond
        private void frmSerial_KeyDown(object sender, KeyEventArgs e)
        {
            string str = e.KeyData.ToString();

            if (!string.IsNullOrEmpty(str))
            {
                // The key is sent to the clsSerial (mySerial) class
                mySerial.writeSerial(str);
            }

            else
            { 
                
            }
        }
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Display the about form.
            // Create a new instance of the frmAbout form class
            frmAbout myAbout = new frmAbout();
            // Show the new aboutForm object.
            myAbout.ShowDialog();           
        }

        private void frmSerial_FormClosing(object sender, FormClosingEventArgs e)
        {
            mySerial.closeSerial();
        }
    }
}

As you might notice, the only significant part of that code is "mySerial" (at the beginning).  "mySerial" is created from the "clsSerial" class.  The following code is for the clsSerial class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace CIS169_SerialDemo
{   
    class clsSerial
    {
        // Making the serialport
        SerialPort mySerialPort = new SerialPort();
    
        // Constructor adds the needed details for the serial connection
        // and then open's the serial.
        public clsSerial()
        {
            setupSerial();
            openSerial();
        }

        private void setupSerial()
        {
                      // COM9 was where my bluetooth was located
                      // Your "PortName" may be different as your
                      // bluetooth may be located somewhere else
            mySerialPort.PortName = "COM9";
            mySerialPort.BaudRate = 9600;
            mySerialPort.Parity = Parity.None;
            mySerialPort.StopBits = StopBits.One;        
        }

        // Open the serialport, if its not available
        // then try again.
        private void openSerial()
        {
            try
            {
                if (!mySerialPort.IsOpen)
                {
                    mySerialPort.Open();
                }
            }
            catch (Exception e)
            {
                // Try again code would be posted but
                // I need to be able to test without the serial connection
                // openSerial();
            }
        }

        // Close the serialport 
        public void closeSerial()
        {
            if (mySerialPort.IsOpen)
            {
                mySerialPort.Close();
            }
        }

        // Used to write to the serial port and get the response
        public void writeSerial(string str)
        {
            openSerial();
            string cmd = str;
            // Checking for any value
            if (!string.IsNullOrEmpty(cmd))
            {
                mySerialPort.Write(cmd);
                // To ensure the conversation is going well, we listen for bot to speak
                          // After sending the command, the code on the Arduino will respond via
                          // the "Serial.println" portions to acknowledge the receipt of the message
                          // that we just sent.  The next lines listen for this.
                mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            }
        }


        

        // This is used to debug my commands sent
        /* 
         * After a command is sent from this machine, the other machine will
         * receive the command, respond back through serial, and act.
         * The console.write presents me with a way to check the 
         * command/response situations.
        */
        private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                SerialPort sp = (SerialPort)sender;
                string indata = sp.ReadLine();
                Console.Write(indata);
            }
            catch (Exception myexception)
            { 
                // For demo purposes... do nothing (not the coolest thing to do)
            }
        }
    }  
}
Code for Arduino:
     This is the sketch used for the Arduino.  (A sketch is the entire file containing the code for your Arduino)


/*
DMACC
CIS169
Sean

Main ref's:
arduino.cc
http://www.ladyada.net/make/mshield/index.html
http://www.sparkfun.com
MSDN
*/

// for the library (using/import)
#include <AFMotor.h>

// For the motors from the library
AF_DCMotor leftMotor(2, MOTOR12_64KHZ);
AF_DCMotor rightMotor(1, MOTOR12_64KHZ);

// variables
char val;         // variable to receive data from the serial port
int ledpin = 2;  // LED connected to pin 2 (on-board LED)
int counter = 0; // Used to toggle the LED


void setup()
{

  pinMode(ledpin = 13, OUTPUT);  // pin 13 (on-board LED) as OUTPUT

  Serial.begin(115200);       // start serial communication at 115200bps

 // set motor speed (range is 0 - 255)
  leftMotor.setSpeed(200);
  rightMotor.setSpeed(200);
}

void loop() {
  if( Serial.available() )       // if data is available to read
  {;}
    val = Serial.read();         // read it and store it in 'val'


 // All code follows the same format....
 // Respond, set the speed, action.


 // Turn in place to the left
  if( val == '0' )            
  {
    // Respond
    Serial.println("CMD: SPIN LEFT");
    // Set the speed
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
    // Action
    leftMotor.run(BACKWARD);
    rightMotor.run(FORWARD);
  }

  // if '1' was received led 13 is switched to it's opposite state
  if( val == '1' )  
  {
   toggle();
  }

    //stop
  if( val == '2')
  {
    Serial.println("CMD: STOP");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
 
    leftMotor.run(RELEASE);
    rightMotor.run(RELEASE);
  }

    // forward
  if( val == '3')
  {
    Serial.println("CMD: FORWARD");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
 
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
  }
   // backward
  if( val == '4')
  {
    Serial.println("CMD: BACKWARD");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
 
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
  }

  // forward to the left
  if( val == '5')
  {
    Serial.println("CMD: FORWARD LEFT");
    leftMotor.setSpeed(30);
    rightMotor.setSpeed(255);
 
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
  }

  // forward to the right
  if( val == '6')
  {
    Serial.println("CMD: FORWARD RIGHT");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(30);
 
    leftMotor.run(FORWARD);
    rightMotor.run(FORWARD);
  }

  // backward to the left, port side
  if( val == '7')
  {
    Serial.println("CMD: BACKWARD LEFT");
    leftMotor.setSpeed(30);
    rightMotor.setSpeed(255);
 
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
  }

  // backward to the right, starboard side
  if( val == '8')
  {
    Serial.println("CMD: BACKWARD RIGHT");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(30);
 
    leftMotor.run(BACKWARD);
    rightMotor.run(BACKWARD);
  }

  // turn in-spot to the right
  if( val == '9')
  {
    Serial.println("CMD: SPIN RIGHT");
    leftMotor.setSpeed(255);
    rightMotor.setSpeed(255);
 
    leftMotor.run(FORWARD);
    rightMotor.run(BACKWARD);
  }


}

// turn the LED on or off with one value
void toggle()
{
  if (counter == 0)
  {
    digitalWrite(ledpin = 13, HIGH);
    Serial.println("CMD: LIGHT ON");
    counter++;
  }
  else
  {
    digitalWrite(ledpin = 13, LOW);
    Serial.println("CMD: LIGHT OFF");
    counter--;
  }

}



Comments/Questions?
I'm always wanting to improve the quality of the content here.  If you have questions, want to see a better explanation, a better picture, let me know.  Thanks - Sean



No comments:

Post a Comment