Category Archives: Novice

PIC talks UART on IR

 

PIC talks UART on IR

IR-Modules

Overview

When talking about infra-red communication my first thought goes to TV remote controls, my second to IrDA. This article is about the remote control type of infra-red which provides the physical layer on top of which one must build the rest of the communication. IrDA is a complete stack and albeit being used for similar purposes, it requires different devices and considerations compared to what we will see in this article.

The very nature of infra-red dictate the boundaries of its implementation. Just as with visible light the communication happens by either direct line of sight but also by reflection.

One tip to overcome the limitations imposed by the line of sight is to provide more than one transmitter installed at different angles so as to cover wider angles or install a matte material in front of the receiver to help increasing its operating angle.

The wave length ranges from 700 nm to 1 mm. Within this range there are further subdivisions. Our components work in the Near Infra-red part or NIR  which spans from 750 nm to 1400 nm.

For this article we will use two sensors from iNex.

One of the useful tips when dealing with infrared is to use a CCD or CMOS sensor in order to make the infrared visible to us. Using your phone will do the job just fine but why can it render “the invisible” visible on its display? Well it turns out that it is a rather interesting reading. Have a look at Icarous82 answer on this forum and the spectral response of some cameras to which he also provides a link to.


  The communication

In order to carry our information over infra-red we then need to modulate it over a carrier wave.

Infra-red is a radiation that is strictly linked with temperature. As such there are normally many sources of infra-red in any given environment and we need to be able to filter out all the ones we are not interested in. Our sensors are set to work with modulated signals so as to make sure that the sender signal is made “extremely interesting” to the receiver.

As you can appreciate from the block diagram off of a Vishay datasheet, the sensor incorporates a demodulator and a filter which is set to a specific frequency. In our case 38 kHz.

Phototransistor Block Diagram

Phototransistor Block Diagram

 

In order to carry our information over infra-red we then need to modulate it over a carrier wave. The 38 kHz signal needs to be generated at the sender side and our data will piggy back onto it until it gets to the receiver. The phototransitor at the receiver demodulates the incoming signal and strip the carrier from the data. From then on the receiver will work as a plain UART like in our main article.


 The Circuit

The circuit below includes two NAND ports off of an —– which are used to modulate the signal onto the carrier wave.

PIC-Talks-UART-IR

Circuit setup

Below a picture of the two iNex modules and the breadboard I used to take the measurements.

The IR module and the breadboards

The IR module and the breadboards


The Code

The TX part of our program will be very similar to the one of the main article, the major difference is given by the instructions that will be used to configure and generate the 38 Khz carrier wave for our “Hello, world!”. The other minor difference is about the baud rate which needs to be set to 4800 bps because the modules are not designed for anything higher.

The 38 Khz signal is generated via the Pulse Width Modulation which is a technique used to switch on and off a signal off pin RC2 to generate the square wave we need.

void main() {
  ANSEL  = 0;                     // Configure AN pins as digital
  ANSELH = 0;
  C1ON_bit = 0;                   // Disable comparators
  C2ON_bit = 0;
  
  PWM1_Init(38000);               // Initialize PWM1 module at 38KHz

  UART1_Init(4800);               // Initialize UART module at 4800 bps
  Delay_ms(100);                  // Wait for UART module to stabilize

  while (1) {                     // Endless loop
        PWM1_Start();                        // Start PWM1
        PWM1_Set_Duty(100);                  // Set duty cycle
        
        UART1_Write_Text("Hello, world!");   // 0x48 0x65 0x6C 0x6C 0x6F 0x2C 0x20 0x77 0x6F 0x72 0x6C 0x64 0x21
        UART1_Write(10);                     // 0x0A
        delay_ms(1000);                      // Wait a bit
        UART1_Write_Text("From 0xEE.net");   // 0x46 0x72 0x6F 0x6D 0x20 0x30 0x78 0x45 0x45 0x2E 0x6E 0x65 0x74
        UART1_Write(10);                     // 0x0A
        delay_ms(1000);                      // Wait a bit
  }
}

