Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

Tuesday, August 30, 2011

Controlling a Brushless Motor with NETMF

2011-08-30 22.10.59
Continuing with the NETMF for Electronics Noobs Tutorials.  Today, I’ll demonstrate wiring up a brushless motor to your NETMF device.
 
If you’re building any type of R/C planes, copters, cars, boats or robots with your NETMF device then you’ll likely encounter the need to control a brushless motor.  Controlling a brushless motor is very different than controlling a regular brushed DC motor.  What makes it different is the addition of the Electronic Speed Controller (ESC).

The main reason this article exists is because the hobby parts distributors have done a terrible job of documenting these most basic of parts.  You should be able to go to the manufacturer website for the ESC you purchase and get most of this info.  However, my experience is that you can’t and they assume you know what you’re doing if you buy these parts.  Obviously, not the case or you wouldn’t be here.

If you click on the main photo, and look closely at the ESC (the blue part in the lower left corner) you will see that on one side it has three black wires.  These colors may vary from model to model.  On the other side it will have two thick red & black wires.  It will also have a bundle of two or three thinner wires depending on your model.

2011-08-30 22.12.09First connect the three black wires from the ESC to the three wires coming from your motor.  Right now you’re thinking “which wires on the motor go to which wires on the ESC?”.  Trust me, it doesn’t matter.  To understand why, study how brushless motors work and you’ll understand.  For now, just take a leap of faith.  If you find later that your motor is turning in the wrong direction, then swap any two of these wires and the direction will change.  It’s magic…
2011-08-30 22.24.17
The small bundle of three wires on my ESC are colored brown, red, and orange.  After quite a bit of digging, I finally found that the two outer wires are the important ones.  The brown wire is ground and the orange wire is the control.  The red wire in the center provides 5V power and can be used to power the microcontroller.  Most people do not recommend this due to the fact that when the motor is accelerated quickly it is possible that power could be momentarily lost.  This is an especially bad situation if you’re controlling a flying vehicle.  It’s not so bad if you’re controlling a car or plane.  If your bundle only has two wires, then you do not have the power wire.

You should wire the brown wire of the ESC bundle to any ground on your NETMF device.  For this example, I’m using a GHI Panda-II.  The orange wire should be connected to any PWM pin.  I’m using PWM1 (I/O 10).

2011-08-30 22.12.31Next, all you need to do is connect the red & black wires from the ESC to the respective wires on your battery.  If all is well, you will probably hear a series of tones from your ESC indicating that it is now armed.

NEVER TEST YOUR MOTOR WITH A PROPELLOR ATTACHED!!!

Until you have fully tested out your controls and have everything mounted securely and have a safe place to work, it is a really bad idea to attach the propellers.  If you have never worked with a brushless motor with a propeller on it, you will probably be amazed at how much power they have the first time your power it up.  Propellers are very sharp and will cut you.

Now that everything is wired up, it’s a simple thing to get the software going.  Start by downloading Chris’ Brushless Motor ESC driver class and add it to a new NETMF project.  Assuming you also used pin 10 to control your ESC, the following code should test your motor by powering it up to 20% power for about half a second and then powering it off.  Push the reset button to make it go again.

public static void Main()
{
    var m1 = new BrushlessMotor((PWM.Pin) FEZ_Pin.PWM.Di10);
    m1.Scale = 100;
    m1.SetPower(20);
    Thread.Sleep(500);
    m1.Stop();
}
If that works then you’re off and running.  Just figure out what power your project needs and when then apply where necessary.  If you need additional motors, then rinse & repeat but use a different PWM pin.

If you’re using a netduino or other NETMF device, do not be dissuaded.  It’s very easy to port Chris’ driver class to your device and to make the appropriate change to the test app.  Feel free to drop me a line if you need help.

Choulant asked for it and here they are - the parts used in this tutorial:



Have fun!

Saturday, August 13, 2011

Using an External Button & LED with NETMF

In continuing with the BlinkyLEDNETMF for Electronics Noobs series of tutorials, today I’m going to demonstrate how to connect a button/switch to a Panda-II NETMF microprocessor and how to respond when the button is pushed.  Since I need to do something when the button is pushed, I thought this would be an opportune time to also show how to connect an LED to the board and light it up also.

