c167cr can ap

Upload: auntudh

Post on 09-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 c167cr Can AP

    1/24

    /******************************************************************************C167CR CAN Ap. Note projectMain - a_canx1

    This is an example program showing how to use the CAN interface on theKeilMCB167 evaluation board.

    Copyright (c) 1997 Keil Software******************************************************************************/#include #include #include "can_ifc.h"#include "timer.h"#include "can_msgs.h"

    #define TIME_MO 1 /* message object number for time message */

    /******************************************************************************Setup CAN controller

    Returns: nothing-----------------------------------------------------------------------------*/voidsetup_can( void ){

    begin_can_init();

    /* These mask values tell the CAN controller that all bits in amessage id. are significant when comparing the id of a received

    messageto the id's in the arbitration registers of the message objects.

    */CAN_MASK_SHORT = 0xffff;CAN_UMASK_LONG = 0xffff;CAN_LMASK_LONG = 0xf8ff;

    /* Since this program doesn't use message object 15, it isunnecessary

    to initialize the 'mask of last message' registers(CAN_UMASK_LAST and

    CAN_LMASK_LAST).*/

    CAN_MSGOBJ[TIME_MO].msg_ctl = MSGVAL_CLR;CAN_MSGOBJ[TIME_MO].arbitr = ARBITR(CAN_TIME_MSG);CAN_MSGOBJ[TIME_MO].msg_cfg = MSG_CFG(LEN_CAN_TIME_MSG,

    CANDIR_TRANSMIT, 0); /* We're not initializing the data field right now, so we set

    CPUUPD to prevent the message from being transmitted in

  • 8/8/2019 c167cr Can AP

    2/24

    response to a remote frame.*/CAN_MSGOBJ[TIME_MO].msg_ctl =

    /* clear bits set bits */INTPND_CLR &RXIE_CLR &TXIE_CLR &

    MSGVAL_SET &NEWDAT_CLR &

    CPUUPD_SET &TXRQ_CLR &RMTPND_CLR;

    /* CAN_IE_ must be set for any CAN interrupts to occur.CAN_EIE_ must be set for CAN error status change interrupts to

    occur.*/end_can_init(CAN_IE_ | CAN_EIE_);

    }

    /******************************************************************************main

    This program does the following:Set up the CAN controller, with a message object for the time stamp

    messageas a transmit object.

    Setup a timer to generate periodic interrupts.Loop forever, periodically updating the time stamp message object.

    The CAN controller will transmit the time stamp message when itreceives aremote frame for it, without any intervention from the CPU.

    Returns: never-----------------------------------------------------------------------------*/voidmain( void ){

    printf( "Program A start\n" );

    /* Set up */setup_can(); /* set up CAN interface */init_timer(); /* initialize timing */

    /* Run */ while (1) { /* infinite loop */ unsigned long t;

    t = timer();update_can_transmit_message(TIME_MO, &t, LEN_CAN_TIME_MSG);

  • 8/8/2019 c167cr Can AP

    3/24

    /* Put the processor in idle mode to conserve power.The next interrupt (from the timer) will wake it up again.

    */_idle_();

    }}

    1

    C167CR CAN Ap. Note projectMain - b_canx1

    This is an example program showing how to use the CAN interface on theKeilMCB167 evaluation board.

    Copyright (c) 1997 Keil Software******************************************************************************/#include #include #include "can_ifc.h"#include "can_msgs.h"

    #define TIME_MO 1 /* message object number for time message */

    /******************************************************************************Setup CAN controller

    Returns: nothing-----------------------------------------------------------------------------*/voidsetup_can( void ){

    begin_can_init();

    /* These mask values tell the CAN controller that all bits in amessage id. are significant when comparing the id of a received

    messageto the id's in the arbitration registers of the message objects.

    */CAN_MASK_SHORT = 0xffff;CAN_UMASK_LONG = 0xffff;CAN_LMASK_LONG = 0xf8ff;

    /* Since this program doesn't use message object 15, it isunnecessary

    to initialize the 'mask of last message' registers(CAN_UMASK_LAST and

    CAN_LMASK_LAST).*/

  • 8/8/2019 c167cr Can AP

    4/24

  • 8/8/2019 c167cr Can AP

    5/24

    (there are other ways), so also clear NEWDAT to make sure weprocess

    a new time message, not an old one that has been waiting aroundunprocessed.

    */CAN_MSGOBJ[TIME_MO].msg_ctl = TXRQ_SET & NEWDAT_CLR;

    /* Wait for updated time messageNote: Doing it this way, the program will hang here forever if

    themessage is not received.

    */ while (!(CAN_MSGOBJ[TIME_MO].msg_ctl & NEWDAT_)) ;

    /* Process the time message */

    copy_received_can_message(TIME_MO, &time_value); /* If this time message is at least one second later than thelast one

    that was output then output it.*/

    if (time_value - last_printed_time_value >= 1000) {printf( "%lu\n" , time_value);last_printed_time_value = time_value;

    }}

    }

    /******************************************************************************C167CR CAN Ap. Note projectHeader file for timing

    Copyright (c) 1997 Keil Software******************************************************************************/

    #define TIMER_UNITS_PER_SECOND 1000

    voidinit_timer( void );

    unsigned longtimer( void );

    C167CR CAN Ap. Note projectTiming functions

    This is an example program showing how to use the CAN interface on theKeilMCB167 evaluation board.

    Copyright (c) 1997 Keil Software

  • 8/8/2019 c167cr Can AP

    6/24

    ******************************************************************************/#include #include #include "timer.h"

    /* The following macro calculates the value to write to an interruptcontrol

    register. The arguments are:ir: Interrupt request (0 or 1)ie: Interrupt enable (0 or 1)ilvl: Interrupt priority level (0, 1, ... 15)glvl: Group level (0, 1, 2, or 3)

    */#define CALC_IC(ir,ie,ilvl,glvl) ((ir)

  • 8/8/2019 c167cr Can AP

    7/24

    /******************************************************************************Initialize the timer.

    Return: nothing.-----------------------------------------------------------------------------*/voidinit_timer( void ){

    CAPREL = RELOAD_VALUE;T6 = RELOAD_VALUE;T6CON = 0x80c0 | PRESCALE_SELECTION;

    /* interrupt set up */T6IC = CALC_IC(0, 1, 10, 0); /* enable interrupt at priority level

    10, group level 0 */}

    /******************************************************************************Gets the timer value.

    Returns: Elapsed time since the timer was initialized, inTIMER_UNITS_PER_SECOND * seconds.

    -----------------------------------------------------------------------------*/unsigned longtimer( void ){ long temp;

    /* This code was written for a 16-bit processor (Siemens C167CR), sothe

    32-bit variable timer_val cannot be processed (copied,incremented, etc.)

    in a single machine instruction. The _atomic_() and _endatomic_()"functions" tell the compiler to generate an ATOMIC machine

    instructionto protect the sequence of instruction processing timer_val from

    beinginterrupted. If the timer interrupt (which increments timer_val)

    occurredafter one word of timer_val had been copied but before the other

    word hadbeen copied, the copied value could be erroneous. The problem

    wouldprobably occur only sporadicaly, and be maddeningly difficult to

    find.*/

    _atomic_(0);temp = timer_val;_endatomic_();

  • 8/8/2019 c167cr Can AP

    8/24

    return temp;}

    /******************************************************************************Interrupt service routine for the timer interrupt.-----------------------------------------------------------------------------*/voidtimer_interrupt( void ) interrupt 0x26{ /* See comment in timer() function above discussing interruptabilityof

    operations on timer_val.This operation (incrementing timer_val in the interrupt serviceroutine) also needs to be uninterruptable, if any higher-priorityinterrupt handlers make use of the time. Otherwise, such an

    interrupt

    could catch timer_val half-updated and get an erroneous time.*/_atomic_(0);timer_val++;_endatomic_();

    }

    ******************************************************************************C167CR CAN Ap. Note projectHeader file for CAN hardware (non RTX-166 ap. note only)

    Copyright (c) 1997 Keil Software******************************************************************************/

    #include "canregs.h" /* Describes CAN registers */

    /* Given a message id, the following macro computes the value to writeto

    the arbitr member of a CAN message object structure. If a standard(i.e., 11-bit) identifier is being used, the significant bits are28...18, not 10...0. If you are specifying 11-bit message ids in bitpositions 10...0 and wish to use this macro, make sure the id is anunsigned long, and shift it left 18 bit positions, e.g.,

    ARBITR((unsigned long)std_id > 21 & 0x000000ff | \

    ( unsigned long )(id) >> 5 & 0x0000ff00 | \( unsigned long )(id)

  • 8/8/2019 c167cr Can AP

    9/24

    dir is direction. 0 (CANDIR_RECEIVE) receive; 1 (CANDIR_TRANSMIT)transmit

    xtd is extended flag. 0 standard (11 bit) id; 1 extended (29 bit) id*/#define MSG_CFG(dlc,dir,xtd) ((dlc)

  • 8/8/2019 c167cr Can AP

    10/24

    It establishes the bit timing and marks all the message objects invalid.

    The mask registers, and any message objects that will actually be used,mustbe set up separately, and then end_can_init() should be called.

    Returns: nothing.-----------------------------------------------------------------------------*/voidbegin_can_init( void ){ int object_number;

    CAN_CTL_STAT = CAN_INIT_ | CAN_CCE_;

    CAN_BIT_TIMING = BIT_TIMING;

    /* Mark all CAN objects invalid */ for (object_number = 1; object_number

  • 8/8/2019 c167cr Can AP

    11/24

    end_can_init( unsigned interrupt_enable_flags){

    CAN_CTL_STAT = interrupt_enable_flags;}

    /******************************************************************************Copy a message from a CAN object to a buffer.

    This function ensures that the copied data come from a single versionof themessage. If a new version of the message is received while the copy isinprogress, the function will start over, copying the new version.

    The object_number argument specifies which of the 15 CAN objects(1...15) will

    be read.

    The buf argument is a pointer to the buffer the message is to be copiedinto.Only the first n bytes of the buffer will be altered, where n is thenumber ofbytes in the data portion of the CAN message, as specified by the datalengthcode in the message configuration register (0

  • 8/8/2019 c167cr Can AP

    12/24

    (3) Check NEWDAT: if NEWDAT is set, it means the CAN controllerhas

    updated the message (i.e., received a new message).The copied message may be corrupt, so go back to step 1.

    */ do { /* Clear NEWDAT */

    cano->msg_ctl = NEWDAT_CLR;

    /* Copy the message.The Data Length Code for the message is in bits 7...4 of themessage configuration register.

    */length = cano->msg_cfg >> 4;

    /* If CAN_MSGOBJ[object_number] hasn't been properly initialized,the

    data length code could be greater than the maximum valid valueof 8. This function shouldn't be called for an uninitializedCAN object, but mistakes sometimes occur during development.This inexpensive check contains the error in an easily

    identifiableform, rather than allowing the excess data to overwrite

    whateverfollows the buffer in memory.

    */ if (length > 8) {

    length = 0; /* If this statement ever gets executed, youhave a problem. */

    }{

    unsigned char *src; unsigned char *dest; unsigned char *stop;

    src = cano->msg;dest = ( unsigned char *)buf;

    for (stop = dest + length; dest != stop; ) {*dest++ = *src++;

    }}

    } while (cano->msg_ctl & NEWDAT_); /* Check NEWDAT */

    return (length);}

    /******************************************************************************Update a CAN transmit object with new data from a buffer.

    This function ensures that a partially updated form of the message willnot be transmitted.

    The object_number argument specifies which of the 15 CAN objects(1...15) willbe updated.

  • 8/8/2019 c167cr Can AP

    13/24

    The buf argument is a pointer to the buffer the message is to be copiedfrom.

    The number of bytes of data to copy is specified by the length argument.If length >= 0, the DLC (data length code) of the message object ischangedto length, and length bytes are copied.If length < 0, the number of bytes to copy is read from the DLC of themessageobject.If length > 8, or length < 0 and the DLC of the message object is notcorrectlyset up, then incorrect results will occur.

    Returns: length of message data-----------------------------------------------------------------------------*/intupdate_can_transmit_message(

    int object_number, void *buf, int length){ volatile struct can_obj *cano;

    cano = &CAN_MSGOBJ[object_number];

    cano->msg_ctl = NEWDAT_SET & CPUUPD_SET;

    /* The Data Length Code of the message object and the variable'length'

    must match. Change one to equal the other.The Data Length Code for the message is in bits 7...4 of themessage configuration register.

    */ if (length < 0) { /* Get length from the message object */

    length = cano->msg_cfg >> 4;}

    else { /* Set data length code in message object */

    cano->msg_cfg = cano->msg_cfg & 0xf | length msg;

    for (stop = dest + length; dest != stop; ) {*dest++ = *src++;

    }}

  • 8/8/2019 c167cr Can AP

    14/24

    cano->msg_ctl = CPUUPD_CLR;

    return (length);}

    /******************************************************************************CAN interrupt handler

    There is a single interrupt vector for all interrupts generated by theon-chipCAN module. The INTID field of the CAN interrupt register (CAN_INTID)identifies what caused the interrupt. Several interrupt-causingconditions canexist at once, but the INTID field will reveal only one of these at atime.The values of INTID and their corresponding interrupt causes are:

    0: no interrupt pending1: status change interrupt2: message 15 interrupt2+N: message N (1

  • 8/8/2019 c167cr Can AP

    15/24

    while (1) { switch (interrupt_id = CAN_INTID) {

    case 0 : /* no interrupt */ return ;

    case 1 : /* status change interrupt */ /* Interrupts associated with changes in the CAN statusregister

    are handled here.

    Reading the status register clears this interrupt condition.

    If the SIE bit of the CAN control register is set, aninterrupt is

    generated when the CAN controller updates the LEC field ofthe CAN

    status register.

    If the EIE bit of the CAN control register is set, an

    interrupt isgenerated when the CAN controller changes the BOFF or EWRN

    bits inthe CAN status register.

    The only one of these interrupts we are interested in forthis

    program is a change in the BOFF (Bus Off) bit.*/{ /* Bus Off recovery */

    /* During bus off recovery, busoff_recovery_state containsthe

    (non-zero) value to write into the CAN control registerwhen

    recovery is complete. At all other times, it contains 0.*/

    static unsigned char busoff_recovery_state; unsigned char boff; /* reading of BOFF bit in statusreg */

    if ((boff = CAN_STAT & CAN_BOFF_) && busoff_recovery_state== 0) { /* Bus off condition just occurred. */ /* When Bus Off occurrs, the CAN module sets the BOFFand INIT

    bits in its control/status register. It begins thebus off

    recovery sequence when the CPU clears the INIT bit.

    Remember the current value in the CAN controlregister so we

    can restore it later. (Except the INIT bit; it willalways

    be set at this point, and we will always want torestore it

    cleared.)

  • 8/8/2019 c167cr Can AP

    16/24

    Clear INIT bit to start bus off recovery, and clearSIE (if

    it were set) to disable SIE-controlled status changeinterrupts. They are of no interest to us while the

    bus offcondition exists.

    */busoff_recovery_state = CAN_CTL & ~CAN_INIT_;CAN_CTL = CAN_EIE_ | CAN_IE_;

    } else if (busoff_recovery_state && !boff) { /* Bus off recovery just completed */

    CAN_CTL = busoff_recovery_state; /* Restore controlregister from before bus off */

    busoff_recovery_state = 0; /* No longer in bus offrecovery */

    }}

    break ;

    case 2 : /* message 15 interrupt */message_number = 15;

    goto handle_message_interrupt;

    default : /* other message interrupts */message_number = interrupt_id - 2;

    handle_message_interrupt: /* Clear the INTPND (interrupt pending) bit in the messagecontrol

    register for the message object.

    For most applications, you will probably need to do morethan this,

    and you probably need to do different things for differentmessages. But you will always need to do this.

    */CAN_MSGOBJ[message_number].msg_ctl = INTPND_CLR;

    break ;}

    }}

    C C OMPILERS R EAL-T IME OS S IMULATORS E DUCATION E VALUATION BOARDS Programming the Siemens C167CR CAN Interface: A Real Life Case:

    Constructing the HardwareApplication Note 115b - Hooking up the CAN hardware and running the software: Version 1.0By Robert Boys, MISKeil Software, Inc.1-800-348-8051 or [email protected] application note will instruct you on how to connect two Keil single board computers together toconstruct a working two node CAN network. This article has instructions on loading and using theKeil

  • 8/8/2019 c167cr Can AP

    17/24

    monitor and debugger to operate and evaluate the entire system. This note will also work on thePhytecKitCON 167 board that is sold by Siemens.IntroductionGary Culp and Robert Boys wrote an article on the CAN bus in the Siemens Contact magazine inFebruary 1998. The basis of the article was making a two node CAN network using two Keil

    MCB167evaluation boards. This article very briefly described the CAN bus, the Keil CAN libraries and RTOS,the Keil C167CR microcontroller and the MCB167. It then described some unusual and interestingaspects of programming the C167CR on-chip CAN controller. These were discovered during theresearch phase of this article and deemed to be of enough interest to form the main content of thearticle.The original article has become Keil Application Note # 115 and is available on the Keil Website:www.keil.com/~market/115.pdf. The note you are now reading continues the original article andcompletes the experiment. It describes the actual steps required to connect the two boards together andgetting the software running to display the expected results.The Keil Tool Chain - an overviewThe Keil Tool Chain fully supports the entire Siemens C166 and the SGS Thomson ST10microcontroller lines. The Keil Tool Chain includes a C Compiler, Macro Assembler, Linker/Locator, Vision IDE, and the dScope Simulator and Target Monitor.The Keil tool chain consists of the following executables:C Compiler c166.exeAssembler a166.exeLinker L166.exeConverter oh166.exedScope dsw166.exe (a Windows application) Vision uvw166e.exe (a Windows application)These files are located in the c:\c166eval\bin directory for the evaluation version when installed onyour hard drive. The full version would locate them in the c:\c166\bin directory. They are DOS programsexcept for Vision and dScope. Access to these programs from Windows is accomplished with Vision. The entire tool set can be run from Vision or directly from DOS with your batch files.TheEvaluation version is limited in code size to 4Kbytes. Other than these restrictions, all features operatenormally.2 Vision IDE Vision is a Windows based front end for the C Compiler and Assembler. It was developed in theUSAas was the printed manual set. Compiler, Assembler and Linker options are set with simple mouseclicks. Vision runs on Windows 3.1, 95 and NT. This Integrated Development Environment (IDE)has

    been expressly designed with the user in mind. A full function editor is included. All IDE functions

    areintuitive via pull down menus with prompted selections. An extensive Help utility is included.Externalexecutables can be run from within Vision. This includes emulator software.C166 C Compiler for the entire Siemens 166/167 family and SGS Thomson ST10The C166 ANSI compiler and A166 assembler are designed specifically for the Siemens 161, 163,C164CI, 165,166, 167, 167CR, and future derivatives. The C166 easily integrates with the KeilRTOS.The C166 interfaces and passes debug information to the Keil dScope Simulator and all in-circuit

  • 8/8/2019 c167cr Can AP

    18/24

    emulators. The Keil C166 provides the fastest and smallest code using industry benchmarks. TheST10family, which is a second source of the C166 - is supported.dScope Simulator dScope is a software simulator. Your code can be debugged either in software on your PC or in your target hardware. When operated in conjunction with the Keil monitor installed in your target

    hardware,dScope becomes tScope. You have the ability to run/halt, set breakpoints, examine/change memory,view the stack, view/set peripheral information and apply virtual external signals. dScope has aPerformance Analysis feature to ensure your code runs efficiently. dScope has a built-indisassembler/assembler allowing you to make changes in your code without recompiling.The evaluation version of the Keil 8051 tool set is restricted to a 2K code size and the code must belocated at 0x4000. The C166 version can produce up to 4K of code and does not have a startingaddress restriction. Useful object code is produced. Other than these restrictions, the tool set worksexactly as the full version does. This allows you to fully evaluate the features and power of Keil

    products on the Rigel board. The full version has no restrictions and is fully ANSI compliant.FR166 Full-Function RTOS: Siemens 166/167 family and SGS Thomson ST10The FR166 is a multitasking real-time operating system for the Siemens 166 family. You can managemultiple tasks on a single CPU making your programs much easier to develop. The RTX166 Fullincludes CAN libraries. The RTX166 Tiny is a subset of the RTX166 Full and is included with allC166 C Compiler Kits. There are no royalty payments generated by using a Keil RTOS.CAN Library - Controller Area NetworkThe RTX51 and RTX166 Full RTOS supports CAN controllers with the included libraries. The CANlibraries are sold with the RTOS. The CAN interface is becoming popular for automotive andindustrialmarkets. Both 11 and 29 bit identifiers are supported. Keil C166 and 8051 C compilers interface withthe RTOS and CAN libraries. Keil supports all CAN microcontrollers based on the Siemens C505C,C515C, C164-CI, and C167CR. Future CAN products based on these 8051 or C16x Families areeasily supported due to the flexible Keil Compiler design. The Siemens 81C90 CAN peripheral chip issupported with a new Keil evaluation board. Contact Keil Software for details.STARTING THE TUTORIAL

    The SoftwareWhat you need to get started1) Two Keil MCB167 evaluation boards with the CAN physical-layer interface added. You may beable to substitute Phytec or Rigel boards. You need only install the proper monitor and boot files.2) Two PCs with the Keil C166 tools installed and one serial port available for communication withMCB167 boards. The 4K evaluation version of the Keil Tool Set can be used.3) Note: you can use only one PC by switching between this single PC and the two boards either manually or with a RS-232 switch box4) Appropriate cable for connecting the CAN interfaces of the two MCB167 boards.3The CAN programsKeil provides C source code for the A and the B boards. A runs a counter that determines how long ithas been activated in seconds. It also scans the CAN bus looking for a message from B. A sends amessage requesting this timer value. If B receives this message, it sends the timer message to A. Athen prints this value to the serial port window on the Keil debugger dScope.The C source code, project files, compiled object files and startup files are available as file cansoft.zipon the Keil website or was embedded in the file with this document. This file contains all the filesnecessary to reproduce the two programs described in this application note and are listed below.File Descriptiona_canx1.c main() module for program A

    b_canx1.c main() module for program B

  • 8/8/2019 c167cr Can AP

    19/24

    timer.c timer functionscan_ifc.c CAN interface functionstimer.h header file for timer can_ifc.h header file for CAN interface functionscanregs.h header file describing CAN hardwarecan_msgs.h header file for CAN message id.'sa_canx1.prj project file for program a_canx1

    b_canx1.prj project file for program b_canx1ax1_dsco.ini dScope initialization file for program a_canx1

    bx1_dsco.ini dScope initialization file for program b_canx1 boot & monitor dScope monitor kernel for the Keil MCB167 boardcompiled.zip compiled object files and listing filesInstall these files in a directory of your choice. This tutorial used c:\can.Various other files will be

    produced as a result of the compiling and linking process of the Keil ToolSet.The Keil Tool Set - Vision, C compiler, linker, locator and dScopeThis project uses the Keil Vision IDE to interface to the compiler and linker/locator and dScope tointerface to the two the Keil single board computers. You can use either one or two PCs to be the hostcomputer. The Keil evaluation software must be installed on each of these computers if you use two.The evaluation software is capable of compiling and demonstrating this project.Installing the Keil SoftwareInstall the Keil Software development tools by completing the following steps:1) Get the 2 disks from the Keil or Siemens CD-ROM, or the Web site,www.keil.com/demo/ek166.htm or prepare to install them from the Keil CD-ROM in the directory/ek166/.2) To install the Keil EK166 evaluation software from the Keil CD-ROM, run the program/ek166/setup.exe from within Windows. Use the default destination drive of c:\c166eval. If youhave downloaded two floppies from the web - install them in the usual manner.3) If you ever need to reload a totally fresh copy of the Keil C Compiler - you must delete dsw166.iniand uvw166e.ini from your c:\windows\ directory. These files are created and updated by Visionand dScope to retain user settings. You may want to save the existing files under new names tosave your settings.After you install the Keil development tools to Windows 3.11, a Keil program group or icons appearson your desktop. (the Windows 95 version is shown in Figure 1). Recall dScope is the Keil Simulator and Vision is the Keil Windows based user interface (or IDE = Integrated DevelopmentEnvironment).4

    FIGURE 1For Windows 95 you must install the two icons manually as follows. If the two icons are visible in asmall window drag them onto the desktop. If they are not visible, follow these instructions:1) right mouse click while in the Desktop and select New/Shortcut2) The executable file you want to enter as the Command Line is c:\c166eval\bin\uvw166e.exe3) The suggested name is Vision.4) Repeat this process for c:\c166eval\bin\dsw166.exe and name it dScope.The full version of the software installs these icons to the Windows 95 desktop.The Hardware

  • 8/8/2019 c167cr Can AP

    20/24

    The Keil MCB167 does not come with the physical layer circuitry to connect directly to the CAN bus.This layer is easily provided with a Philips 82C250 driver chip. A schematic is provided below asFigure 2. Wire wrap this circuit on the prototyping area of the MCB167. The location of P4.6 and P4.5on the MCB167 is illustrated in Figure 6.P4+5V1U1

    PCA82C250Philips2348765J1AC BR1 120SW1-7276P4.6P4.5C110F16V

    SW1-8Slope Control22kC167CR

    CANBus

    FIGURE 2This demonstration will work without R1 or the ground wire at SW1-8 connected but it is desired. The22K slope control resistor can be directly connected from Pin 8 of U1 to ground. You will not need toadjust the jumper positions on Pin 8 for this demonstration.The on-chip CAN interface of the C167CR connects to the outside world through two pins on Port 4.Port 4.5 is the CAN receive line and Port 4.6 is the CAN transmit line. These pins are shared byaddress lines A21 and A22. These two modes are mutually exclusive. P4.5 and P4.6 can be CAN portsor address ports. Not both at the same time. Addressing mode restrictions apply when using the CANinterface.

    Use the MCB167 default jumper settings and the standard 256K of RAM. J2 in particular must beinstalled. This puts the C167 into the bootstrap mode upon a CPU reset. This is the method thatdScopeuses to load the monitor kernel into the RAM of the MCB167.When mon166.dll is selected within dScope, the file boot is first loaded using the C167 bootstraploader. Boot then loads monitor into the RMB 167-CRIs RAM. These two programs must be in thec:\c167eval\bin directory. If you load the properly configured monitor kernel into on-board FLASH or EPROM memory, you need to deselect J2. For information concerning the Keil monitor see

    Readme.txt in c:\c166eval\mon166.5Connecting it all together 1) Connect the power supply to the two boards

    2) Complete the CAN physical layer connection between the two boards as appropriate for your setup.Pins 7 and 6 of the 82C250 must be correctly connected together along with the ground wire. Use areasonable amount of wire. A few feet will do for this demonstration.3) Connect the serial port of your PC to the COM connector of one of the MCB167 boards. If you areusing two PCs, connect the other serial cable to the second MCB167 and to the second PC.Starting Everything UpStarting Vision for the A board - the Keil IDEDouble-click on the Vision icon to start the user interface. The compiler, assembler, linker anddScope

  • 8/8/2019 c167cr Can AP

    21/24

    will be called from within Vision in this tutorial. After you invoke Vision, the window shown inFigure 3 appears. From this window, you can create projects, edit files, configure the tool, assemble,link, and invoke the debugger. Everything is pre-configured for you for this project.1) Open the Project menu and choose Open Project .2) Select c:\can\a_canx1.prj and press OK.3) Click on the Build All icon (it has three arrows pointing downwards) or open Project and select

    Make: Build Project .4) If the program specified (a_canx1.c) contains any errors, they will be shown on the screen.5) If there are no errors, the code is assembled and linked and the executable code is ready to bedownloaded to the board. The code to be downloaded to the board will be the name of the projectwith no filename extension. In this case this will be a_canx1 . Click on OK in the Project Statusdialog box and continue to the next section. Note a HEX file could have been created. Other filesare created to help the debugging process.6) If a list of errors appears, use the editor to correct the error(s) in the source code and save the file.Then, repeat this section: beginning at step 1. There should be no errors. If there are, somethingserious has gone wrong. Reload all the software.FIGURE 36Downloading the A Software to the MCB167You are now ready to start the dScope debugger to download and execute code to the Keil A board.1) Press the reset button. It is labeled RESET and is beside the 5 volt regulator chip.2) Click on the debugger icon on the Vision toolbar. This icon is a d seen through a magnifyingglass and is yellow and blue in colour. This is the same icon installed for dScope in your desktoparea. If you leave the mouse pointer on an icon for a few seconds, the word debug will appear.A window similar to that shown in Figure 4 is displayed. You may want to move and resize thewindows. The window marked Module: is the Debug window. The Command windowcan be used to enter commands.3) You may need to open, resize and /or move some windows to make your screen look somethinglikeFigure 4. The Debug, Command, and Serial I/O windows will be used. You may want to open theCommands menu in the Debug Window and select Show Toolbar.

    4) Note that the file ax1_dsco.ini configured and loaded dScope. This ASCII file can easily be edited.Its location is specified in Vision in the Options menu under dScope Debugger. The object filethat was loaded into the MCB167 memory is a_canx1. This is the project name with no fileextension. The original C source code needs to be available for source-level debugging.FIGURE 4Running the A Software1) Press Go2) Program A Start with 4 characters beneath it will be displayed in the Serial I/O window. CANnode A is successfully started. It is now waiting for a message from B (which is not started yet).3) If you get errors - a section called Communication Setup - Help ! follows.Starting Vision for the B board - the Keil IDE

    Now you will start the B board. This board sends out a CAN message requesting a time stamp from A.This time stamp will then be displayed in the Serial I/O window. The instructions are the same as for the A board. Only the filenames change.7If using only one PC, move the serial COM cable to the second MCB167. The A board will continuetooperate without intervention of dScope. Start at instruction 1) below.If you are using two PCs; double-click on the Vision icon on the second PC to start the user interface.After you invoke Vision, the window shown in Figure 2 appears as before with A. Everything is

    preconfigured

  • 8/8/2019 c167cr Can AP

    22/24

    for you for this project.1) Open the Project menu and choose Open Project .2) Select c:\can\b_canx1.prj and press OK.3) Click on the Build All icon (it has three arrows pointing downwards) or open Project and selectMake: Build Project .4) If the program specified (b_canx1.c) contains any errors, they will be shown on the screen.

    5) If there are no errors, the code is assembled and linked and the executable code is ready to bedownloaded to the board. The code to be downloaded to the board will be the name of the projectwith no filename extension. In this case this will be b_canx1 . Click on OK in the Project Statusdialog box and continue to the next section. Note a HEX file could have been created. Other filesare created to help the debugging process.6) If a list of errors appears, use the editor to correct the error(s) in the source code and save the file.Then, repeat this section: beginning at step 1. There should be no errors. If there are, somethingserious has gone wrong. Reload everything again. The software has been thoroughly tested.Downloading the B Software to the MCB167You are now ready to start the dScope debugger to download and execute code to the Keil B board.1) Press the reset button.2) Click on the debugger icon on the Vision toolbar.3) You may need to open, resize and /or move some windows to make your screen look somethinglikeFigure 4. The Debug, Command, and Serial I/O windows will be used. You may want to open theCommands menu in the Debug Window and select Show Toolbar.4) Note that the file bx1_dsco.ini configured and loaded dScope. This ASCII file can easily be edited.Its location is specified in Vision in the Options menu under dScope Debugger.Running the A Software1) Press Go2) Program B Start will be displayed in the Serial I/O window on the B PC as shown below. Everysecond a new number indicating in seconds how long A has been running will be displayed in theSerial I/O window shown below. CAN node B is started. B requests A send the time stamp, then Bdisplays it. You now have a running CAN node to experiment with. Congratulations !3) If you get errors - a section called Communication Setup - Help ! follows.

    4) If you get no errors and the Serial windows indicate that both program A and B have started but nonumbers appear in the B Serial window: there is probably something wrong with the physical CANnetwork. The next section describes testing each CAN node to help you track the problems.The first 11 seconds of A running and displaying on B8COMMUNICATIONS SETUP - Help !You need to follow these instructions if proper communication was not established. After a series of attempts, dScope will error out as indicated in the No Target System Found ! dialog box.Select the appropriate configuration. Select the appropriate COM port for your system. The speedmust

    be 9600 for the C167 with a 5 Mhz crystal. Select 19,200 if 9600 does not work.. This depends onwhich version of the monitor you have installed. Monitors for 19.2, 38.4, and 57.6 Kbaud areavailablefrom Keil.After you set the COM port and baud rate correctly, click on Try Again .FIGURE 5If you receive Figure 5 as an error message in dScope; the wrong version of the monitor kernel isloaded into the MCB167 memory. dScope uses the files boot and monitor to load into the Keil boardRAM. The correct files must be loaded into your hard drive where the Keil evaluation software(EK166) was loaded. (default = c:\c166eval\bin). These files are default with the Keil software.Copies are available in the file cansoft.zip that came with this document and it is also available atwww.keil.com/~market/.

  • 8/8/2019 c167cr Can AP

    23/24

    The serial FIFO buffer in Windows 95 can cause transmission problems. dScope may have problemscompleting the communication initialization process. This can be intermittent. The FIFO can bedisabled under "controlpanel/system/device_manager/Port Settings/Advanced". Make sure Use

    FIFO buffers in this menu is not activated.Notes on using RESET in dScope and the MCB1671) dScope in simulator mode: When you are using dScope as a simulator (i.e. no target hardware),

    pressing the 'reset' button does not cause a running simulation to stop at the current point of execution. Reset starts the application from the beginning address (0) again. This situation isevident in example 15 where a reset causes the program to re-run. Press the Stop button to halt a

    program normally.2) dScope in monitor mode (tScope): The monitor is running in the target hardware. A tScope 'reset'sets the IPC to zero and does some other initializations if no user application was started. It is notas good as a hardware reset. The best method to stop an application that is running is to press theSTOP button rather than the RESET button in tScope.'stop' tries to stop a running application when the 'use serial interrupt' option is enabled - or - if notenabled, a dialog box is displayed where you can select the next step. This has the advantage of seeing the 'infinite loop' where your program is stuck. With reset, you are starting at address 0again.3) The Keil board does have a hardware NMI button.9Testing the MCB167 CAN InterfaceAt this point you will have two boards with the physical layer installed, the Keil Tool Set installed,andthe CAN sample programs copied to the c:\can directory. In order to make sure the boards are workingcorrectly; a simple test is provided. This may save you plenty of time. You will need an oscilloscopeor other method of determining the existence of a 1 Mhz TTL level data stream.This test will allow you to determine if each board is capable of sending a CAN message on to the

    physical layer. You can view a TTL level waveform with an oscilloscope when program B is running.You do not need to have the other node working or connected. It is best if they are not connected.1) Connect the board you want to test to the PC COM port and start program B as described above.

    Press GO to run the B program. Program B Start will be displayed in the Serial I/O window.2) Measure P4.6 (transmit) with an oscilloscope. Figure 6 illustrates the position of these points. Youshould see a digital data signal of 4.5 volts p-p as shown in Figure 7.3) If the 82C250 is connected, a similar data signal of about 4 volts will be shown on P4.5 (receive).4) Note that if you stop the CPU with the STOP button, this signal does not stop. This demonstratesthe fact that the CAN controller does not need CPU intervention to operate.5) Check the physical CAN signals on Pins 6 and 7 of the 82C250. Each signal will be about 1.5 and2 volts p-p respectively. Remember these outputs/inputs are a differential pair, so in order to seethe true waveform, you will need to use a two channel scope set to ADD with one channel invertedfrom the other. This will give the same signal as Figure 6 but at about 2 volts p-p.6) Test the other board in the same fashion.FIGURE 6FIGURE 7Notes:1) If P4.6 and P4.5 are not connected to anything; P4.6 would sometimes not put any signal out. TheCPU had to be stopped, the dScope RESET activated and GO pressed again. The dScope reset isthe icon with the small red T pointing into a circle on the dScope toolbar or the RESET button onthe Toolbox window. Sometimes I had to reload the object file again. A signal would never appear on the Receive (P4.4) in this case.102) If I connected a resistor ( 2k or so) between P4.6 and P4.5, the appearance of a signal on theTransmit pin would be appear more consistently and a smaller signal would appear on the Receive

  • 8/8/2019 c167cr Can AP

    24/24

    pin P4.5.3) If the 82C250 was connected; the system became very stable. Only switching a relatively heavyload would cause the signals to disappear. A RESET and then a GO would restore operation.4) The 120 resistor (R1 in Figure 1) or the ground lead at SW1-8 do not need to be connected for this demonstration to work. Using the ground is a good idea.5) Program A does not put out any signal on its own.

    6) If the CAN network is intact and running properly; the signals are similar but fuzzier indicatingthe data is changing and the oscilloscope will not properly lock on to such a dynamic signal.For more information you may visit these Web sites:http://www.keil.com/can and www.keil.com/~market for CAN specific materialhttp://www.keil.com/~market - Technical Marketing page.http:/www.smi.siemens.com - for the Siemens page.http:/www.st.com - for the SGS Thomson page