Here you can fin the full TX code and the RX code for MikroC


The Results

The only part which seemed interesting showing was the one from the logic analyser point of view as it gives a nice representation of the various stage through which our signals get eventually mixed together to produced the 38 Khz modulated signal that we are sending to the receiver.

Signals through the NAND ports

Signals modulation via NAND ports

Logic analyser

To highlight each signal I have chosen the same colours on both the diagram above and the logic analyser (it was a poor choice of colours on hindsight)

Bitscope-Logic

Logic analyser – All signals

Below is the signal as coming out of TX on PIC1

Bitscope-Logic-UART

UART

It then needs to be inverted by going through a NAND which we use as a NOT by fixing on input to 5V

Bitscope-Logic-InvUART

Inverted UART

RC2 generates the 38 Khz carrier wave

Bitscope-Logic-Carrier

38 kHz carrier

and both the inverted signal and the carrier wave, get mixed together on another NAND port to produced our 38 Khz modulated UART

Bitscope-Logic-Modulated

Modulated signal

when going through the filter within the module at the receiver end, the signal returns plain and simple as the red one above and can be applied to pin RC6 of PIC2 without any further manipulation.


 

LCD output

Sure enough the LCD on PIC2 will show our familiar message.

"Hello, world!" on the LCD

“Hello, world!” on the LCD

This article does take into considerations any method to filter out interferences which in wireless communications are to be always accounted for. The following picture shows a message displayed whilst I was using another IR remote just to confuse the receiver.

Wrong message consequence of interference

Wrong message consequence of interference


Final thoughts

IR communication is quite fun, many devices use this method which is cheap and reasonably reliable, It will allow your projects to free from wired umbilical cords and inspire countless hacks like the following from Kerry D. Wong

Reverse Engineering the Syma S107G IR Protocol

With any wireless type of communication though interferences and signal degradation are to be expected and will affect your projects much more frequently than wired links will. To deal with error detection and error correction you might want to consider including ad-hoc algorithms or implement some of the standard ones. Chas was suggesting looking at  High-Level Data Link Control (HDLC) or Hamming code both of which could be right for anything as tiny as 8 bit microcontrollers.

As always we hope the article was helpful.

PIC talks UART on RS-485

PIC talks UART on RS-485

Overview

RS-485 is a differential serial communications link. The link is not open-ended and doesn’t use the local hardware’s ground. The specification is defined by hardware; not the actual communications protocol. I’ve personally ran into dozens of different protocols using RS-485 that including MODbus, BACnet MS/TP, Johnson Controls N2Open, etc. Officially “RS-485” is now TIA-485-A but you’ll find it called RS-485 or EIA-485 more times than not, I’ll switch to referencing this standard as “TIA-485” or just 485 for the remainder of the article. TIA-485 was designed to be a multi-drop bus for multiple devices and multiple “masters” on one communications trunk. Most commonly you’ll find TIA-485 on a 2, 3 or 4 wire circuit with 24-18 gauge wire. The specification boasts of long distance communication relative to its old cousin RS-232, up to 4000ft. TIA-485 is still heavily in use with power control, automation, and monitoring systems. Nearly all commercial and industrial controls systems use TIA-485 to date. You can read more in TSB-89-A.pdf including some of the definitions I’ve used.


 

The communication

It is important to remember TIA-485 is an electrical specification, not a software protocol nor are their recommended physical interfaces. There are other specifications which sit on top of the TIA-485 specifications, BACnet MS/TP and MODbus being two popular choice in industry but likely not your best choice as a hobbyist. The specification was embraced by industry when it was released by the EIA in 1983 so it makes a great option for wired communications for microcontrollers. I’ve personally seen many 6502-variant systems with robust proprietary protocols on top of the bus so you should be able to develop your own protocol with out too much overhead on many of the PIC mid-range devices.

