Programming chipKIT Boards from MPLAB® X IDE Without a Programmer/Debugger

Overview:

Did you know that you can program your chipKIT board or any PIC32 chip preprogrammed with a chipKIT Bootloader right from MPLAB X? It’s actually quite easy to do. This tutorial will demonstrate how to obtain the proper binaries and how to set up MPLAB X to download programs written in C or MIPS Assembly to a PIC32 using the AVRdude bootloader. Note that this tutorial including screen captures was done using a Windows® 7 PC.

What you will need:

To complete this task, you will require the following:

Procedure:

  1. Unzip the chipKIT MPIDE to a location on your computer
  2. Navigate to the MPIDE folder an locate avrdude.exe and avrdude.conf in the following folders:
    1. avrdude.exe: mpide-0023-windows-xxxxxxxx\hardware\tools\avr\bin\avrdude.exelocateAVRdude
    2. avrdude.conf: mpide-0023-windows-xxxxxxxx\hardware\tools\avr\etc\avrdude.conflocateCONFfile
  3. Copy both of these and paste into your MPLAB X directory: C:\Program Files\Microchip\MPLABX\mplab_ide\binmplabXBin*Note: MPLAB X IDE will need to be installed on your computer for this folder to have been created.
  4. Next, open MPLAB X and set up your project as you normally would and write your code. (If you are not familiar on how to do any of these please refer to the tutorials towards the bottom of our Academia page: http://chipkit.net/academia/)
  5. The bootloader pre-programmed on the PIC32 does take up some room in Flash program memory. Therefore, to make sure we do not overwrite the bootloader, we will need to tell MPLAB X where to put our program code. This will be done using a linker script. There are special linker scripts in our MPIDE download that are already formatted to accommodate the bootloader. In the MPLAB X IDE Project window, right click on the Linker Files folder and select Add Existing Items…. In the dialog, navigate to where you unzipped MPIDE and locate the linker script for your particular device (PIC32MX250F128B used in this tutorial). It will be called something like “chipKIT-application-32MX250F128.ld”. You will also need an additional script called “chipKIT-application-COMMON.ld”. Select both of these files, check the Copy checkbox, and press Select to close the window and add these files to your project folder.addingLDscripts
  6. We will need to make some changes to these linker scripts. Double-click on the part-specific linker script (chipKIT-application-32MX250F128.ld in this tutorial) to open it. Scroll down through the linker script to the last line and uncomment the section:
     INCLUDE "chipKIT-application-COMMON.ld"
  7. Double-click on the “chipKIT-application-COMMON.ld linker” script. Scroll down to approximately line 574 and comment out the line:
     /* ASSERT (SIZEOF(.header_info) == 76, "MPIDE Version not specfied correctly")*/
  8. Next, we will need to let MPLAB X know that we wish to use avrdude to program the PIC32. Therefore, right-click on your project and select Properties to open the Project Properties window.openMPLABXproperties
  9. In the Project Properties Window, select the Building category. On the right side of the window, check the Execute this line after build check box and add the following code to the text field under the check box:
    "C:\Program Files\Microchip\MPLABX\mplab_ide\bin\avrdude.exe" -C "C:\Program\Microchip\MPLABX\mplab_ide\bin\avrdude.conf" -v -p32MX250F128B -cstk500v2 -P COM49 -b 115200 -U flash:w:${ImagePath} selectExecuteAfterBuild
    Some important things to note here:
    1. You will need to make sure you’ve selected your MCU if not using the PIC32MX250F128B as shown in the example.
    2. Similarly, you will also need to change the COM port to the one assigned to your chipKIT Platform. The COM port can be found in your Device Manager (on Windows machines)
  10. Finally, to program your PIC32, make sure that it is in bootloader mode. Depending on the board you have, this may require that you press some buttons or this could be done automatically through the use of an FTDI UART-to-USB chip on the board. Once in bootloader mode, click either the Build or Clean and Build button. Following build, the avrdude bootloader should be called and the PIC32 programmed over the COM port selected with your code. 
  IMPORTANT!! The bootloader will be executed anytime you select Build, Clean and Build or if you attempt to enter Debug mode. The bootloader often resides in sections of memory that are used for debugging. Therefore, if you enter debug mode and your PIC32 is connected to your computer, there is a good chance you will overwrite the bootloader and it will need to be programmed back onto the chip using an external programmer/debugger.  Therefore, always disconnect the USB cable if you plan on doing any code debugging with the simulator. You will not be able to do hardware debugging. A programmer/debugger is needed for that. You will also need to deselect the Execute this line after build checkbox in the Project Properties>Building window shown in Step 9. Otherwise you will receive an error.    
VN:F [1.9.22_1171]
Rating: 8.2/10 (11 votes cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)

The Arduino™ Blink Sketch on chipKIT DP32

Overview:

In this tutorial, the standard “Hello World” program (blinking LED) is used to help familiarize you with the chipKIT DP32 board and how it will interface with  the Multi-Platform Integrated Development Environment (MPIDE) and basic language functions.  

Reference:

During the course of this tutorial, various terms will be referenced including:
  • Sketch
  • Function
  • Variable
  • HIGH and LOW
  • INPUT and OUTPUT
We recommend that you read the following sections on the Arduino™ homepage to get a better understanding of these terms:

Hardware Used:

The hardware used in this tutorial will be the chipKIT DP32 manufactured by Digilent Inc. The reference guide for this board, schematics and other resources are available on the chipKIT DP32 homepage at: http://www.digilentinc.com/Products/Detail.cfm?NavPath=2,892,1174&Prod=CHIPKIT-DP32  

Software Used:

In this tutorial, the chipKIT MPIDE will be used. If you haven’t already, follow the instructions at the links below to download MPIDE for your operating system:

Hardware Setup:

The DP32 can be powered in a number of ways including from the USB connection (J2) or over the screw terminal (J6). The user needs to select which method will be used to power the board by configuring the jumpers immediately next to the screw terminal as shown below:  

 jumper config

   

Procedure:

  1. Open MPIDE, by navigating to the extracted files in the folder you selected when you downloaded the source files. Locate the MPIDE executable (Windows® folder shown): openMPIDEopenMPIDE Double click the executable to open the MPIDE  Hint: At this point it is a good idea to create a shortcut to the mpide.exe and place on your desktop.
  2. The first time you open MPIDE, you will be notified that a “sketchbook folder” will be created. In Windows, this folder will be located in the “My Documents” directory. scketchbookFolder Click OK to continue.
  3. The MPIDE Window should appear. Note the following main areas of the IDE Window.MPIDE Workspace button overview
  4. The chipKIT MPIDE comes with a variety of examples that can be used to help explore some of the various features of both the MPIDE and the chipKIT Platform. To access these examples, select File>Examples.EXAMPLES Note that there are all kinds of examples from lighting an LED on the chipKIT Board to different types of displays.Under File>Examples>Basic, there is an example called Blink. This example blinks an LED on the chipKIT Board ON/OFF in 1 second intervals. This little program is what is known as the “Hello World” program as it is usually the first application new users create who are using a Microcontroller for the first time.This example could easily be opened and run as is. However, in order to highlight some of the features of the MPIDE, this example will be recreated from scratch.
  5. Click on the “New” button to open a new sketch window and then click “Save” button. Name the sketch something meaningful like DP32_Blink.  The default directory will be the mpide folder created when the MPIDE was first started. Note: If you navigate to the mpide folder, there will now be a new folder with the name of the sketch you just saved.
  6. In this part of the tutorial, you will create a simple routine that will blink LED 3 on the DP32.dp32 Add the following code into the MPIDE editor:
    int ledPin = 43;                 // LED connected to digital pin 26
    void setup()
    {
      pinMode(ledPin, OUTPUT);      // sets the digital pin as output
    }
    void loop()
    {
      digitalWrite(ledPin, HIGH);   // sets the LED on
      delay(1000);                  // waits for a second
      digitalWrite(ledPin, LOW);    // sets the LED off
      delay(1000);                  // waits for a second
    }
  7. There are quite a few things going on with this sketch. Under the “References” section at the top of the page, links are provided that will explain much of the content.Next, we will upload our code to the DP32.
  8. Make sure that the chipKIT DP32 is connected via the mini-B connector on the board to an availableUSB port on the computer.
  9. In MPIDE, select Tools>Board>chipKIT>chipKIT DP32 to identify the DP32 Board as a target select boardselectboard

    Next, you will need to place the DP32 into “Programming” or “Bootloader” mode; otherwise, the sketch will not be able to be uploaded to the board. To enter into this mode, hold down the RESET button followed by the PGM button, then release the RESET button first, followed by the PGM button. You will know you’ve done this correctly if LED1 begins to flash repeatedly. dp32_BUTTONS

    When the DP32 is in Bootloader mode, LED1 on the board will begin to flash on/off.

  10. Next, select Tools>Serial Port>COMxx. This will depend on which port was assigned to the chipKIT DP32 Board when first connected.selectserialport
  11. To load your sketch onto the chipKIT DP32 board’s Microcontroller, press the upload button. This will compile your sketch (check for errors) and then send to the Microcontroller.
 

Verifying Operation:

After the sketch is sent to the chipKIT DP32 board’s Microcontroller, LED 3 on the chipKIT DP32 should flash on and off in 1 second intervals.  
VN:F [1.9.22_1171]
Rating: 6.5/10 (6 votes cast)
VN:F [1.9.22_1171]
Rating: -1 (from 1 vote)

How to Add a Custom Board to MPIDE

chipKIT MPIDE Board Variant Mechanism

The chipKIT MPIDE system has been designed to make it relatively easy to adapt the operation of the system to new hardware as boards are designed. We’ve put together a document that describes the mechanisms used in the system to allow a board developer to describe the features of a new board to the system and allow the system to use the new board without the need to modify any of the core hardware abstraction layer code or standard libraries.

The board variant mechanism makes use of a standardized folder structure and set of definition files that can be installed into the MPIDE system that adapt the system to work with new boards. In some cases, these files are distributed with the MPIDE, but board variant files can be easily added into an installation of MPIDE after it has been installed on the client computer.

In addition to the board variant mechanism described here, a developer designing a new board will also need to produce a boot loader for the board. Note that this document does not describe the process required to create a new custom boot loader from the boot loader project, as that process is described in a separate document.

To learn more, download the full guide here.

VN:F [1.9.22_1171]
Rating: 6.1/10 (8 votes cast)
VN:F [1.9.22_1171]
Rating: -3 (from 3 votes)

DC Motor Control using Raspberry Pi, chipKIT Pi and the Arduino Motor Control Shield

Overview

This post is intended to demonstrate compatibility of the chipKIT Pi with certain existing Arduino shields. In the second part of this post, we will also demonstrate how to communicate with the chipKIT Pi over a simple I/O line on the Raspberry Pi®, from a terminal window, to control the Arduino™ shield connected to the chipKIT Pi.

Hardware/Software Needed

Procedure

Let’s begin by simply controlling a common Arduino shield. NOTE: Always check the electrical characteristics of any shield that will be connected to the chipKIT Pi. As with the Raspberry Pi, this is a 3.3V system. Therefore, if a shield outputs voltages greater than 3.3V there is a possibility that you could damage the chipKIT Pi or the Raspberry Pi. Connect the Arduino Motor Control Shield as shown:
motor shield 1
  1. Start a new sketch in MPIDE
  2. We will be using Brian Schmalz’s SoftPWMServo library for this application. This is a very flexible library that will enable a PWM (square wave) output on any pin we like. This library comes already included as a core library with the MPIDE. Therefore, to use, simply add the header file to the library at the top of your sketch as follows:
      #include <SoftPWMServo.h>
  3. The remainder of the sketch follows set up as per the Arduino Motor Control Shield specifications. I’ve added comments to explain each line of code.
    //Include the SoftPWMServo Library
    #include<SoftPWMServo.h>
    void setup() {
      //set up channel B on the Arduino Motor Control Shield
      pinMode(13, OUTPUT); //Pin 13 controls direction
      pinMode(8, OUTPUT); //Pin 8 controls the brake
    }
    void loop() {
      //Turn the motor
      // First we disengage the brake for Channel B
      digitalWrite(8,LOW);
      //Depending on how your motor leads are connected to the Arduino
      //motor B header, the direction could be clockwise or counter clockwise
      //So let's just start by calling this direct 1 and drive pin 13 HIGH
      digitalWrite(13,HIGH);
      //We need to send a PWM to the Arduino MC shield to start the motor
      //turning. We also define a duty cycle that will set the motor speed.
      //The higher the duty cycle, the faster the motor will turn. Duty cycle
      //is set between 0 and 255.
      //So we send the PWM to pin 11 according to the Arduino MC specs at say
      // a duty cycle of 100
      SoftPWMServoPWMWrite(11, 100);
      //Let's run the motor for about 5 seconds
      delay(5000);
      //Now lets brake the motor
      digitalWrite(8,HIGH);
      //Give the motor a chance to settle
      delay(500);
      //change directions
      digitalWrite(13,LOW);
      //and run the motor for about 5seconds in the other direction
      delay(5000);
      //Again, we brake the motor
      digitalWrite(8,HIGH);
      //give the motor a chance to settle
      delay(500);
      //and repeat
    }
So, this is nothing really special and can be done on any chipKIT Board. However, we can make something pretty interesting by introducing some Python-based communication from the Raspberry Pi to the PIC32 MCU on the chipKIT Pi. Proceed to the next page to continue.
VN:F [1.9.22_1171]
Rating: 6.6/10 (10 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

chipKIT Design Challenge Winners

  We are pleased to announce the winners of the chipKIT Platform Design Contest.

Winning Entries:

 

Level 1 Challenge

ck761 ROV Controller  http://www.youtube.com/watch?v=_24bMhLS7Wo&list=PLXPjvBuqmMX5DkKE8Ni0FNN7o-nwPIYUU ROV_ck761 Develop an original application using a chipKIT platform, an existing, known-working shield, and existing, known-working libraries. Participants will have the choice of using a chipKIT Max32, Uno32 or uC32 platform.

Level 2 Challenge

ck758    OLED Screen Controller Demo  http://www.youtube.com/watch?v=4x3swzNr14Y&list=PLXPjvBuqmMX6KYPXqucRqc8uklqbSP8iZ OLED_ck758 Develop an original application using a chipKIT platform and an existing shield where associated libraries are modified to exploit specific features of the chipKIT platform’s PIC32 device and associated peripherals. Participants will have the choice of using a chipKIT Max32, Uno32 or uC32 platform.

Level 3 Challenge

ck765    KEELOQ Shield  http://www.youtube.com/watch?v=NVPb-qaEu8k&list=PLXPjvBuqmMX6dKnPE-AY-IAW4HqxAhIfn Keeloq_ck765 Develop an original shield that will highlight the additional functionality of the PIC32 devices populating the chipKIT platform. Participants will have the choice of using a chipKIT Max32, Uno32 or uC32 platform.

How Winners Were Determined

Winning entries were determined through the use of a survey grading each application on:
  • Overall impression of application
  • Use of unique peripherals found on the target MCU
  • If developer modified or created a new library
  • Documentation on hardware, libraries and tutorials 
Congratulations to all who participated. You all did an amazing job!! Please visit the contest YouTube channel to view all entries at www.youtube.com/chipkitcontest     
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

DIY chipKIT Board Using a Through-Hole SPDIP PIC32

Overview:

Certain varieties of Microchip Technology’s PIC32 Microcontrollers are available in Small Plastic Dual In-line Packages (SPDIP). This packaging makes it very easy to build up your own chipKIT board at home using common tools found in the home hobbyist/Maker workshop. Other 32-bit platforms would require specialized equipment to solder their fine pitch packaging to a custom board.

This post will demonstrate how to build up a chipKIT Platform onto a solderless breadboard using a PIC32MX250F128B 32-bit Microcontroller and some readily available components.

NOTE: This application uses a voltage provided off of the USB line. This is adequate for Low Power application such as blinking a single LED. However, most applications will require that you connect a separate power source to the Vin input of the Voltage Regulator such as a battery (shown at the end of this post). Excessive application power consumption could damage your USB port.

Components list:

The following components were used to complete this project

  • The TCHIP-USB-MX250F128B: Microchip PIC32MX250F128B in SPDIP package preprogrammed with the chipKIT USB Bootloader
  • Microchip MCP1702-3302E/TO: 3.3V LDO Voltage Regulator in TO-92 package
  • 8MHz Crystal Oscillator
  • 4 x 0.1uF Capacitors
  • 1 x 10uF Tantalum or Ceramic capacitor (note: needed for low ESR characteristics)
  • 2 x 36pF Capacitors
  • 1 x 130Ω Resistor
  • 4 x 10kΩ resistors
  • LED
  • 2 x SPST Tactile Switches
  • Some sort of way to connect a USB cable to the breadboard. I used a Sparkfun BOB-09614 USB-mini Breakout board 
COMPONENTS

Schematic:

schematic

Procedure:

Insert the PIC32MX250F128B into a solderless breadboard. Be sure to connect all of the Vdd (3.3V) and Vss (0V) signals as shown. Be sure to double check the datasheet pin diagram shown below:

VoltageBlock

power_ground

Note that some pins are not labeled as Vdd or Vss but will need to be connected to these voltages for the application to function. This includes pins related to USB and our Analog peripherals on the Microcontroller. Also note that the 3.3V Vdd signal will be coming off of our MCP1702 3.3V regulator. Connect the GND to a breadboard rail that will be dedicated to Vss and the Vout pin to a breadboard rail that will be dedicated to Vdd. Also connect a 0.1uF capacitor to the Vin and Vout pins to GND. The pin out diagram for the MCP1702 is shown below: MCP1702_pinout MCP1702

Next, the USB breakout board will be connected as follows:

  • Provide the Vin signal for the MCP1702
  • Connect the D- and D+ data lines
usb_MCP1702_Conn
usb_data

There is a Voltage Regulator on the PIC32MX250F128B Microcontroller that regulates internal voltage down to 1.8V to meet the requirement of the core. You don’t really have to worry about this other than you will need to connect a low ESR capacitor such as a Tantalum type to the Vcap pin on the Microcontroller to ground (Vss) as shown: vcap_pinout vcap

This particular version of the chipKIT Platform will use the PIC32MX250F128B’s on-chip USB peripheral instead of the standard way of doing things with the FTDI chip. Therefore, we will need to tell the PIC32 when to go into “bootloader” mode. In order to download a sketch, the PIC32 will need to be in this “bootloader.” To do this, two pushbuttons are used. One to RESET (turn on and off) the microcontroller and a second PROGRAM pushbutton that you will press down while the Microcontroller comes out of RESET. Coming out of RESET, the Microcontroller notices that the pin connected to the PROGRAM pushbutton has been driven HIGH (3.3V) and will automatically enter into “bootloader” mode.

The RESET pushbutton is connected to the MCLR (pin 1 of the Microcontroller) through a 10kΩ resistor that will limit current. The MCLR pin, when driven low, will cause the PIC32 to RESET. Therefore, another 10kΩ resistor is used to pull the line up to 3.3V that will keep the device out of RESET. One lead of the pushbutton is connected to this 3.3V signal and the other to Vss. Therefore, when the pushbutton is pressed, the Microcontroller will notice that the MCLR pin is driven LOW and will enter into RESET mode.

Similarly, the PROGRAM pushbutton is connected to the RB4 (pin 11) on the PIC32 through a current limiting 10kΩ resistor. However, this time the pin is held LOW through a 10kΩ pull down resistor since the a HIGH signal on this pin tells the Microcontroller to enter “bootloader” mode: pushbutton block pushbuttons

Finally, the USB bootloader is based off of an 8MHz external crystal oscillator. The oscillator is connected to the OSC1 and OSC2 pins on the PIC32 and 36pF capacitors are connected to each to ground as shown: oscillator_block oscillator

Next, I added a 130Ω resistor connected to pin 16 then to an LED connected to ground.

led

The final circuit should look something like this:

final circuit microB

To connect to a battery source, disconnect the Vin input to the MCP1702 from the USB connector and connect to the positive terminal of a battery as shown. Make sure that the battery’s negative terminal is connected to the Vss rail on your board.

battery_connection

Testing the Application:

To test the application, we will create a sketch to blink the LED on pin 16, connect the board through the USB, and download the sketch.

Download MPIDE (a FREE download) from the Install page and install it, and then follow these instructions.

  1. Open up MPIDE and create a new sketch with the following code:
  2. /*
      Blink
      Turns on an LED on for one second, then off for one second, repeatedly.
    
      This example code is in the public domain.
     */
    
    void setup() {
      // initialize the digital pin as an output.
      // Digital pin 24 has the LED connected to it
      //For more information including a pin diagram please visit www.chipkit.net/diy-chipkit-board
      pinMode(24, OUTPUT);
    }
    
    void loop() {
      digitalWrite(24, HIGH);   // set the LED on
      delay(1000);              // wait for a second
      digitalWrite(24, LOW);    // set the LED off
      delay(1000);              // wait for a second
    }
    
  3. Connect the application through the USB connector to your computer.
  4. If the driver is not installed successfully, you will need to manually install. The driver is located in the directory where you originally installed MPIDE. On my Window® Machine, I installed MPIDE to my C drive as follows:

  5. C:\mpide-0023-windows-20130426-test\mpide-0023-windows-20130401-test\drivers

  6. Once the device drivers are successfully installed, you are now ready to program the board.The PIC32MX250F128B chip is preprogrammed with the USB bootloader. The bootloader will only define which pin is used as the PROGRAM input (Pin 11 in this case) and which pins will flash to indicate that the device is indeed in bootloader mode. In this case, the LED indicator is defined as pin 7 on the PIC32MX250F128B Microcontroller. If you were to connect an LED to this pin as you did above for pin 16, the LED would flash rapidly when in “Bootloader” mode. In order to define which pin on the PIC32 will do what, we need to select a configuration in the MPIDE. We will be using an existing board definition file for the new Fubarino Mini platform.

  7. In the MPIDE, select Tools>Board>Fubarino Mini.The PIC32 will now be set up as follows: pinout

  8. You will need to make sure that the application is in Bootloader mode. To do this, hold down the PROGRAM pushbutton connected to pin 11 while pressing on/off the pushbutton RESET connected to MCLR (pin 1).

  9. Select Tools > Serial Port > COMx (whatever serial comm has been assigned to the application)

  10. Click the upload button in MPIDE.

  11. The application USB will disconnect and then the LED connected to Digital Pin 24 should start flashing.

To view the pinout configuration and to locate some relevant tutorials, please visit the Fubarino Mini homepage at www.fubarino.org/mini.

VN:F [1.9.22_1171]
Rating: 8.4/10 (22 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Arduino-style Maze Solving Robot using Sparkfun Ardumoto

OVERVIEW:

Here is a robot application that implements a very simple maze solving algorithm. This application uses off the shelf components along with a very basic chassis built from common materials. This could be a good weekend project. The robot chassis for this Demo was constructed with 2½” wide by ¼” thick poplar project wood purchased at a local home improvement center. Note that a box was also created to house the battery holder. mazebot

HARDWARE USED

CONSTRUCTION

The Ardumoto Shield is mounted to a chipKIT Uno32 Development Platform with all component connections made to the shield as indicated in labels next to component. mazebot_construction

LOGIC OVERVIEW

The maze solving theory used here is based on the following: Say you enter a maze or room, close your eyes, place your right hand on the wall, and start walking while keeping your hand on the wall. You will eventually find your way out of the room or maze. Not the fastest route, but it works! This assumes that all the walls are connected of course. Here is the basic software algorithm in flowchart form. A graphical representation of the robot and the sensors is on the right of the chart for reference.   Robot starts by checking its sensors. If it detects a wall on its side sensor, it checks to see if the wall is in its “Sweet Spot”. If so, the robot will adjust its wheel speeds to move in a straight line (supposedly parallel to the wall). If either the front or side sensor detects a wall that is too close, then the robot turns off its left wheel so that it veers to the left (hopefully avoiding a collision). Otherwise, the robot will move in a wide circle to the right with the hopes that an object will come into view of at least one of the sensors.   Note: You can also use the left side to do this.   mazebot_overview  

 SKETCH

 
/*
 9/10/2012
 Marc McComb

This code runs a maze solving routine based on the following:
Say you enter a maze or room, close your eyes, place your right hand on the wall, and start walking while keeping your hand on the wall. 
You will eventually find your way out of the room or maze. Not the fastest route, but it works! This assumes that all the walls are connected of course

So the robot starts by checking its sensors. If it detects a wall on its side sensor, it checks to see if the wall is in its “Sweet Spot”. If so, the robot
will adjust its wheel speeds to move in a straight line (supposedly parallel to the wall). If either the front or side sensor detects a wall that is too close,
then the robot turns off its left wheel so that it veers to the left (hopefully avoiding a collision). Otherwise, the robot will move in a wide circle to the
right with the hopes that an object will come into view of at least one of the sensors. 

This application uses the following hardware:
chipKITâ„¢ Uno32 available at http://www.digilentinc.com/chipkit 
Sparkfun Ardumoto - Motor Driver shield: https://www.sparkfun.com/products/9815
Some Sharp GP2Y0A21YK0F IR Sensors - Available at Adafruit with wires already attached: https://www.adafruit.com/products/164

Software used:
The Ardumoto board is designed for a PWM on pin 11. Since the Uno32 doesn't have a hardware PWM on that pin, no worries, we just
use Brian Schmaltzs SoftPWMServo library:
http://www.chipkit.org/wiki/index.php?title=Library_Status#SoftPWMServo_library 

You will need to make sure that you add the library. To do this:
1) Make sure that you have a folder in your Documents:/MPIDE folder called Libraries
2) Copy the SoftPWMServo library folder from C:\mpide-0023-windows-20120903\hardware\pic32\libraries to the Libraries folder above
3) If MPIDE is open, close and reopen. 
4) Now all you have to do is go to the MPIDE toolbar and select Sketch>Import Library>SoftPWMServo

More info on libraries at:
http://arduino.cc/en/Reference/Libraries

*/

//Need to use this library instead of just analogWrite() since there pin 11 isn't a PWM pin on the chipKIT UNO32 board.
//No big deal. This library works great on almost any pin. 
#include <SoftPWMServo.h>

//MOTOR SETUP
const int pwm_a = 3;   //PWM control for motor outputs 1 and 2 is on digital pin 3
const int pwm_b = 11;  //PWM control for motor outputs 3 and 4 is on digital pin 11
const int dir_a = 12;  //direction control for motor outputs 1 and 2 is on digital pin 12
const int dir_b = 13;  //direction control for motor outputs 3 and 4 is on digital pin 13
const char motor_speed = 200; //set the motor speed (between 0 and 255)

//IR SENSOR SETUP
const int rSensor_pin = 0; //right sensor will be read on ANO
const int fSensor_pin = 5; //front sensor will be read on AN5

//Let's set up some variable that we'll use in the code
int rSensor_val = 0;  //this will be the right sensor value ADC reading (between 0 and 1023)
int fSensor_val = 0;  //this will be the front sensor value ADC reading (between 0 and 1023)
boolean sweetspot = false;  //boolean value initialized to false. When its true, it means the wall on the right of the robot is the "sweet spot"
boolean rSensorHit = false; //boolean value initialized to false. When its true, it means the wall on the robot's right is too close
boolean fSensorHit = false; //boolean value initialized to false. When its true, it means the wall in front of the robot is too close 
int sensor_state = 0;

void setup()
{
  pinMode(dir_a, OUTPUT); //Set the dir_a pin as an output
  pinMode(dir_b, OUTPUT); //Set dir_b pin as an output
  digitalWrite(dir_a,  HIGH);  //Reverse motor direction, 1 high, 2 low
  digitalWrite(dir_b, HIGH);  //Reverse motor direction, 3 low, 4 high  

}

void loop()
{ 

  //This is how I usually do things but you may wish to change it up a bit

  //First get all you inputs
  read_sensors();
  //Then make some decisions based on these inputs
  parse_inputs();
  //Then do all your outputs at the same time. In this case, determine motor speeds
  run_motors();
  //I always have a loop timing function
  loop_timing();
}

//this function reads the IR value on the analog input pins
void read_sensors()
{

  rSensor_val = analogRead(rSensor_pin);
  fSensor_val = analogRead(fSensor_pin);
}

//this function then makes decisions based on those inputs
void parse_inputs()
{

  if (fSensor_val > 850) fSensorHit = true; //if the front sensor sees a wall set the fSensorHit variable TRUE

  //Otherwise, check if the robot is in the "sweet spot"
  else if ((rSensor_val > 750)&&(rSensor_val <850)&&(fSensor_val < 850)) sweetspot = true;      //If not, then is the wall on the right side of the robot too close?   //If so, set the rSensorHit variable TRUE   else if (rSensor_val > 850) rSensorHit = true;

  //Otherwise make sure all of the sensor flags are set to FALSE
  else{
    fSensorHit = false;
    rSensorHit = false;
    sweetspot = false;
  }

  //reinitialize your sensor variable to a known state
  rSensor_val = 0;
  fSensor_val = 0;

}

//This routine runs the two motors based on the flags in the previous funciton
void run_motors()
{

  //If the wall on the right is too close, turn left away from the wall
  if (rSensorHit)left(); 

  //Otherwise, if the wall is in the "sweet spot", then try and stay parallel with the wall
  //keeping both wheel speeds the same
  else if (sweetspot)forward();

  //If the front sensor sees a wall, turn left 
  else if (fSensorHit)left();

  //If neither sensor sees a wall, then move in a really big arc to the right. 
  //Hopefully, the bot wil be able to pick up a wall
  else right();

  //Always set your flags to a know value. In this case, FALSE
    fSensorHit = false;
    rSensorHit = false;
    sweetspot = false; 

}

void loop_timing()
{
  delay(50);

}

//Motor routines called by the run_motors()

void forward() //full speed forward
{ 

  //both wheels spin at the same speed 
  SoftPWMServoPWMWrite(pwm_a, motor_speed); 
  SoftPWMServoPWMWrite(pwm_b, motor_speed);
}

void stopped() //stop
{ 

  //turn off both motors
  SoftPWMServoPWMWrite(pwm_a, 0);
  SoftPWMServoPWMWrite(pwm_b, 0);
}

void left()                   //stop motor A
{

  //turn of the left motor so that the robot vears to the left
  SoftPWMServoPWMWrite(pwm_a, motor_speed);
  SoftPWMServoPWMWrite(pwm_b, 0);

}

void right()                   //stop motor B
{ 

  //Here we're running the right motor at a slower speed than the left motor
  //Therefore, the bot will travel in a large circle to the right
  SoftPWMServoPWMWrite(pwm_a, 50);
  SoftPWMServoPWMWrite(pwm_b, motor_speed+50);  
}
 
VN:F [1.9.22_1171]
Rating: 8.8/10 (8 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Line Following Robot with Arduino Shield

OVERVIEW:

Here is a fairly basic robot application that implements a line following algorithm. This application uses off the shelf components along with a very basic chassis built from common materials. This could be a good weekend project. The Line-Follower chassis for this Demo was constructed with 2½” wide by ¼” thick poplar project wood purchased at a local home improvement center. Note that a box was also created to house the battery holder.

HARDWARE USED

CONSTRUCTION

The Arduino Motor Shield is mounted to a chipKIT Uno32 Development Platform with all component connections made to the shield as indicated in labels next to component.  

LOGIC OVERVIEW

The line following robot is programmed to basically avoid the color black. If both sensors see black, then the robot will back up until it no longer sees black. If one sensor sees black, then the robot will turn in the direction of that sensor until it no longer sees black. Other than that, if the robot doesn’t see black on either sensor, it will simply move for- ward. In this application, the black line is created using common electrical tape. The logic for this algorithm is shown below along with a graphical representation of the front of the line following bot for reference.  

 SKETCH

 
/*
 9/10/2012
 Marc McComb

The line following robot is programmed to basically avoid the color black. If both sensors see black, 
then the robot will back up until it no longer sees black. If one sensor sees black, then the robot will
turn in the direction of that sensor until it no longer see black. Other than that, if the robot doesn’t 
see black on either sensor, it will simply move forward. In this application, the black line is created 
using common electrical tape. 

This application uses the following hardware:
chipKITâ„¢ Uno32 available at http://www.digilentinc.com/chipkit 
Arduino Motor Shield available at: http://arduino.cc/en/Main/ArduinoMotorShieldR3 
Sparkfun QRE1113 Line Sensor Board- Analog(Item #: ROB-09453) https://www.sparkfun.com/products/9453 

Software used:
The Aruino Motor shield is designed for a PWM on pin 11. Since the Uno32 doesn't have a hardware PWM 
on that pin, no worries, we just use Brian Schmaltzs SoftPWMServo library:
http://www.chipkit.org/wiki/index.php?title=Library_Status#SoftPWMServo_library 

You will need to make sure that you add the library. To do this:
1) Make sure that you have a folder in your Documents:/MPIDE folder called Libraries
2) Copy the SoftPWMServo library folder from C:\mpide-0023-windows-20120903\hardware\pic32\libraries 
    to the Libraries folder above
3) If MPIDE is open, close and reopen. 
4) Now all you have to do is go to the MPIDE toolbar and select Sketch>Import Library>SoftPWMServo

More info on libraries at:
http://arduino.cc/en/Reference/Libraries

*/

#include <SoftPWMServo.h>

//Setting up the Hardware pins
// First the line following (IR) sensors
const int irLeft = 2; //Left line sensor is on pin A2
const int irRight = 3; //Right line sensor is on pin A3

//Setting up the Arduino Motor Shield
const int leftDIR = 12; 
const int rightDIR = 13;
const int leftPWM = 3;
const int rightPWM = 11;
const int leftBrake = 9;
const int rightBrake = 8;
const char bothSpeed = 100; //sets how fast the motors will spin (0 to 255)

//Here we set up variable that will hold the ADC value representing the line sensor values
int leftSees = 0; //A2 ADC value (0 to 1023)
int rightSees = 0; //A3 ADC value (0 to 1023)

void setup() 
{ 

  //Make sure to set all of our control signal pins as output
  pinMode(leftDIR, OUTPUT); 
  pinMode(rightDIR, OUTPUT); 
  pinMode(leftBrake, OUTPUT); 
  pinMode(rightBrake, OUTPUT); 

  //Next we make sure our brake signals are set LOW
  digitalWrite(leftBrake, LOW);
  digitalWrite(rightBrake, LOW);
} 

void loop() 
{ 
    //Start by reading the left sensor on A2
  int leftEye = analogRead(irLeft);

  //delay a little bit
  delay(5);

  //next read the right sensor connected A3
  int rightEye = analogRead(irRight);

  //Next, we run the motors based on the sensor reading

  //If both sensors see black (ADC value greater than 1000), then back up
  if ((leftEye >= 1000)&&(rightEye >= 1000)) reverse();

  //Otherwise, if only the left sensor sees black, then turn off the left motor
  //so the robot veer to the left
  else if ((leftEye >= 1000)&&(rightEye < 1000)) turnLeft();

  //Otherwise, if only the right sensor sees black, then turn off the right motor
  //so the robot veer to the right
  else if ((leftEye < 1000)&&(rightEye >= 1000)) turnRight();

  //Otherwise, move forward
  else forward();

}

//Turn right by turning off the right motor 
//i.e disable the PWM to that wheel
void turnRight(void)
{
  digitalWrite(leftDIR, HIGH); 
  digitalWrite(rightDIR, HIGH);
  SoftPWMServoPWMWrite(leftPWM, bothSpeed);
  SoftPWMServoPWMWrite(rightPWM, 0);
}

//Turn left by turning off the left motor
//i.e disable the PWM to that wheel
void turnLeft(void)
{
  digitalWrite(leftDIR, HIGH); 
  digitalWrite(rightDIR, HIGH);
  SoftPWMServoPWMWrite(leftPWM, 0);
  SoftPWMServoPWMWrite(rightPWM, bothSpeed);
}

//Move forward by enabling both wheels
void forward(void)
{
  digitalWrite(leftDIR, HIGH); 
  digitalWrite(rightDIR, HIGH);
  SoftPWMServoPWMWrite(leftPWM, bothSpeed);
  SoftPWMServoPWMWrite(rightPWM, bothSpeed);
}

//Reverse by enabling both wheels 
void reverse(void)
{
  digitalWrite(leftDIR, LOW); 
  digitalWrite(rightDIR, LOW);
  SoftPWMServoPWMWrite(leftPWM, bothSpeed);
  SoftPWMServoPWMWrite(rightPWM, bothSpeed);
}
 
VN:F [1.9.22_1171]
Rating: 6.9/10 (27 votes cast)
VN:F [1.9.22_1171]
Rating: +2 (from 2 votes)

Debouncing a Pushbutton

Overview:

A pushbutton is a Mechanical Switch. Switches play an important and extensive role in practically every computer, microprocessor and microcontroller application. Mechanical switches are inexpensive, simple and reliable. However, switches can be very noisy electrically. When a switch, such as a pushbutton is pressed, the connection actually makes and breaks several, perhaps even hundreds, of times before the final switch state settles. The problem is known as switch bounce.

The consequences of uncorrected switch bounce can range from being just annoying to catastrophic.

A software technique called “Debouncing” is one way to solve this problem. Here’s how it works:

Usually, the switch is connected to a pin on the Microcontroller so that it maintains either a HIGH or LOW condition when the switch is open (not pressed). If the switch closes (is pressed) then that condition will change. The Microcontroller detects that change. Instead of reacting right away, the Microcontroller will wait a period of time, say 5 mS, to give the switch a chance to stop bouncing and then checks that pin again. If the pin still reads that the switch is closed, then the Microcontroller will do something about it.

In this tutorial, a pushbutton press (BTN1) will trigger LD1 to light. Otherwise, LD1 will be OFF.

 

Reference:

This tutorial introduces the if/else statement. This type of statement gives your sketch the ability to make decisions based on conditions occurring outside of the Microcontroller or as a result of some sort of internal condition such as the result of some mathematical operation.

We recommend you read the following before proceeding:

 

Hardware Used:

The hardware used in this tutorial will be the chipKIT uC32 along with a chipKIT Basic I/O Shield both manufactured by Digilent Inc. The reference guide for each board, schematics and other resources are available on their individual homepages:

 

Procedure:

  1. Create a new sketch in MPIDE.
  2. Save the sketch with a meaningful name.
  3. Add the following code to your new sketch:
    int ledPin = 26;   // LED connected to digital pin 26
    int pbPin = 4;   //pushbutton BTN1 connected to digital pin 4
    int pbState = LOW; //this variable will hold the value or state of BTN1
                       // i.e. if not pressed, pbState = LOW, if pressed, pbState = HIGH
    
    void setup()
    {
      pinMode(ledPin, OUTPUT);   // sets the digital pin 26 as output
      pinMode(pbPin, INPUT); //sets digital pin 4 as input
      digitalWrite(ledPin, LOW); //make sure LD1 is OFF
    }
    
    void loop()
    {
    
      pbState = digitalRead(pbPin); //read the value, HIGH or LOW, on the pushbutton pin
    
      if (pbState == HIGH) //is pbState HIGH indicating BTN1 is pressed??
      //if yes, do the code inside the curly braces. This is the debounce section
      {
        delay(5); //wait 5 mS for any pushbutton bounce to disappear
        pbState = digitalRead(pbPin); //read the value on the pushbutton pin again
    
        if(pbState == HIGH) //is it still HIGH (pressed)
        {
          digitalWrite(ledPin, HIGH); //Light LD1>
        }
      }
    
      //otherwise
      else
      {
          digitalWrite(ledPin, LOW); //keep LD1 OFF
      }
    
    }
     
  4. In the MPIDE, verify that the chipKIT uC32 and the associated communication port are selected.
  5. Upload the code to the chipKIT Board.
   

Verifying Operation

After the sketch is sent to the chipKIT uC32 board’s Microcontroller, LED 1 (LD1) on the chipKIT Basic I/O Shield should light when pushbutton BTN1 is pressed.

   
VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)