Nearly every NETMF basic tutorial out there starts with a very simple program that uses the on-board button to light up the on-board LED.  That’s just great and is absolutely fantastic the first time you write a NETMF program.  However, as soon as you start working on a real project you soon discover that the on-board button & LED have very limited uses since they can’t be exposed outside of your project enclosure. Then the question comes up – how do I add more buttons?  How do I light up an LED on my project box?  How do I use more than one button or LED?

I’m going to demonstrate how to do this in the most basic situation – the one that will work for 95% of all hobbyist’s needs.

Panda-II Connections

For this project, you’ll need a momentary button, an LED, a breadboard, one 10K ohm resistor, one 100 ohm resistor, and some wires.

Like most things, there are many ways you could wire this up.  This is just one.  What I did was to first plug my button into the breadboard and wire one side of the button to the ground line (very top row on the breadboard).  Then, I connected a 10K ohm resistor (brown, black, orange) to the power (5V) line (2nd row on the breadboard) and used it to connect power to the other side of the button.  The 10K resistor prevents us from creating a “short” which could fry the electronics by allowing too much current to be pulled through the electronics.  Next, we put a 100 ohm resistor (brown, black, brown) on the power side of the button then connect the other side of the resistor to the analog 0 pin on the Panda-II.  This resistor prevents too much current from getting into the board and damaging it.

Panda-II Connections.Fritzing

Now that we have the button wired up, we’ll wire up the LED.  Since only a very small amount of current flows through pins of the Panda-II board we can connect the anode/positive side (longer wire) of the LED to the D5/PWM5 pin and wire the cathode/negative (shorter) side of the LED to our ground line.  That’s it for the wiring.

I do want to note here that if we were wiring the LED to an external power source that we would need to add a current limiting resistor to one side.  To determine the correct size resistor, you can use an LED calculator.

Now that we have the hardware all wired up, it’s time to write some software that responds to our button being pressed by lighting the LED.

In Visual Studio, we create a new console project and add the following references:

FEZPanda_II_GHIElectronics.NETMF.FEZ
Microsoft.SPOT.Hardware
Microsoft.SPOT.Native
mscorlib

In our Program.cs file that is automatically created, replace what is there by default with the following.

using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using GHIElectronics.NETMF.FEZ;
 
namespace ExternalButtonAndLedTutorial
{
    public class Program
    {
        // Tell the CPU we're going to use digital pin #5 to send a signal to the LED.
        static readonly OutputPort _led = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.Di5, false);
 
        public static void Main()
        {
            // Tell the CPU we're going to receive an analog signal from analog pin #0.
            var blueButton = new InterruptPort((Cpu.Pin)FEZ_Pin.Interrupt.An0, true, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeLow);
            
            // The second parameter in the line above ("true") tells the CPU that we want to use the "glitch" filter.
            // If you disable this line then run the program, you will notice in the debug windows that if you are not very fast
            // at pushing the button that the event will actually get fired multiple times.  We only want the event to fire once.  GHI gives
            // us this property that we can set to put a boundary around our first event and prevent redundant events from being fired.
            // Adjust the number of tick
            Cpu.GlitchFilterTime = new TimeSpan(TimeSpan.TicksPerSecond/2);     // 1 Tick = 100 nanoseconds
 
            // When the button is pushed it will signal an interrupt in the CPU which will in turn cause an OnInterrupt event to be thrown.
            // Our BlueButton_OnInterrup function will be called when the interrupt/event is fired.
            blueButton.OnInterrupt += BlueButton_OnInterrupt;
 
            while(true) Thread.Sleep(10);
        }
 
        private static void BlueButton_OnInterrupt(uint port, uint state, DateTime time)
        {
            _led.Write(true);       // Turn on the LED
            Thread.Sleep(1000);     //  wait 1 second...
            _led.Write(false);      // Turn off the LED
 
            Debug.Print("Blue Button Pushed! " + DateTime.Now.ToString());
        }
    }
}



I’ve chosen to document the code as comments in-line, but if anything isn’t clear please leave a comment and I’ll clear it up.


Make sure and set your project properties to deploy to the USBizi device then run it.  If you’ve done everything correct then when you push the button the LED should come on for half a second then turn back off. 