Typical speeds are 9,600 to 115k baud. In my experiences I’ve seen 9,600, 38,400 and 76,800 baud used most commonly. Typically longer segments use slower speeds for reliability, however if you have short runs you can run your bus into the multiple Mbps range.
Multiple devices? Yes, In practice the specification defines up to 32 “loads” on one bus. There have been some clever devices developed to operate as a “1/2 load” allowing for 64 devices on one segment.

Some of the actual specifications:

  • Balanced interface
  • 120 Ohm typical impedance
  • -7 to +12V common mode range
  • 200mV differential voltage between twisted pair
  • 100Kbps @ 4000ft (much faster the shorter you limit the bus)
  • full duplex (4-wire) or half duplex (2-3 wires)
  • 32 nodes

In my example I use a USB to RS-232 adapter to my PC followed by a RS-232 to TIA-485 adapter from B&B Electronics model number: 485SD9TB ($75).


 

The circuit

For this circuit I pulled some small 20-pin PIC development boards I had created for some experimentation with TIA-485. I hadn’t gotten to use these yet and as these were the second PCB I had ever developed in Eagle CAD I found I had made a few mistakes so I will not publish the circuit as it would be a disservice to you. You’ll note a little dead-bug wiring with the /RESET pull-up resistor. I also placed some of my jumpers in a manor I had wished I configured differently. Perhaps I’ll re-manufacture these for the more expanded board in a future article. Below I have provided a “sample” circuit which is the RS485 click board if you’re using a MikroElektronika development board. I used the Analog Devices ADM485 for my circuit although I’ve been testing some polarity agnostic devices from other manufactures. The ADM485 is a low power transceiver; You can review its specification sheet in this PDF. I used a simple test configuration as shown in this diagram:

EIA485_circuit

 

In your circuit you will want to connect your UART TX pin to the transceiver DI pin. A digital output pin to DE to enable/disable the driver. Your UART RX pin will be wired to the ADM485 RO pin and another digital output connected to the RE pin to enable/disable the receiver. The other connections on the transceiver include the power and the A and B bus pins that you connect to other transceiver chips as shown below. I used a common two wire bus configuration.

IMG_4781

 

This is photo was pulled from the TI RS-485 Reference Design Guide

Typical daisy-chain bus structure

Typical daisy-chain bus structure.

 

EIA-485 home-brew development board

EIA-485 home-brew development board

Francesco scolded me for trying to pass off this mostly-hardware article without at least a hint of a schematic; what was I thinking? 🙂 Below is the schematic of the RS485 click from MikroElecktronika. This is a good starting point. You’ll notice some options to drop in termination resistors (jumpers 32, 33, and 34 depending on how you want to reference your signal, talking about ground loops and ground potential difference is beyond the scope of this article but that is the purpose for the jumper configurations). This board was set up for half-duplex as was mine. This is the most common configuration of the 485 bus.

A sample schematic for a UART to 485 interface. Note the ADM485 is pin compatible with the SN75176. The schematic shown is the actual schematic of the RS485 click board from MikroElektronika.

A sample schematic for a UART to 485 interface. Note the ADM485 is pin compatible with the SN75176. The schematic shown is the actual schematic of the RS485 click board from MikroElektronika.

The Code

The code is no different from using the standard UART on the PIC. You can read more about that on our UART article or use any UART code you desire. To use multiple devices you will may have to develop your own protocol for addressing and sending/receiving/replying to data. I’ve place this on my “PROJECTS TO-DO” list and will link that project in once I get to it.

For my testing I re-used my code on the PIC talks UART article, but in this case I had previously made a TIA-485+20 pin PIC development board so I decided to port my code to the PIC18F14K22. Instead of ‘Hello world’ I opted for the program to simply repeat a character for easy testing.

