Posts Tagged ‘pic’

Introducing the QuadHybrid – a stable, maneuverable and cheap flying robotic platform

Introduction & Demo of the QuadHybrid Design

I’ve been experimenting for quite a while with different configurations of Multi-Copters and RC Helicopters, basically looking for a stable robotic platform that can be used for my machine vision or other sensor-enabled flying robotic projects. RC helicopters have been around for quite a while, however (with the exception of some 3-Channel helicopters) they are not easy to fly, not very stable and not too precise in maneuverability – in other words not exactly good match for a flying robot. Then came the quadcopters and everyone loved them, talked about them , and eventually wanted to or actually built one.  I built a few – and what I learned is that  they have a great lifting power, great maneuverability (basically equivalent to a 4ch or 6ch heli), however   they rely entirely and heavily on relatively expensive IMU sensors  to achieve this stability.  I a QuadCopter you basically have four “monster” motors on each beam than must be synchronized precisely. Because you’re controlling so much power with your IMU sensors – any small deviation or lack of callibration and your platform is no longer stable. That’s why the sensors are crucial in a quadcopter  – without them the quadcopter will not fly at all ! 

After many trial designs – my conclusion was that a suitable flying robotic platform must not rely too much (or at all) on its sensors to be stable while hovering. It must be mechanically symmetric, preferably with it’s center of mass in the center.  At the same time it must have the maneuverability  capabilities of a quadcopter –  and namely I wanted it to fly sideways, forward & back  and rotate around its axis. Although the solution I came up with might seem to some (including myself) a little strange  and out of the ordinary –  as turned out it flew surprisingly well , was very stable and maneuverable, and best of all – had a very low price tag due to the fact that it was easy to built from the off-the-shelf toy helicopter replacement parts.

Without further adieu – below is the picture of the machine that I called “QuadHybrid”:


My very first QuadHybrid prototype.

Below you can see some flying test video:


So What Exactly is a QuadHybrid ?

Let’s have a closer look at QuadHybrid’s pictures. A simple way to look at it is:  a co-axial helicopter on top of a quadcopter – it’s actually as simple as that.

In total QuadHybrid has 6 motors and 6 propellers (2 large one center from the helicopter + 4 small on each arm from the quadcopter).

The two large center propellers in the center consist of 2 heli-type blades – they provide all the lifting power needed. They spin in opposite directions to compensate for the yaw rotation introduced by any rotating propeller and are stabilized by an optional vertically mounted MEMS gyroscope  (the only sensor used in this design). The slight difference in speed of the top and bottom blades is used to control the desired yaw rotation.  Thus the center motors provide the throttle and yaw control of the QuadHybrid – in other words ability to fly up/down or rotate about its center vertical axis.

The four small rotors on the four arms are actually small tail motors from a 3ch helicopter, they provide the remaining maneuverability  functions – pitch/roll or – or in other words the ability to fly  forward & backwards or shift sideways  (right / left) . 

The resemblance to a quadcopter and a helicopter can be seen in the picture below where they are put side by side.



How Does a QuadHybrid Work and How to Build One

QuadHybrid has all the maneuverability of a 4 channel helicopter or a quadcopter (throttle, yaw, pitch and roll). A 3 channel helicopter as we know it – only has 3 controls (throttle, yaw and pitch). The problem with a co-axial 4CH helicopter for instance is that it relies on a swash plate and servos to achieve the pitch/roll control. Basically it is a servo mechanism for tilting the axis of rotation of the bottom rotor – it is not easy to fine tune and it needs frequent maintenance. A 3CH toy helicopters on the other hand relies on a tail rotor to achieve the pitch control – and this is one of the ideas I used for QuadHybrid – basically I multiplied the tail boom and rotor on a 3CH helicopter by four.


This is how a typical 4CH helicopter is build. Please note that the bottom blade can be tilted by using 2 servos that tilt the swashplate. In the QuadHybrid design we are going to eliminate the servos and the swashplate and replace them with 4 small motors mounted on 4 arms (beams), just like on a quadcopter.

I built my QuadHybrid, from spare RC or “toy” heli  parts. They are widely available and thanks to the fact that manufactures copy each other in some cases bluntly, these parts are compatible in many cases  so I was able to mix-and-match. I took the electronics from a E-Sky Lama V3 helicopter  – that is a 4 channel heli so it has a swashplate and 2 servos to control the pitch and roll. Because I didn’t wanted the swashplate (the roll/pitch on QuadHybrid is controlled by the 4 small quadcopter style rotors), I used the frame and blades from another toy helicompter  – Syma S001 and I was able to fit the Esky motors into that frame which are bigger and more powerful than the S001 stock motors. 