Now that you have one button and one LED working,  get creative!  You can reproduce this many times and as many different ways as your imagination will allow.  To use more buttons or more LEDs, just use any of the other pins and be sure to specify in your code when you define your buttons or LEDs which pin they are connected to and you’ll be fine.  Put these new skilz to work and be sure to post your results in the comments!

NETMF for Electronics Noobs Tutorials

NETMF Logo
I’m starting a series of tutorials for people just getting started with .NET Micro Framework (NETMF).  My target audience will be people with an intermediate level of experience with C# but very little if any experience with the electronics side of things.  There is plenty of good info out there regarding using C# and there are several good tutorials on getting started with NETMF but in my opinion most of these assume the user is already somewhat experienced with electronics.  This is where I hope to bridge the gap.  I will not go in-depth on either the C# (NETMF) or the electronics side.  I will show you just enough to help you get started having fun with NETMF and then point you to other sources where you can learn more.
Although in most of my tutorials, I will use the GHI Panda-II microprocessor board the techniques can directly be applied to netduino or most any other NETMF device with minor code changes.
I’ll update the following list of topics as I add posts (I’ll try to add one weekly).  So, bookmark this page and follow my blog if you want to keep up.  If you have any specific topics you would like to see covered, please feel free to email me at ian (at) houseoflees.net or post to the comments below.
TUTORIALS:
QUICK TIPS:
FURTHER DISCUSSION
  • TinyCLR.com – great place to ask questions regarding anything about the GHI Panda-II microprocessor and NETMF.
  • netduino.com – great place to ask questions about the netduino microprocessor and NETMF.
  • netmf.com – the official NETMF community forum
NETMF

Monday, August 8, 2011

Basic XBee on NETMF

As I wait for parts for the Omnicopter, one of the things I’m getting started is the XBee radio communications between the remote/computer and the copter.  My initial design will attempt to use XBee radios for all control of the copter as well as in sharing diagnostic & control data between the base station [remote & or PC] and the copter.  I fear that XBee may end up not being responsive enough and have enough throughput to accomplish all things but that’s where I’m going to start before attempting traditional R/C radio techniques.

Xbee Series 1I want to be able to control the Omnicopter both by a remote control I’m building based on a NETMF microcontroller and with software on a PC.  The most basic of things is to make sure that the NETMF microcontroller I’ve chosen for the copter, a GHI FEZ Panda-II, can communicate with my PC. 
For the Panda-II I have bought and assembled an Adafruit Protoshield and an Adafruit XBee Adapter.  I already have some XBee Modules (series 1) from a previous project.  So, I’m using them for now.  Once I’ve proven the copter can fly and I’m brave enough to push the range limits of the XBee series 1 (300 ft.) then I can simply buy new XBee Pro radios and drop them in place of the existing radios to get a range of 6-15 miles (line of sight).
To test communications, two things are required – an XBee connected to the PC and a NETMF microprocessor with an XBee and the necessary software on both sides.

Setting Up An XBee on NETMF

An XBee radio communicates using basic RS232 type of communications.  All that’s required to connect it to the Panda-II is to give it 5V power, ground, and transmit & receive signals.
XBee Test on Panda-II w Caption

For a better view of the wiring connections, I drew it up in Fritzing.
XBee Test on Panda-II.Fritzing

Note that the receiver (RX) on the XBee is connected to the transmitter (TX) on the Panda-II and vice-versa.  This may not be obvious to those first getting started.

Next, we’ll need a NETMF C# program to install on the Panda-II.  Visual Studio 2010 (VS2010) Express or better can be used to compile and deploy the program.  GHI has a great tutorial on getting started if this is your first time to create a NETMF program.  So, I’ll jump straight to the code.  I’m using the MFToolkit open source code by Michael Schwartz to simplify the code required considerably.  An alternative assembly that is somewhat easier to understand and seems to satisfy basic XBee needs is Grommet.  Since I expect this project to get much more sophisticated over time, I’ve decided to stick with the MFToolkit. 