You may recognize this simple XC8 UART transmit function:


void uart_xmit(unsigned int mydata_byte) {   //this function sends 1 character to the UART transmit buffer
while(!TXSTAbits.TRMT);   // make sure buffer full bit is high before transmitting
TXREG = mydata_byte;   // transmit data by loading variable into the TXREG register
}

void write_uart(const char *txt){
    while(*txt != 0) uart_xmit(*txt++);     //this send a string to the TX buffer through my 'uart_xmit' function
                                            //one character at a time
}

And then the actual code to send the repeating characters:


while (1) {
 write_uart("Hello, world!");   //send Hello, world! to UART
 uart_xmit(0x0A);   //send an ASCII character for line feed
 __delay_ms(149);   //delay 149 milliseconds
 write_uart("From 0xEE.net");   //send From 0xEE.net
 uart_xmit(0x0A);   //send an ASCII character for line feed
 __delay_ms(149);   //delay 149 milliseconds
 } //... wash, rinse, repeat

I have plans to develop a light-weight protocol for use in some projects. My goal is a single master with multiple “slaves”. The slaves will be “polled” so they will listen and only respond when commanded to respond. I will likely include some form of change-in-state poll on a quick poll and follow-up with actual polling of data as needed. I will also include some form of addressing and ability to “time-out” on devices no longer on the bus or powered down.


 

The Results

 

Oscilloscope

For ease of visibility I picked on one letter to show you what the signal between the 485 A and B bus terminals looks like on the oscilloscope. You can clearly see the Z character (binary ‘1011010’). As before the data is transmitted LSB first with a start and stop bit 0101101, note that this signal is inverted from the signal recorded below on the logic analyzer. I made this measurement at the A/B output of the transceiver chip.

The EIA-485 signal reading ASCII character "Z" on an oscilloscope.

The TIA-485 signal reading ASCII character “Z” on an oscilloscope.

Logic analyzer

The output of the logic analyzer…  this shows the capture of the UART output as it goes to the transceiver chip on a single character (for comparison with the above TIA-485 output):

Using the logic analyzer to look at the ASCII character "Z" being send by the UART to the ADM485 transceiver.

Using the logic analyzer to look at the ASCII character “Z” being sent by the UART to the ADM485 transceiver.

As before here is the whole string in the test program being captured:

Hello.. on Logic Analyzer

Terminal program

For my test I decided a quick connection to my PC through its RS-232 port and converted over to TIA-485 by the B&B converter showed my circuit was working correctly and the UART on the PIC was sending proper information to my PC.

Sending Hello World! from PIC UART through TIA-485 bus and converted to RS-232 to be captured by a terminal program.

Sending Hello World! from PIC UART through TIA-485 bus and converted to RS-232 to be captured by a terminal program.

 

Connecting to the UART on the PC via TIA-485

Connecting to the UART on the PC via TIA-485

Physical Measurements

Enabling and Disabling the transceiver shouldn’t be left to the wayside if you’re only using the circuits for point-to-point communications. I noted that my circuit consumed 5mA with the transceiver disabled, 61mA enabled with no termination resistors and 83mA with a 100 Ohm termination resistor at the output of the transmitter. A considerable amount of power if you’re operating on batteries.


Final thoughts

 

As usual you can find more information on Wikipedia and a number of other sites including Analog Devices, TI and Maxium who make interface chips for the communications link. I look forward to developing a light-weight 485 protocol for the PIC and perhaps it’s something we can build on with our readers input.

Why? What use is TIA-485 to you and me? Well if you haven’t figured it out by now I have always favored TIA-485 in two applications:
1. hardwired communications lines that run more than a couple feet, and
2. When I want multiple addressed micro devices to communicate on the same trunk to a master and perhaps with each other.

 

PIC talks UART on RS-232

PIC talks UART on RS-232

Overview