To clarify the design let’s look at the guts of the E-Sky Lama V3 helicopter . I actually used all electronics in this 4CH helicopter, except the servos (as will become clearer in the next diagram):



The main idea of the QuadHybrid design is: to achieve a better Pitch/Roll  control I replaced the servos with a custom control board called “QuadHybrid Controller V1”. This board basically takes the servo RC signals (Pitch and Yaw) as inputs and controls the 4 arm motors using a set of 4 transistors. This allows QuadHybrid to fly just like a quadcopter in “+”  or “X”  configurations (for explanation of “+” or “X”  flying configurations  see for example




On the mechanical part – the swashplate on the bottom blade was replaced with a fixed blade mount from a 3CH helicopter. This made the bottom blade of the 4CH fixed. Normally on a 4CH heli it is being tilted by servos that are connected to the swashplate using 2 links.

Main Rotor Head

This is a swashplate assembly on a 4Ch helicopter it is the black disk under the blades mount. It is connected to the blade mount with two links. Two servos that are controlled by the RC receiver are able to tilt the swashplate and thus alter the axis of rotation of the bottom blade. This is how the roll and pitch is controlled in a 4 channel helicopter. It is far from perfect and requires frequent tune-ups.


A gyro-stabilized co-axial 3 channel toy helicopter is fairly stable, as opposed to a 4CH helicopter- it uses the tail rotor to control the pitch (flying forward or backward). Note the bottom blade is fixed , just like on the QuadHybrid.

QuadHybrid Controller Board and Software

Below is the schematic of the QuadHybrid V1 controller (the blue board on the diagram above that controls the 4 motors). This is the only custom component that is not available from RC toys parts.


At the heart of the QuadHybrid V1 controller board is a PIC16F1825 microcontroller – it’s main task is to capture the servo signals received on ports RA5(ROLL) and RA4(PITCH) and convert them  to 4 PWM signals that control the 4 rotors mounted on arms. The motors are driven using 4 NPN transistors – these can be any NPN transistors as long as they have a current rating of at least 1A (or the maximum current of your arm-mounted motors) and a low Collector-Emitter resistance (< 0.3Ohm or so).  MOSFET could be used instead of NPN transistors, with slight schematic change – however I found hard to source them in an easy to solder and light-weight TO-92 package so I used NPNs instead.

QuadHybrid V1 controller board operates by default in “+” configuration. If you want to operate it in “X” configuration then connect the X_CONF jumper – this will give you better control with smaller motors , since for example flying forward will activate two motors at once (3 & 2). The only thing to keep in mind when flying in “X” configuration is that the “Front” is a imaginary line between arm #0 and #1 .

QuadHybrid V1 PCB was created as a all through-hole design so that anyone can assemble it and covert a toy RC helicopter into a QuadHybrid:

For anyone wishing to spend time on creating their own QuadHybrid V1 controller board – source code and Eagle files are available on the SVN repository, otherwise easy to solder kits will be available in my Store.

If you would like just to peak over the source code here is a direct link:

As you can see it is a fairly simple project a(for anyone familiar with C  and microcontrollers) and a good placeholder for further improvements and add-ons.


Mechanical Construction

On top of QuadHybrid prototype is basically a stripped down frame of a 3ch helicopter and namely it comes from Syma S001:



Under the frame are 2 aluminum tubing pieces that form the 4 arms. At the end of each arm I attached a tail rotor from the same Syma S001 helicopter model:



Then, to house all the electronics and battery I just sandwiched two perforated  boards with nylon spacers (Tip: most bolts,nuts and spacers used in this design are nylon-made to lower the weight) :


For landing gear I just used a RC helicopter training kit that consist of a round bracket attached to the bottom deck, four carbon fiber rods and four (orange) ping-pong balls:


Please note that: although all the mechanical parts are from a 3Channel helicopter (Syma S001), you will need electronics from a 4Ch helicopter! The main reason for using a 3CH helicopter for mechanical part is because the bottom blade bracket was already fixed (3Ch helicopters have no swashplate):



It might be more economical to get a 4Ch helicopter (mainly for its electronics that support pitch & roll not just pitch as a 3Ch helicopter) and then just remove the servos and the swashplate and then fix the bottom blade bracket using screws and/or glue.  As I did in the photo below (E-Sky Big Lama parts shown):



As an alternative to fixing the bottom blade bracket, you can also get a fixed blade bracket from a 3CH helicopter – it must be same inner diameter as the one from your 4CH helicopter. The diameter of the outer drive shafts are typically 4mm ( and 5mm , 6mm and even 8mm for larger helicopters).

Esky helicopters are best to use in terms of electronics because they have standard signal RC protocols in their transmitter / receiver boards that you can tap-into to get the Pitch/Roll signals needed for the QuadHybrid controller board. Syma helicopters integrated boards are harder to hack into – however some people have managed to hack into them and reverse engineer the signals.


Conclusion: What are The Advantages and Disadvantages of the QuadHybrid Design over a traditional QuadCopter or a RC Helicopter

While building the QuadHybrid  I selected the best features of a quadcopter and a helicopter and put them together, this resulted in a machine that took the best of the two worlds:

– QuadHybrid is mechanically symmetrical and stable. As opposed to a QuadCopter it does not rely on sensor to achieve this, the main hovering stability comes from the co-axial design and the centrifugal momentum of the fly-bar (the black bar on top of the blades with two weights on each side) – this is basically the same principle at work as in a mechanical gyroscope.

– QuadHybrid only requires two lifting “powerful” motors, the other 4 small motors are used for steering and are not crucial for device stability. There’s no need for motors to be brushless, and no need for brushless ESC controllers, they can be cheap RC-type brushed motors that can be driven by MOSFETs or transistors, there’s no need to reverse rotation of any motors, however it will be a feature in V2 of the controller board. Also there’s no need for CW and CCW propellers for the motors mounted on arms. All this vastly reduces the complexity and cost of the design.

– Partial or complete failure of any motor will still keep device in the air and give the operator/program a good chance to land it safely. In the worst case scenario – if a driving motor fails , the device will loose lifting power and will spin in the air, but will still at least stay on it’s vertical axis. In case of a quadcopter – failure of any motor is fatal – it will basically flip the quadcopter, or make it fly sideways with great chance to hit something. This is of course debatable, but in any case statistics tells us that the probability of one of the 4 motors to fail is twice of that of one of the two motors to fail (and economics tells us it’s also cheaper to get two motors than four).  Failure of any arm-mounted motor on a QuadHybrid is not critical, the device will still hover in the air and can be landed safely.

– Safety (we all know it should be first). A QuadCopter without  shielded high-powered rotors is a pretty dangerous device,  its propellers are spinning with an incredible force and are ready to cut into anything that falls in their way – they can do a lot of damage to humans, pets or property. QuadHybrid only has four low-powered motors on its arms since they are only used for steering, not lifting. The center driving propellers on a QuadHybrid are shielded away by its arms, also they have a folding design, so if they hit something it will somewhat make the impact less destructive.  Overall QuadHybrid is more suitable for indoor applications such as schools , universities or research facilities. Make no mistake though – QuadHybrid  can  still do damage and safety procedures must he observed at all times !

Few advantages of Quadcopters over QuadHybrid worth mentioning may be:

– because they have four powerful motors, Quadcopters  have greater lifting power. However this is more of a “brute-force” advantage – one could always get more powerful motors and battery for a QuadHybrid to achieve the desired lift power.

– Quadcopters can do some serious aerobatics (if you’re a good pilot)  including fly upside down or do 3D stunts. This is not really an advantage for some people, specifically when you are actually trying to build a nice and stable robotic platform – on the contrary it’s more something you try to avoid. 

In conclusion: although this first version of QuadHybrid was not designed to do 3D stunts or fly with high speeds –  it has a great hovering and maneuvering stability. I think it will find most of its use as a highly stable and controllable indoor flying robotic platform. However similar spin-offs could be expected to be developed for flying outdoors and/or with higher speeds.



This article is dedicated to all my math and science teachers !

USB firmware debugging with USBTrace, PicKit & MPLAB IDE

Ah, the joy of firmware debugging! I’ve been working on a USB firmware for my new upcoming product that involves a dual traditional TTL (Serial) and a USB-TO-SERIAL converter (CDC Communication Port) implemented in the same firmware. The firmware was written in C18 , using the USB stack from Microchip Applications Libraries.

Everything worked well until I suddenly discovered that while sending data over the CDC port from the computer to the device, the device would *sometimes* receive garbage data instead of what I sent. This wouldn’t be so discouraging if the data received would be the same, or at least this would happen always not *sometimes*.  The bug was caught in the act on the screenshot below, the arrows show the data I actually sent ‘stop’ followed by LF (0xA) char and the character codes (in decimal) actually received. This is garbage because 92,162,62,180 are note the ASCII chars for ‘stop’.  Please note that this will only occur *sometimes*, however I could almost consistently repeat it after several retries of sending a command to the device.


The tracking of this bug turned out to be so adventurous and involved that I decided to write a tutorial about it. It involved some tools that I didn’t use often before, but now they proved indispensable in locating this furry and fuzzy code pest . As you’ll see at the end of the article the bug was pretty obvious at least for me (I already made this mistake many times , but forgot about it), however it might be really useful for someone just starting working with microcontrollers,  C and/or  interrupts. It also provides an opportunity to review some tools I used in the process.

So where do we go from here ? Same data is send over a USB CDC Serial Emulator Port  but sometimes the microcontroller receives garbage instead of the original data. A general rule of thumb is – start at the source and go up. Let’s identify the possible problems:

#1  – the computer terminal, or USB driver has gone crazy, it is sending something else instead of what was typed
#2  – there’s a hardware noise problem on the USB lines
#3  – there’s a bug in the Microchip USB Stack
#4  – there’s a bug in my code

Ok so we start with #1 , how do we see that the terminal is actually sending the correct data ? We need a way to see the actual packets send via USB. For someone who had a hardware USB protocol analyzer it would be a good time to power it up. Unfortunately these devices are really costly (let me know in the comments if I am wrong and you know any affordable solutions), and luckily for us there are decent software USB protocol analyzers that we can use instead. The tool that I used and that I highly recommend is USBTrace. It is not free , but still affordable and a great value that will pay off if you value your debug time. The reason I like USBTrace is that is so easy to use. You know a good product because after you start it you don’t have to read a manual to perform a basic function. Once I started USBTrace on the left side I was able to find a list of all USB devices, it was easy to track down my virtual CDC Serial port because in the bottom panel I could see the device descriptors. Please note that I also had connected a FTDI serial converter that I could have confused with my device. However my device had some strings in the descriptor that I recognized from my firmware such as “CDC RS-23 Emulation Demo”. Once I checked my device I was ready to click the green Run buttons. And the packets started pouring in …


Wow , that was an overwhelming number of packets! My device was in streaming mode and sending a lot of data to the EndPoint #82. I only needed data that I send to device so how do I do that ? Again USBTrace was great and very intuitive , clicked on the funnel icon (Filter) and I got following dialog:


Here I was able to set the Direction of the packet – OUT. Please note that for USB packets , by convention , the direction is as looking from host – so OUT from computer to device. I also set the CDC OUT endpoint as specified in my firmware #2, finally I set the request type to BULK_OR_INTRRUPT_TRANSFER.

Now all I had to do is to send the ‘stop’ command couple of times until the bug happened again, that was easy to spot since the streaming would not stop once garbage was received. And once it happened, I checked the contents of the last packet in USBTrace, and what do I see:


The data is completely correct, so my first guess is ruled out. Let the bug hunt continue. Moving on to #2.

#2 – there’s a hardware noise problem on the USB lines

I had a look at the cables, I had a look at the device, I knew the hardware setup worked perfectly before. If I had a hardware USB analyzer I would hook it up. But I didn’t so I took a leap of faith and I skipped #2. This wasn’t by the books. However it was all I could do in reasonable time. So moving on to #3.

#3 – there’s a bug in the Microchip USB stack

Once you download the USB stack, and integrate into your project , it becomes part of your project. So tracking Microchip’s bug was no different than tracking my own code bug. So I moved to #4 and handled #3 in the same step.

#4 – there’s a bug in my code

Ok so here we are in the MPLAB IDE 8.83. My PIC device is capable of up to 4 Hardware breakpoints. This means that the MCU can halt on specific memory locations, it also can halt when a specific memory location is written or read.  By scanning through the USB Stack code, I found that it stores the incoming  USB CDC data in the cdc_data_rx[] buffer . From the .map file I was able to determine that this buffer address is starting at 0xE08. The MAP file is basically a file the compiler creates and where you can find all your variables and code and at what address they are stored, look for it in the same folder where you output .hex file is.

Setting a memory breakpoint is accomplished by clicking on the “ADV.B”  blue button in the debugger toolbar, this brings up a dialog like this:


I just punched in the address of my buffer, selected access type as Write. Now when the first byte in the incoming CDC buffer is written with good / or garbage data the code should break and point me to where the data writing happened. Again I stared sending data, and I had to click on the green debug run icon couple of times, to skip through good cases until the bad garbage write happened. The MPLAB debugger didn’t stop every time the bad case happened , I am not sure if this is a limitation of the debugger or something caused by my code bug, but finally it stopped at a place where I defined some code that was executed inside an interrupt.


This is the code for receiving the data over the other port the TTL USART, not the one having problems CDC Serial !  It basically fills out a buffer called usart_rx_buf, but this not the cdc_data_rx buffer so how could they interfere?  Eureka ! Buffer overflow – the index used to access the buffer byte  uasart_rx_pos was going crazy out of bounds. Indeed I looked at how usart_rx_pos was declared:


The only other place where this variable was used was in this non-interrupt code:


Now this is a big problem, let’s look at the last statement

usart_rx_pos = 0

If we look at the disable of this instruction, on a PIC 8 bit controller we can see that it takes actually 2 instruction to complete it:


This is because this is a 2 bytes variable . Now think what would happen if the interrupt happens between these two instructions. The interrupt mentioned above modifies the variable. So while the main code thinks it has “0” in usart_rx_pos, in fact it only sets to 0 the second part of the variable the first one could have been modified by an interrupt! Thus the unpredictable behavior … usart_rx_pos becomes a random variable which causes the buffer overflow. Data is written at random locations in program memory . Scarrrrrry !

So how did this happened , even if  “I’ve been there done that” many times ? Well the timer interrupt code was not inside an interrupt initially , I later migrated it to an interrupt and forgot to do a sanity check of variable types. In fact I don’t need an int for usart_rx_pos (the buffer is smaller than 255). So I changed it’s declaration  to:


Now that writing of one byte is done in single instruction there’s no risk of corruption by an interrupt updating same variable. However as we’ll see below this is only part of the solution. Below is the disassembly code of writing 0 to a one byte variable:


Please note that I also added an important ‘volatile’ specification in front of all variables modified by the interrupt code.  Actually the lack of ‘volatile’ was my second guess why the bug happened. Without ‘volatile’ compiler might think that there’s no other place where the variable can change besides the spot it compiles. So it might optimize the code in weird ways. Here is an example, if a variable is not volatile the compiler could theoretically update this code

x =  1;
y = 0;
x = 1;

to simply

x = 1;
y = 0;

It removes the second assignment of x since it considers it redundant, while in fact if you have an interrupt executing let’s say before y=0 , and modifying x=0 thus in this case the  x=1 at the end is necessary ! So ‘volatile’ basically tells the compiler that a variable can change suddenly ‘out of the blue’ and it should take care while optimizing the code and not to remove any assignments even if they look redundant.

I’ll now present my final solution to ensure the interrupt code does not modify usart_rx_pos and usart_rx_buf  while we’re processing it in non-interrupt code.  The solution is to prevent the interrupt from happening during that time. No worries, if interrupt has to happen while it was disabled by us -  there ‘s usually  a flag set and the interrupt will happen eventually once we’re re-enabling it. Because the processing in session_new_char() might take a while (and you don’t want to disable USART receiving interrupts for a long time) my strategy was to declare two SAFE non-volatile variables and copy data over quickly then re-enable the interrupt. Please note that this code would work fine even if usart_rx_pos was an int (dual instruction assignment) :





Please note that I didn’t have to disable all interrupts, it was enough to disable only the interrupts that would cause our variable to be modified (the USART Receive interrupt). It’s enabled  or disabled by the RC1IE flag in PIE1 register.

After testing this new code, the problem was gone. So now I am thinking “everything is for the best” , I spent some time tracing a bug, but I learned along the way and sure thing  I wrote this tutorial so I never again forget that interrupts can modify variables when you don’t expect to !

Bottom line:

A.  Declare variables modified in interrupts as  ‘volatile’ to stop compiler doing nasty things to them
B.  Disable the interrupts that can modify those variables, while working with these variables in a non-interrupt code (both reading and writing), this will create a so called ‘atomic’ code, called so because it cannot be split by an interrupt.
C.  Keep ‘the atomic’ code short – the interrupts can wait , but not for too long in some cases.  For example the hardware USART buffer on my device only has 2 bytes – so it would get filled and lost soon if the processing done in the interrupt   would be halted for too long.
D. Have fun. Life is beautiful even when debugging Smile


Quadcopter Prototype using Acc_Gyro and a PIC

For anyone following this site, here is what I've been up to lately – building a quadcopter based on the Acc_Gyro 5DOF IMU sensor and a 16bit PIC. Although it's still a work in progress I decided to start putting together an article placeholder and build it up as project evolves. It's going to be a long one !

The source code will be Open-Source and will be hosted on Google Code, you can get code for quad copter here:

As usual I like to start with a video demo, it's basically me controlling the tilt of the quad using a RC controller:

Read More »

Trickster Mouse Emulator – April Fools Day Practical Joke

Trickster is a simple application built on UsbThumb platform. It tricks your victim into thinking they have a virus on their computer, by hardware emulating and moving their mouse in circles on intermittent intervals.

Read More »

Updating Firmware on USBThumb

USBThumb can be programmed with different firmware, including all Microchip samples from USB Framwework (use the ones for low pin count USB demo board).

In order to upload a new firmware to USBThumb you need to enter the bootloader mode. This is done by connecting the  VPP pin to ground during the time when device is plugged into the USB port.

This can achieved by placing a jumper wire or a 1K resistor (recommended) between GND and VPP pin.

GND pin is number 1, and VPP is number 5. Make sure you do not confuse VPP with the nearby VDD(pin number 4) or you will get a short !!! To be safe use a 1K or 10K resistor instead of the wire. Wire/resistor can be held by the spring action, it only needs to make contact during a split second while the device is plugged. If you plan on making frequent firmware updates , soldering a header is recommended.


Read More »

Using USBThumb as a Propeller Programmer and as a USB to Serial Converter

The Parallax's classic propeller programmer PropPlug  is simply a USB to Serial converter, the DTR/RTS signals are used to reset the Propeller chip before starting the programming sequence.

A custom PIC firmware  comes preloaded on the
"USBThumb Propeller Programmer" available on, it allows you to use USBThumb as a Propeller Programmer but also as USB to Serial converter.

USBThumb (loaded with USBThumbSerial firmware)  is detected on your computer as a standard  CDC Modem device and works on all modern operating systems (Windows, Mac os , Linux).

On Windows you might be asked for driver path once you attach the device, simply use the driver part of the Microchip's USB Framework (it can be found in C:\Microchip Solutions\USB Device – CDC – Serial Emulator\inf\win2k_winxp ) , and I am including a copy for direct download here:

On Windows you can identify USBThumb's COM port number from Device Manager:

3-15-2010 10-24-15 PM.png

Read More »

USB Motion Gamepad Update: wide accelerometer and gyroscope support, configuration utility software

I have received some feedback from my readers regarding my first usb gamepad project , so for the past few weeks I was working on a new imrpoved design. There are plenty of new improvements that I hope will address many of your requests.

Read More »

Use macro definitions to simplify work with I/O ports in C (MICROCHIP PIC/ATMEL AVR)

Wouldn't it be nice that instead of the following PIC  C  ( or similar AVR C ) code:

TRISAbits.TRISA2 = 1;  //make switch pin an input
WPUAbits.WPUA2 = 1;    //turn on the pull-up on switch pin
TRISBbits.TRISB5 = 0;  //make led pin an output


You could just right something like this, that allows you to change later on the PIN assigned for a specific function:


#define pinSwitch(f)       f(A,2)        //Declare Switch pin RA2
#define pinLed(f)          f(B,5)        //Declar Led pin RB5
_TRIS(pinSwitch) = 1; //make pin an input
_WPU(pinSwitch) = 1;  // turn on internal pull-up on switch pin
_TRIS(pinLed) = 0;    // make led pin an output


If you're interested how you can simplify your PIC/AVR C code then read on ….


I started working with MCUs using Basic Stamps 2. My first programs where written in PBASIC. I enjoyed the simplicity of this language but soon moved on to C. One particular thing that I was missing in the C enviroment was the ability to define a pin at the begining of the program and then perform various operations on it. (Make it an input or output, toggle the pin, read its level, output a high or low signal). PIC Microcontrollers make use of several registers to perform these operations, and if you change your pin you need to update all your lines of code that perform these operation.

To illustrate let's take a simple example. Let's say you have a button and a led, you'd like to create a simple application that will turn on the led when a momentary switch is pressed. The hardware setup will be very simple: the led is connected to an output pin of MCU (with a resitor in series to avoid burning the led); the switch is connected to another pin with an optional external pull-up resistor (some PIC and AVR can use an internal pull-up). Please note when the switch is pressed it will output 0 (LOW) and when it is not pressed it will output 1 (HIGH) due to the pull-up resistor.

Read More »