Once you download the MFToolkit (or Grommet) code from Codeplex and create a new NETMF C# project, you can simply copy this code into your project to have the NETMF device send a “ping” every 5 seconds.  The ping is basically the word “Hello” plus the current time in Ticks.  The following code is not meant to be “production ready”.  It’s just enough to test that the XBee is working.
public static void Main()
{
    var ledBlinkerThread = new Thread(BlinkOnboardLed);
    ledBlinkerThread.Start();

    var pingThread = new Thread(SendPingWithMFToolkit);
    pingThread.Start();
}

private static void SendPingWithMFToolkit()
{
    var xbee = new SerialPort("COM1", 115200, Parity.None, 8, StopBits.One);
    xbee.Open();
    xbee.DataReceived += XBeeDataReceived;

    while (true)
    {
        string output = "Hello " + DateTime.Now.Ticks;
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(output);
        xbee.Write(bytes, 0, bytes.Length);
        xbee.Flush();
        Thread.Sleep(5000);
    }
}

static void XBeeDataReceived(object sender, SerialDataReceivedEventArgs e)
{
    int bytesReceived = ((SerialPort)sender).BytesToRead;
    var bytes = new byte[bytesReceived];
    ((SerialPort)sender).Read(bytes, 0, bytes.Length);
    var received = new string(System.Text.Encoding.UTF8.GetChars(bytes));
    Debug.Print(received);
}
Note that the second parameter of the SerialPort constructor in SendPingWithMFToolkit() specifies the baud rate of the XBee radio.  By default, the radios will be set to 9600.  I have changed mine to 115200 prior to this writing.  If this is your first attempt with XBee then you should change this parameter to 9600 or whatever your actual baud rate is if yours have been changed to something different.  The important thing to know is that both radios must be set to the same baud rate and the software on both sides is configured likewise.

At this point you should be able to compile and run your code from the Panda-II without issue and it will start sending it’s “ping”.  Also, although I am using the Panda-II for this post just about any Arduino shield compatible NETMF device such as the netduino should also work w/o any change to the code or wiring.


Setting Up An XBee on a PC

Setting up an XBee on a PC is a bit simpler since all we really have to do is connect the XBee to a breakout or dev board with a USB cable and install the X-CTU software by Digi.  No reason to write our own code for this test since there already exists this great utility that does everything we need to test & configure an XBee.  I am using Windows 7 Ultimate (x64) but the steps are basically the same for any OS.

XBIB-U-DEV w caption

I have a MaxStream (now Digi) XBIB-U-Dev (Rev 3) XBee development board from a previous project that I’m using, but you can use just about any XBee adapter including the one from Adafruit that we used on the NETMF.  On my board, I’m able to plug a USB cable directly into it.  On most of the basic adapters, you will need an FTDI cable to convert the serial communications to USB.  You will also need to locate and install the appropriate drivers for your OS.

imageOnce you have your hardware all figured out, we need to download and install the X-CTU software.
After you install X-CTU, run it and it should come up with something similar to this except the Baud setting will probably be at 9600.  Set the baud rate to match that of your modem and hit the “Test/Query” button to see if X-CTU can connect to your XBee radio.  Assuming you can connect and all is good then we’ll now see if we are receiving the “ping” from our NETMF device.  Click on the “Terminal” tab and wait 5 seconds.  You should see some text appear in red on the screen and more to be added every 5 seconds.

If we have this then we know we are properly sending from the NETMF device and receiving by the PC.  Next thing to test is that we can send from the PC and receive from the NETMF device.

First make sure that we are running our program on the NETMF device through the VS2010 debugger and not just on the board itself.  You’ll notice on our NETMF code that we are capturing XBee received data with the XBeeDataReceived() handler function.  Anytime data is received, it will be simply printed to the Output Window.

imageTo send a packet of data from the PC we hit the “Assemble Packet” button in the X-CTU Terminal screen.  We’ll send a simple “Hello World” packet.  Type that in the textbox and hit “Send Data”.  You should see “Hello World” printed in blue text in the X-CTU console and in the VS2010 output window you should see the same text also printed there.

Mission accomplished.  We have established the most basic of communications and know that all of our hardware is setup properly and is working.  Now the challenge is for you to figure out how to best utilize this power in your project by designing the data you will send and how to handle it properly when it is received.

If you are still having issues with hardware or software, you should start by checking the forums at any of the following sites.
Good luck and happy transmitting!