In this follow up of the PIC talk UART series we will be looking at how to use a new IC in combination with our PIC in order to talk to a PC. PCs have been equipped with an RS-232 for many many years before it was phased out in favour of other interfaces. Back then the serial port, the parallel port, the PS/2 and the joystick port where the interfaces you would use to connect the mouse, the printer, the keyboard and of course the joystick. Everything was then replaced by the USB, one standard to rule them all! Until the USB effectively took over the RS2-32 had been used to interface a plethora of devices including various types of instruments and other electronic gadgets. One of its uses comes from the mainframe and teletypewriter times. With DOS time it had even been used to connect two PCs together in a sort of one to one network in order to exchange data.
Wikipedia, as usual, will be able to tell you much more about the RS-232 (TIA-232-F) as will many other sites including Sparkfun with this nice article.

For our tutorial we will be using an USB to RS-232 in order to enable our PC to have its RS-232 back on board (be aware that Win8 might give you problems with some e.g. prolific). In terms of the terminal emulator you have many choices which will also depend on the OS that you are running. Here you can find some examples:

Windows

Hyperterminal (if your OS still has it, Win7/8 no longer package it)
TeraTermPro
Putty
Mikroelektronika’s USART terminal (available as a tool in the Mikro compilers)

Linux

Picocom
Minicom
many others through the GUI and depending on the Linux distro of choice

We will be using TeraTermPro on Windows and Gtkterm on Lubuntu) .


 

The Communication

The RS-232 uses has different electric characteristics from the TTL signal provided by the PIC. The RS-232 compared to the TTL signal, will be inverted and range between -15V to +15V. Be aware though that, as reported on Wikipedia Valid signals are either in the range of +3 to +15 volts or the range −3 to −15 volts with respect to the ground/common pin; consequently, the range between −3 to +3 volts is not a valid RS-232 level“. In order to be able to interface the PIC to an RS-232 of a PC, we will need an IC like the MAX232 whose role is to convert the TTL/CMOS signal into an RS-232 and vice-versa

MAX232 Pinout and Typical Configuration

MAX232 Pinout and Typical Configuration

Known limitations

While RS-232 once enjoyed ubiquitous use throughout the interface world, it has it’s limitations. Namely:

Common Ground
Due to a single signalling wire with a common ground the RS-232 has a limited cable length usually quoted to 15 meters (50 ft). This also allows for current loops when the devices are powered from separate sources.

Point-to-point
There is no specification for multiple devices on one bus. This is usually not a problem but can sometime be troublesome in micros when there is usually only one, maybe two UARTs on the micro.

RTS/DSR
Handshaking is unreliably implemented, many if not most hobbyist projects do not use hardware handshaking.


 

The Circuit

Based on the above our circuit will look as the one in the picture below.

PIC-Talks-UART-RS232

Circuit setup

For me to be able to take the measurements available in the results I have used a DB25 breakout box so that I could create the necessary connections and also probe them with the oscilloscope. To do so I have also used a couple of DE9 to DB25. (It is DE9 not DB9, there is no such a thing as DB9!)

RS232 Breakout

RS232 Breakout

Note that I haven’t crossed pin 2 with pin 3 and vice versa on the DB25 of the breakout connector in respect to the DCE to DTE connection pinout which requires a straight cable. (The very same used between PCs and modems)

RS232 Breakout chain

RS232 Breakout chain

Of course I could have used a breakout box like the one in the picture below but it seemed a bit of an overkill for this tutorial!

RS232 Breakout over the top

RS232 Breakout over the top

The Code

With regards to the code nothing changed from the main article with the exception that we will only be using the TX part. Nothing would stop us from reverting roles and have the PC communicating with the PIC. We would then need to run the RX part of the code on the PIC but the result would essentially be the same.


 

The Results

In reviewing the results, we will only focus on the measurements from the oscilloscope and the output on the terminal emulation program. There is in fact no need to look at the logic analyser as all of that is unchanged from the main article.

Oscilloscope

What the oscilloscope shows on channel 1 is the “Hello, world!” in its TTL form. The signal is kept high at 5V when the communication is idle. This measurement can be taken off the bridge linking pin 25 on the PIC to pin 11 on the MAX232.

Rigol Scope TTL

Rigol Scope TTL

When moving our probe to pin 14 of the MAX232, the signal we would get is the one of channel 2 shown below which is in line with the IC specifications on the datasheet. In idle state the line is kept at -7.5V. This means that the LOW signal ranges between 0 and -7.5 volts indicating a logic 1. As soon as the message starts, the level will move to 7.5V indicating a HIGH signal which corresponds to a logic 0.

Rigol-Scope-RS232

Rigol Scope RS-232

When viewing the two overlapped, it is rather evident that the logic levels are inverted.

Rigol Scope TTL-RS232

Rigol Scope TTL-RS-232

Terminal emulator output

Sure enough on the side of the PC, the terminal will show our message in pretty much the same way the Bus Pirate did.

TeraTermPro-Message

TeraTermPro Message

Not sure the results would have been universally right 🙂 , we have tested things on a Lubuntu instalation. Note the name of the device that gets created when plugging in our USB to RS-232 adapter.

Gtkterm-Message

Lubuntu Gtkterm Message

Final thoughts

The RS-232 is a really nice way to have your PIC talking to a PC. It is particularly useful when debugging code and to connect to more and more rare devices that come with that interface. You will be surprised though of how many times you can still come across the DE9 connector!

Buying an USB to RS-232 adapter is a good investment especially considering that the majority should sell at less then £10/$16. On the TTL side of your circuit you can also buy ready made TTL to RS-232 module for £5/$8, or you can build your own as I did.

MAX232-Proto

We hope you enjoyed reading this tutorial, more to come soon.

PIC talks UART

 

PIC talks UART

16F887 UART Breadboard Hello World

Overview

This article is about connecting two PICs via their UART. If you need to know about UARTs just Google that up, if you want to see them up close … read on!

Serial communication is something that has been around for quite some time and it is still very present today in many shapes and forms. When working with embedded systems knowing how to use the UART is of the utmost importance. The UART can be used for micros to talk to each other, for a micro to I/O to a terminal running on a PC, to interface to devices like a GPS module or a Zigbee or an infrared module.

For this article we will be using two PIC16F887 40 pin PDIP and compile the code with MikroC and Microchip XC8. We will be using two Mikroelektronika’s EasyPICs boards for the preparation of the material but we will also provide instructions on how to achieve the same results on a breadboard.

The two EasyPICs board connected via UART

The two EasyPICs board connected via UART


 The communication

At the wires level the two PICs will interface using PINs 25 and 26. These are the PINs reserved as TX and RX.

16F887-pinout-UART

PIC16F887 pinout

They are respectively RC6 and RC7 of port C in the block diagram below.

16F887-block-UART

PIC16F887 block diagram

16F887-Datasheet-USART-PINs

RC6/7 modes and functions

The signal generated should look like the one below. Bear in mind that our PICs will use simplex asynchronous communication. Wikipedia’s Universal asynchronous receiver/transmitter has additional information.

signal-UART

UART signal

The line is kept high until the transmission starts bringing the line to low and logic 0, then 8 or 9 bits are transmitted. The packet is terminated with a stop bit which is always 1. In this way the signal is brought back to high. Further details on the inner workings of the UART module can be found in the Serial Communication Modules of Mikroelektronika e-book and in Microchip PIC Mid-Range USART.


 The circuit

Our circuit will be as follows, we are connecting the PICs so that the TX on PIC1 is connected on the RX on PIC2 and vice versa the TX on PIC2 to the RX on PIC1. This configuration is also known as NULL-Modem.

Circuit setup

Just to make things easier in order to replicate the circuit on a breadboard, we have provided a BOM and a description of the breadboard set-up in another article … 40-pin (6F887) DIY Protoboard

Once the breadboards are ready and connected, they should look like this

UART-breadboard-connected1

Breadboards connected


UART-breadboard-connected2

Breadboards connected from another angle. The LCD hooks up neatly on top of the microcontroller

The Code

The aim of the program on PIC1 is to send a “Hello, world!” message to PIC2 so that the program running on it can display the message on its LCD.

The TX side will first of all set the baud rate, in this case to 9600 bps, then enter an endless loop in which it will write “Hello, world!” and “From 0xEE.net” to its UART at 1 seconds intervals. Between each message a character 10, representing a linefeed, is also sent as a terminator.

UART1_Init(9600);               // Initialize UART module at 9600 bps
  Delay_ms(100);                  // Wait for UART module to stabilize

  while (1) {                     // Endless loop
        UART1_Write_Text("Hello, world!");   // 0x48 0x65 0x6C 0x6C 0x6F 0x2C 0x20 0x77 0x6F 0x72 0x6C 0x64 0x21
        UART1_Write(10);                     // 0x0A
        delay_ms(1000);                      // Wait a bit
        UART1_Write_Text("From 0xEE.net");   // 0x46 0x72 0x6F 0x6D 0x20 0x30 0x78 0x45 0x45 0x2E 0x6E 0x65 0x74
        UART1_Write(10);                     // 0x0A
        delay_ms(1000);                      // Wait a bit
  }

The RX side will setup the baud rate to match the one from the TX PIC and then simply stay in an endless loop waiting for data to be ready. If some data is received. Each byte representing a character gets stored in an array of characters until a \n or linefeeld is received at which point the array is considered complete and ready to be displayed on the LCD via the next line.

UART1_Init(9600);               // Initialize UART module at 9600 bps
  Delay_ms(100);                  // Wait for UART module to stabilize

  while (1) {                                     // Endless loop
    if (UART1_Data_Ready()) {                     // If data is received,
       UART1_Read_Text(received,"\n",255);        // Store in received everything before a linefeed
      Lcd_Out(1,1,received);                      // Display received on the LCD
    }
  }

In the XC8 version of the program as shown in the snippet below the bulk of the work for receiving is done in the interrupt service.

void interrupt ISR() {

    if (PIR1bits.RCIF)          // see if interrupt caused by incoming data
    {
        char temp;
        temp = RCREG;     // read the incoming data
        PIR1bits.RCIF = 0;      // clear interrupt flag

        if(temp=='\n')      //if EOL
        {
            index = 0;
            new_rx = 1;             //"ding"
        }
        else if(temp!=1)           //in middle of string
        {
            rxtxt[index] = temp;         //load it up
            index++;                    //increment index
            if(index > 19)              //that's more than enough data
                {
                index = 0;              //reset index
                new_rx = 1;             //"ding"
                }
        }

        //
    }

}
Here you can fin the full TX code and the RX code for MikroC and the TX code and RX code for Microchip XC8.

 The Results

We thought it would be a good idea to give a bottom up approach to analysing what happens during the communication. Much like the ISO/OSI model will look at the different layers from the wires and the voltages up through to the message that gets displayed on the LCD.

Oscilloscope

The oscilloscope is a useful tool to look at voltage levels in the time domain. The scope displays the level from the input from the left to the right. Shown in the screen-shot is the ASCII letters “Hello”. We used a single sequence trigger to capture this sequence of the message. If you use a free-running rising-edge trigger it is difficult to determine what part of the message you are looking at. Note that there are very low levels of noise on the line. If there is noise on your UART communication lines you would find it with an oscilloscope as the oscilloscope is displaying actual voltage levels. In this case each major division horizontal  grid marking represents 2.0V with the middle horizontal marking set up as the 0V reference;  The vertical grid lines indicate time.

Hello at 9600 Baud

“Hello” at 9600 Baud

Logic analyser

One step above the voltage levels measured by the oscilloscope we can position the logic analyser which will interpret the changes of the voltage as logic levels. Depending on the type of signals and the electronics involved, the values will be interpreted as high and low or logic 1 and 0.

Bitscope-Oscilloscope2

“Hello, world!” as logic states

Protocol decoding

In order to better understand the results from the protocol decoders of both the logic analyser and the bus pirate, we can refer to the following ASCII table. The values displayed by both tools are both in hexadecimal.

ASCII TABLE

ASCII Table

Logic analyser decoding

A part from looking a bit more squeezed, the picture below is the same as the one obtained using the logic analyser,

Hello, world as timing

“Hello, world!” as timing

it is only by inspecting it with a packet decoder that the next level of abstraction will be unveiled.

Bitscope-Logic2

“Hello, world!” as UART Packets at 9600 kb/s

By using the hex column of ASCII table above we can already make sense of the packets by matching the numbers with the characters. It is with no surprise that the sequence above reads “Hello, world!” plus a line feed character at the end.

If you are so bold/mad as to look at the logic levels from the wave above, you will notice that the sequence for the “H” character has to be read from left to right to make sense. The “H” character is 0x48 in hexadecimal which in binary translates to 0b01001000. This should be made more evident by looking at the following picture which breaks down the packet sent into its 10 bits.

Bitscope-Logic4

UART packet dissection

Note the duration of each byte sent. At 9.600 kb/s we are sending 9600 b/s. The adjustment made by the baud rate generator produced an effective baud rate of 9.615 kb/s.

9.615 kb/s = 9615 b/s = 9.615 b/ms = 0.009615 b/us
The packet is composed of 10 bits and it takes 1.039 ms to send according to the logic analyser. This means that 1 bit takes 0.1039 ms or 103.9 us. The rate calculated from this yields 0.009624 b/us or 9.624 kb/s which is, rather obviously, very close to the baud rate set by the micro. Hurray!

Bitscope-Logic3

“H” character transmit duration. The duration should read 1.039 ms and not 980 us

Bus Pirate

Much like with the previous tool, when using the bus pirate in UART mode we can decode the message sent by either reading each byte sent

BusPirate-Decode-Input

Bus Pirate input decode

 

Note that the sequence captured on the left is inverted as “From 0xEE.net” comes before “Hello, world!”

while (1) {                     // Endless loop
        UART1_Write_Text("Hello, world!");   // 0x48 0x65 0x6C 0x6C 0x6F 0x2C 0x20 0x77 0x6F 0x72 0x6C 0x64 0x21
        UART1_Write(10);                     // 0x0A
        delay_ms(1000);                      // Wait a bit
        UART1_Write_Text("From 0xEE.net");   // 0x46 0x72 0x6F 0x6D 0x20 0x30 0x78 0x45 0x45 0x2E 0x6E 0x65 0x74
        UART1_Write(10);                     // 0x0A
        delay_ms(1000);                      // Wait a bit
  }

 

 

 

 

 

 

 

 

 

or by reading the raw UART input

BusPirate-Raw-Input

Bus Pirate raw input

Note the linefeed that we have inserted at the end of each message.

Follow the link should you want to know more about sniffing UART packets with the Bus Pirate.

LCD output

Finally our message gets displayed on the LCD connected to PIC2 gets displayed!

"Hello, world!" on the LCD

“Hello, world!” on the LCD


Final thoughts

At the end of this article you should be able to have two PICs talking to each other via their UART whether you are using MikroC or Microchip XC8. With some basic understanding of the protocol we can now move onto connecting to other devices or using different media to achieve the same communication. We will add a number of spin-off of this article as soon as we manage to put them together. Stay tuned!

We hope you add fun and in doing so also learned something new. Please get in touch through the forums, we’ll do our best to answer your questions, cherish your advices and, why not, learn something more.