Пример #1
0
static void board_peripheral_pin_select()
{
    // Disable I/O Lock (Peripheral pins can be mapped to PIO pins)
    PPSUnLock;
    
    // Map RP3 to UART1 Transmit (U1TX)
    PPSOutput(PPS_RP3, PPS_U1TX);
    // Map RP2 to UART1 Receive (U1RX)
    PPSInput(PPS_U1RX, PPS_RP2);

    // Map RP1 to UART2 Transmit (U2TX)
    PPSOutput(PPS_RP1, PPS_U2TX);
    // Map RP0 to UART2 Receive (U2RX)
    PPSInput(PPS_U2RX, PPS_RP0);

    // Map RP6 to SPI1 Data Input
    PPSInput(PPS_SDI1, PPS_RP6);
    // Map RP8 to SPI1 Clock Output
    PPSOutput(PPS_RP8, PPS_SCK1OUT);
    // Map RP9 to SPI1 Data Output
    PPSOutput(PPS_RP9, PPS_SDO1);

    // Map RP12 to External Interrupt 1 (IRQ1)
    PPSInput(PPS_INT1, PPS_RP12);

    // Enable I/O Lock
    PPSLock;
}
Пример #2
0
/**
 * Initializes all PIC functionality beyond the clock.
 *  * Maps all ECAN/UART pins
 *  * Assigns pins as input/output
 *  * Initializes the UART
 */
void Init(void)
{
    // And configure the Peripheral Pin Select pins:
    PPSUnLock;

#ifdef __dsPIC33FJ128MC802__
    // To enable ECAN1 pins: TX on 7, RX on 4
    PPSOutput(OUT_FN_PPS_C1TX, OUT_PIN_PPS_RP7);
    PPSInput(IN_FN_PPS_C1RX, IN_PIN_PPS_RP4);

    // To enable UART1 pins: TX on B11/P11, RX on B13/P13
    PPSOutput(OUT_FN_PPS_U1TX, OUT_PIN_PPS_RP11);
    PPSInput(IN_FN_PPS_U1RX, IN_PIN_PPS_RP13);
#elif __dsPIC33EP256MC502__
    // To enable ECAN1 pins: TX on 39, RX on 36
    PPSOutput(OUT_FN_PPS_C1TX, OUT_PIN_PPS_RP39);
    PPSInput(IN_FN_PPS_C1RX, IN_PIN_PPS_RP36);

    // To enable UART1 pins: TX on B11/P43, RX on B13/P45
    PPSOutput(OUT_FN_PPS_U1TX, OUT_PIN_PPS_RP43);
    PPSInput(IN_FN_PPS_U1RX, IN_PIN_PPS_RPI45);
#else
#error Invalid processor selected.
#endif

    PPSLock;

    // Initialize status LEDs for use.
    // A3 (output): Red LED, off by default.
    _TRISA3 = 0;
    _LATA3 = 0;
    // A4 (output): Amber LED, on by default.
    _TRISA4 = 0;
    _LATA4 = 1;

    _TRISB7 = 0; // Set ECAN1_TX pin to an output
    _TRISB4 = 1; // Set ECAN1_RX pin to an input;

    _TRISB11 = 0; // Set UART1_TX pin to an output
    _TRISB13 = 1; // Set UART1_RX pin to an input;

    // Set up UART1 for 57600 baud. There's no round() on the dsPICs, so we implement our own.
    double brg = (double) F_OSC / 2.0 / 16.0 / UART_BAUD - 1.0;
    if (brg - floor(brg) >= 0.5) {
        brg = ceil(brg);
    } else {
        brg = floor(brg);
    }
    Uart1Init((uint16_t)brg);

    // Initialize the Canaconda interface library callback functions
    commandFunction[COMMAND_FUNCTION_INDEX_OPEN] = CommandOpen;
    commandFunction[COMMAND_FUNCTION_INDEX_CLOSE] = CommandClose;
    commandFunction[COMMAND_FUNCTION_INDEX_SETUP] = CommandSetup;
    commandFunction[COMMAND_FUNCTION_INDEX_TRANSMIT] = CommandTransmit;
}
Пример #3
0
int InitPPS( void)
{
//   Setup Peripheral Pin Select for UART2, SPI1, SPI2,
//   IC1, OC1, OC3, OC4 on PIC24 GB110 and GA110 PIMs
    PPSUnLock;
    
// SPI1
    PPSOutput( PPS_RP15, PPS_SDO1);     // SDO1 =RP15 F8/pin 53
// SDO1 is the only pin we will use 

// SPI2
    PPSInput( PPS_SDI2,  PPS_RP26);     // SDI2 =RP26 G7/pin 11
    PPSOutput( PPS_RP22, PPS_SCK2OUT);  // SCK2 =RP21 G6/pin 10
    PPSOutput( PPS_RP21, PPS_SDO2);     // SDO2 =RP19 G8/pin 12

// UART
    PPSInput( PPS_U2RX,  PPS_RP10);     // U2RX =RP10 F4/pin 49
    PPSInput( PPS_U2CTS, PPS_RPI32);    // U2CTS=RP32 F12/pin40
    PPSOutput( PPS_RP17, PPS_U2TX);     // U2TX =RP17 F5/pin 50
    PPSOutput( PPS_RP31, PPS_U2RTS);    // U2RTS=RP31 F13pin 39

// IC
    PPSInput( PPS_IC1,   PPS_RP2);      // IC1  =RP2  D8/pin 68

// OC
    PPSOutput( PPS_RP19, PPS_OC1);      // OC1  =RP11 D0/pin 72
    PPSOutput( PPS_RP11, PPS_OC2);      // OC2  =RP24 D1/pin 76
    PPSOutput( PPS_RP24, PPS_OC4);      // OC4  =RP22 D3/pin 78

// GB110 PIM pin-remapping to accomodate additional USB pins
// GB110 shares usage of D2/pin 77 between SDI1 and OC3
//      pin 54 SDI1 is remapped to Explorer pin 77/D2 
// NOTE: we will use it only as OC3
//      pin 55 SCK1 is remapped to Explorer pin 25/B0 
// NOTE: pin 55 is input only, connecting it to SCK1
//          restricts usage to "slave mode" only 
//      pin 56 RG3  is remapped to Explorer pin 89/G1
//      pin 57 RG2  is remapped to Explorer pin 90/G0

#ifdef __PIC24FJ256GB110__
    PPSOutput( PPS_RP23, PPS_OC3OUT);   // OC3=RP23 D2/pin 77 
#endif

    // Done, lock the PPS configuration 
    PPSLock;
            
    return 0;
} // InitPPS
Пример #4
0
inline void Pin_Setup(void)
{
    TRISBbits.TRISB11 = 1;

    /*Set RB11 as external interrupt INT1*/
    PPSInput(PPS_INT1, PPS_RP11);
}
Пример #5
0
int main(void) {
    char buffer[80];
    unsigned int pb_clock;
    float actual_baud;
    const int baud = 500000; // max baud rate using arduino interface 

    pb_clock = SYSTEMConfigPerformance(SYS_CLK); // if sys_clock > 100MHz, pb_clock = sys_clock/2 else pb_clock = sys_clock

    PORTSetPinsDigitalOut(IOPORT_E, BIT_4); // led

    // setup UART
    PPSUnLock;
    PPSInput(1,U1RX,RPF4); // Rx - F4 (pin 49) 5V tolerent
    PPSOutput(2,RPF5,U1TX); // Tx - F5 (pin 50) 5V tolerent
    PPSLock;
    
    actual_baud = U1_init(pb_clock, baud);

    sprintf(buffer, "SYSCLK: %d\r\n", SYS_CLK);
    U1_write(buffer);
    sprintf(buffer, "PBCLK: %d\r\n", pb_clock);
    U1_write(buffer);
    sprintf(buffer, "U1BRG: %d\r\n", U1BRG);
    U1_write(buffer);
    sprintf(buffer, "target baud: %d\r\n", baud);
    U1_write(buffer);
    sprintf(buffer, "actual baud: %f\r\n", actual_baud);
    U1_write(buffer);

    timer1_init();

    timer_delay_test();
}
Пример #6
0
void SERIAL_Init(void) {
    transmitBuffer = (struct CircBuffer*) &outgoingUart; //set up buffer for receive
    newCircBuffer(transmitBuffer);

    receiveBuffer = (struct CircBuffer*) &incomingUart; //set up buffer for transmit
    newCircBuffer(receiveBuffer);

    UARTConfigure(UART1, 0x00);
    UARTSetDataRate(UART1, F_PB, 115200);
    UARTSetFifoMode(UART1, UART_INTERRUPT_ON_RX_NOT_EMPTY | UART_INTERRUPT_ON_TX_BUFFER_EMPTY);

    INTSetVectorPriority(INT_UART_1_VECTOR, INT_PRIORITY_LEVEL_4); //set the interrupt priority

    //RPC5R = 1;
    PPSOutput(1, RPC5, U1TX);
    PORTSetPinsDigitalIn(IOPORT_C, BIT_3);
    //U1RXRbits.U1RXR = 0b111;
    PPSInput(3, U1RX, RPC3);

    UARTEnable(UART1, UART_ENABLE_FLAGS(UART_PERIPHERAL | UART_TX | UART_RX));
    INTEnable(INT_U1RX, INT_ENABLED);
    //INTSetFlag(INT_U1RX);
    //INTEnable(INT_U1TX, INT_ENABLED);
    //PutChar('z');
}
Пример #7
0
// Initialization.
void hc05_init(void) {
    // PPS UART2
    PPSInput (PPS_U2RX, PPS_RP6);  // U2RX = RP6
    PPSOutput(PPS_RP15, PPS_U2TX); // U2TX = RP15

    // UART2 init
    U2BRG  = 34;     // Baud Rate = 115200 (Fcy = 16 MHz)
    U2MODE = 0x8008; // UART is enabled, BRGH = 1
    U2STA  = 0x0400; // Transmit enabled
}
Пример #8
0
static void map_peripherals()
{
	/* unlock PPS sequence */
	SYSKEY = 0x0;			/* make sure it is locked */
	SYSKEY = 0xAA996655;		/* Key 1 */
	SYSKEY = 0x556699AA;		/* Key 2 */
	CFGCONbits.IOLOCK=0;		/* now it is unlocked */

	/* map SPI and PWM pins */
	PPSInput(4, SS2, RPB14);	/* CS */
	PPSInput(3, SDI2, RPB13);	/* MOSI */
	PPSOutput(2, RPB11, SDO2);	/* MISO */
	PPSOutput(1, RPA0, OC1);	/* PWM 0 */
	PPSOutput(2, RPA1, OC2);	/* PWM 1 */
	PPSOutput(4, RPB0, OC3);	/* PWM 2 */

	/* lock PPS sequence */
	CFGCONbits.IOLOCK=1;		/* now it is locked */
	SYSKEY = 0x0;			/* lock register access */
}
Пример #9
0
int main(void)
{
    initPic32();

    PORTSetPinsDigitalIn(IOPORT_A, BIT_0);
    PORTSetPinsDigitalIn(IOPORT_A, BIT_1);
    PORTSetPinsDigitalIn(IOPORT_B, BIT_14);

    PPSInput(1, SS1, RPA0);
    PPSInput(2, SDI1, RPA1);

#ifndef NO_SDO
    PPSOutput(3, RPA2, SDO1);
#endif

    SpiChnOpen(1, SPI_OPEN_MODE8|SPI_OPEN_SLVEN|SPI_OPEN_SSEN
#ifdef NO_SDO
               |SPI_OPEN_DISSDO
#endif
               , 2);

    init();

    uint8_t lastByteReceived = 0;
    uint8_t cmd[8];
    uint8_t length=0;
    uint8_t toRead = 1;
    while(1) {
        if(SpiChnTxBuffEmpty(1))
            SpiChnPutC(1, lastByteReceived);
        lastByteReceived = 0;

        while(!SpiChnDataRdy(1))
            loop();
        uint8_t byte = SpiChnGetC(1);
        cmd[length++] = byte;
        toRead--;
        if(toRead==0)
            toRead = commandReceived(cmd, length);
    }
}
Пример #10
0
/**
 * Initialize pin mappings and set pins as digital.
 */
void initPins(void)
{
    // And configure the Peripheral Pin Select pins:
    PPSUnLock;
    // To enable ECAN1 pins: TX on 7, RX on 4
    PPSOutput(OUT_FN_PPS_C1TX, OUT_PIN_PPS_RP39);
    PPSInput(PPS_C1RX, PPS_RP20);

    // To enable UART2 pins: TX on 11, RX on 13
    PPSOutput(OUT_FN_PPS_U2TX, OUT_PIN_PPS_RP43);
    PPSInput(PPS_U2RX, PPS_RPI45);
    
    // enable the SPI stuff: clock, in, out
    PPSOutput(OUT_FN_PPS_SCK2, OUT_PIN_PPS_RP41);
    PPSOutput(OUT_FN_PPS_SDO2, OUT_PIN_PPS_RP40);
    PPSInput(PPS_SDI2, PPS_RP42);
    PPSLock;

    // Disable A/D functions on pins
    ANSELA = 0;
    ANSELB = 0;
}
Пример #11
0
inline void INT2_Setup(void)    //Setup External Interrupt 0
{
    _INT2IF = 0;

    //For INT2EP:  0=Positive Edge, 1=Negative Edge
    _INT2EP = 0;

    TRISBbits.TRISB6 = IN;
    PPSInput(PPS_INT2, PPS_RP6);

    _INT2IE = 1;                //Turn on INT2 Interrupt

    return;
}
Пример #12
0
inline void INT1_Setup(void)    //Setup External Interrupt 1
{
    _INT1IF = 0;

    //For INT1EP:  0=Positive Edge, 1=Negative Edge
    _INT1EP = 0;

    TRISBbits.TRISB5 = IN;
    PPSInput(PPS_INT1, PPS_RP5);

    _INT1IE = 1;                //Turn on INT1 Interrupt

    return;
}
Пример #13
0
inline void INT2_Setup(void)    //Setup External Interrupt 0
{
    _INT2IF = 0;

    //For INT2EP:  0=Positive Edge, 1=Negative Edge
    _INT2EP = 0;

    TRISBbits.TRISB6 = IN;
    PPSInput(IN_FN_PPS_INT2, IN_PIN_PPS_RP6);

    _INT2IE = 0;                //Turn on INT2 Interrupt

    printf("INT2 Setup\r\n");
    return;
}
Пример #14
0
inline void INT1_Setup(void)    //Setup External Interrupt 1
{
    _INT1IF = 0;

    //For INT1EP:  0=Positive Edge, 1=Negative Edge
    _INT1EP = 0;

    TRISBbits.TRISB5 = IN;
    PPSInput(IN_FN_PPS_INT1, IN_PIN_PPS_RP5);

    _INT1IE = 0;                //Turn on INT1 Interrupt

    printf("INT1 Setup\r\n");
    return;
}
Пример #15
0
//===================== Main ======================= //
void main(void) {
    SYSTEMConfig( SYS_FREQ,  SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);

    ANSELA = 0; ANSELB = 0; CM1CON = 0; CM2CON = 0;

    PT_setup();
    INTEnableSystemMultiVectoredInt();

    
    // initialize the threads
    PT_INIT(&pt_blink);
    PT_INIT(&pt_capture);
    
    // initialize the display
    tft_init_hw();
    tft_begin();
    tft_fillScreen(ILI9340_BLACK);

    tft_setRotation(0); //240x320 vertical display

    // initialize the comparator
    CMP1Open(CMP_ENABLE | CMP_OUTPUT_ENABLE | CMP1_NEG_INPUT_IVREF);
    
    // initialize the timer2
    OpenTimer2(T2_ON | T2_SOURCE_INT | T2_PS_1_64, 0xffffffff);

    // initialize the input capture, uses timer2
    OpenCapture1( IC_EVERY_RISE_EDGE | IC_FEDGE_RISE | IC_INT_1CAPTURE | IC_TIMER2_SRC | IC_ON);
    ConfigIntCapture1(IC_INT_ON | IC_INT_PRIOR_3 | IC_INT_SUB_PRIOR_3 );
    INTClearFlag(INT_IC1);

    // initialize the input/output I/O
    mPORTBSetPinsDigitalOut(BIT_3);
    mPORTBClearBits(BIT_3);
    PPSOutput(4, RPB9, C1OUT);		//set up output of comparator for debugging
    PPSInput(3, IC1, RPB13);		//Either Pin 6 or Pin 24 idk
   
    //round-robin scheduler for threads
    while(1) {
	PT_SCHEDULE(protothread_blink(&pt_blink));
	PT_SCHEDULE(protothread_capture(&pt_capture));
    }
    
} //main
Пример #16
0
void Setup_SPI1()
{
     OpenSPI1(
            (
            ENABLE_SCK_PIN  &//
       //     FIFO_BUFFER_DISABLE      &
            ENABLE_SDO_PIN          &//
            SPI_MODE16_OFF          &//
            SPI_SMP_ON            &//
            SPI_CKE_ON             &//
            SLAVE_ENABLE_OFF        &//
            CLK_POL_ACTIVE_HIGH     &//
            MASTER_ENABLE_ON        &//
            SEC_PRESCAL_4_1         &//
            PRI_PRESCAL_4_1//
            )
            ,
            (
            FRAME_ENABLE_OFF        &   //NOT USED
            FRAME_SYNC_OUTPUT       &   //NOT USED
            FRAME_POL_ACTIVE_HIGH   &   //NOT USED
            FRAME_SYNC_EDGE_PRECEDE   //NOT USED

            )
            ,
            (
            SPI_ENABLE          &//
            SPI_IDLE_CON        &//
            SPI_RX_OVFLOW_CLR   //
            )
            );

    ConfigIntSPI1(SPI_INT_EN & SPI_INT_PRI_5);

    PPSOutput(OUT_FN_PPS_SCK1, OUT_PIN_PPS_RP8);//CLK
    PPSOutput(OUT_FN_PPS_SDO1, OUT_PIN_PPS_RP7);//MOSI
    PPSInput(IN_FN_PPS_SDI1, IN_PIN_PPS_RP6);   //MISO

    TRISBbits.TRISB8 = 0;//Clk
    TRISBbits.TRISB7 = 0;//MOSI
    TRISBbits.TRISB6 = 1;//MISO
    printf("SPI1 Setup\r\n");
    return;
}
Пример #17
0
void HilNodeInit(void)
{
    // Set a unique node ID for this node.
    nodeId = CAN_NODE_HIL;

	// And configure the Peripheral Pin Select pins:
	PPSUnLock;
	// To enable ECAN1 pins: TX on 7, RX on 4
	PPSOutput(OUT_FN_PPS_C1TX, OUT_PIN_PPS_RP7);
	PPSInput(PPS_C1RX, PPS_RP4);

	// To enable UART1 pins: TX on 11, RX on 13
	PPSOutput(OUT_FN_PPS_U1TX, OUT_PIN_PPS_RP11);
	PPSInput(PPS_U1RX, PPS_RP13);

	// Configure SPI1 so that:
	//  * (input) SPI1.SDI = B8
	PPSInput(PPS_SDI1, PPS_RP10);
	//  * SPI1.SCK is output on B9
	PPSOutput(OUT_FN_PPS_SCK1, OUT_PIN_PPS_RP9);
	//  * (output) SPI1.SDO = B10
	PPSOutput(OUT_FN_PPS_SDO1, OUT_PIN_PPS_RP8);
	PPSLock;

    // Enable pin A4, the amber LED on the CAN node, as an output. We'll blink this at 1Hz. It'll
	// stay lit when in HIL mode with it turning off whenever packets are received.
    _TRISA4 = 0;

    // Initialize communications for HIL.
    HilInit();

	// Set Timer4 to be a 4Hz timer. Used for blinking the amber status LED.
	Timer4Init(HilNodeBlink, 39062);

    // Set up Timer2 for a 100Hz timer. This triggers CAN message transmission at the same frequency
	// that the sensors actually do onboard the boat.
    Timer2Init(HilNodeTimer100Hz, 1562);

    // Initialize ECAN1
    Ecan1Init();

	// Set a schedule for outgoing CAN messages
    // Transmit the rudder angle at 10Hz
    if (!AddMessageRepeating(&sched, SCHED_ID_RUDDER_ANGLE, 10)) {
		FATAL_ERROR();
    }

    // Transmit the rudder status at 10Hz
    if (!AddMessageRepeating(&sched, SCHED_ID_RUDDER_LIMITS, 10)) {
		FATAL_ERROR();
    }

    // Transmit the throttle status at 100Hz
    if (!AddMessageRepeating(&sched, SCHED_ID_THROTTLE_STATUS, 10)) {
		FATAL_ERROR();
    }

    // Transmit the RC status at 2Hz
    if (!AddMessageRepeating(&sched, SCHED_ID_RC_STATUS, 2)) {
		FATAL_ERROR();
    }

    // Transmit latitude/longitude at 5Hz
    if (!AddMessageRepeating(&sched, SCHED_ID_LAT_LON, 5)) {
		FATAL_ERROR();
    }

    // Transmit heading & speed at 5Hz
    if (!AddMessageRepeating(&sched, SCHED_ID_COG_SOG, 5)) {
		FATAL_ERROR();
    }

    // Transmit heading & speed at 5Hz
    if (!AddMessageRepeating(&sched, SCHED_ID_GPS_FIX, 5)) {
		FATAL_ERROR();
    }
}
Пример #18
0
UINT16 SetupUART(void)
{

    PPSOutput(OUT_FN_PPS_U1TX, OUT_PIN_PPS_RP37);
    PPSInput(PPS_U1RX, PPS_RP20);


 OpenUART1(UART_EN &
            UART_IDLE_CON &
            UART_IrDA_DISABLE &
            UART_MODE_SIMPLEX &
            UART_UEN_00 &
            UART_EN_WAKE &
            UART_DIS_LOOPBACK &
            UART_DIS_ABAUD &
            UART_UXRX_IDLE_ONE &
            UART_BRGH_SIXTEEN &
            UART_NO_PAR_8BIT &
            UART_1STOPBIT
            ,
            UART_INT_TX_BUF_EMPTY &
            UART_SYNC_BREAK_DISABLED &
            UART_TX_ENABLE &
            UART_INT_RX_CHAR &
            UART_ADR_DETECT_DIS
            ,
            23
            //BAUD = 9600
            );
 
            U1STAbits.UTXINV = 0;           //make TX active low
            //U1STAbits.URXISEL = 0x00;       //force interrupt on every 8 bits recieved

            ConfigIntUART1(UART_RX_INT_EN &
                    UART_RX_INT_PR4 &
                    UART_TX_INT_DIS
                    );

/*This is a copy of UART setup working for TX
  OpenUART1(UART_EN &
            UART_IDLE_CON &
            UART_IrDA_DISABLE &
            UART_MODE_SIMPLEX &
            UART_UEN_00 &
            UART_EN_WAKE &
            UART_DIS_LOOPBACK &
            UART_DIS_ABAUD &
            UART_UXRX_IDLE_ZERO &
            UART_BRGH_SIXTEEN &
            UART_NO_PAR_8BIT &
            UART_1STOPBIT
            ,
            UART_INT_TX_BUF_EMPTY &
            UART_SYNC_BREAK_DISABLED &
            UART_TX_ENABLE &
            UART_INT_RX_BUF_FUL &
            UART_ADR_DETECT_DIS
            ,
            23
            //BAUD = 9600
            );

            U1STAbits.UTXINV = 0;
            */

    return 0;   //return success
}
Пример #19
0
void initIO()
{
    ANSELB = 0x3400; //AN0 - AN15

    ANSELGbits.ANSG6 = 0; //AN16
    ANSELGbits.ANSG7 = 0; //AN17
    ANSELGbits.ANSG8 = 0; //AN18
    ANSELGbits.ANSG9 = 0; //AN19


    ANSELEbits.ANSE2 = 0; //AN20
    ANSELEbits.ANSE4 = 0; //AN21
    ANSELEbits.ANSE5 = 0; //AN22
    ANSELEbits.ANSE6 = 0; //AN23
    ANSELEbits.ANSE7 = 0; //AN27

    ANSELDbits.ANSD1 = 0; //AN24
    ANSELDbits.ANSD2 = 0; //AN25
    ANSELDbits.ANSD3 = 0; //AN26


    //Configure analog pins IO
    TRISBbits.TRISB0 = 0;
    TRISBbits.TRISB1 = 1;
    TRISBbits.TRISB2 = 1;
    TRISBbits.TRISB3 = 0;
    TRISBbits.TRISB4 = 0;
    TRISBbits.TRISB5 = 0;
    TRISBbits.TRISB8 = 1;
    TRISBbits.TRISB9 = 0;
    TRISBbits.TRISB10 = 1;
    TRISBbits.TRISB11 = 0;
    TRISBbits.TRISB12 = 1;
    TRISBbits.TRISB13 = 1;
    TRISBbits.TRISB14 = 0;
    TRISBbits.TRISB15 = 0;


    TRISEbits.TRISE0 = 0;
    TRISEbits.TRISE1 = 0;
    TRISEbits.TRISE2 = 0;
    TRISEbits.TRISE3 = 0;
    TRISEbits.TRISE4 = 0;
    TRISEbits.TRISE5 = 0;
    TRISEbits.TRISE6 = 0;
    TRISEbits.TRISE7 = 0;


    TRISD = 0x001C;

    TRISGbits.TRISG6 = 0;
    TRISGbits.TRISG7 = 1;   //pin RG7 is configured as SPI input
    TRISGbits.TRISG8 = 0;
    TRISGbits.TRISG9 = 0;

    TRISC = 0x0000; //RC1-RC4 extra pins

/* ********************* Assign UART 2 signals onto pins using PPS *********************************** */
    PPSInput(4, U4RX, RPB2);  //Assign U2RX to pin RPD8
    PPSOutput(3, RPB0, U4TX);   //Assign U2TX to pin RPD9

/* ********************* Assign Encoders signals onto pins using PPS ************************************/
    PPSInput(3, T4CK, RPD4);  //Assign T4CK to pin RPD4
    PPSInput(2, T5CK, RPB1);  //Assign T5CK to pin RPD11

/* ********************* Assign SDI/O 2 signals onto pins using PPS *********************************** */
    PPSInput(2, SDI2, RPG7);  //Assign SDI2 to pin RPG7
    PPSOutput(1, RPG8, SDO2);   //Assign SDO2 to pin RPG8

/* ********************* Assign OC1 & OC2************************************************************** */
    PPSOutput(4, RPD1, OC1);
    PPSOutput(4, RPD5, OC2);

    //mappingMode = 1;
    //fastMode = 0;
}
Пример #20
0
int main(void)
#endif
{   
    BYTE i, j;
    BYTE TxSynCount = 0;
    BOOL bReceivedMessage = FALSE;
    _U16  m;

    
     #define BAUDRG 77
    /*******************************************************************/
    // Initialize the system
    /*******************************************************************/

    ANCON0 = 0XFF;     /*desactiva entradas analogicas*/
    ANCON1 = 0XFF;     /*desactiva entradas analogicas*/

    PPSUnLock();
    PPSOutput(PPS_RP10, PPS_TX2CK2);    // TX2 RP17/RC6
    PPSInput(PPS_RX2DT2, PPS_RP9);     // RX2 RP18/RC7

    PPSOutput(PPS_RP23, PPS_SDO2);    // SDO2 RP23/RD6
    PPSInput(PPS_SDI2, PPS_RP24);     // SDI2 RP24/RD7
    PPSOutput(PPS_RP22, PPS_SCK2);    // SCK2 RP22/RD5

    PPSLock();

     System_PeripheralPinSelect( ExternalInterrupt3, 19);  /*external interrupt 3 B3*/

     BoardInit();
     ConsoleInit();

     Open2USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG);
     baud2USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF);

     Gpios_PinDirection(GPIOS_PORTD, 7, GPIOS_INPUT);  /*pin C0 como salida para SDI*/
     Gpios_PinDirection(GPIOS_PORTD, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/
     Gpios_PinDirection(GPIOS_PORTD, 5, GPIOS_OUTPUT); /*pin C2 como salida para SCK*/

     Spi_Init(SPI_PORT1, SPI_64DIV); /*Inicializamos SPI2*/
     Spi_Init(SPI_PORT2, SPI_64DIV); /*Inicializamos SPI2*/
     //Spi_SetMode(SPI_PORT1, 1);
     //Spi_SetMode(SPI_PORT1, 1);


    LED_1 = 1;
    LED_2 = 1;

    Read_MAC_Address();

    LED_1 = 0;
    LED_2 = 0;

                    ConsolePutROMString((ROM char *)"\r\n<MAC Addr:");
                 
                    PrintChar(myLongAddress[3]);
                    PrintChar(myLongAddress[2]);
                    PrintChar(myLongAddress[1]);
                    PrintChar(myLongAddress[0]);

                    ConsolePutROMString((ROM char *)"\r>");

        
    Printf("\r\nStarting Testing Interface for MiWi(TM) PRO Stack ...");
    #if defined(MRF24J40)
    Printf("\r\n     RF Transceiver: MRF24J40");
    #elif defined(MRF49XA)
    Printf("\r\n     RF Transceiver: MRF49XA");
    #elif defined(MRF89XA)
    Printf("\r\n     RF Transceiver: MRF89XA");
    #endif
    Printf("\r\n   Demo Instruction:");
    Printf("\r\n                     Press Enter to bring up the menu.");
    Printf("\r\n                     Type in hyper terminal to choose");
    Printf("\r\n                     menu item. ");
    Printf("\r\n\r\n");
   
    /*******************************************************************/
    // Following block display demo information on LCD of Explore 16 or 
    // PIC18 Explorer demo board.
    /*******************************************************************/
    #if defined(MRF49XA)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF49XA", 0, TRUE); 
    #elif defined(MRF24J40)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF24J40", 0, TRUE);
    #elif defined(MRF89XA)
        LCDDisplay((char *)"MiWi PRO Test Interface MRF89XA", 0, TRUE); 
    #endif
    
    //if( (PUSH_BUTTON_1 == 0) || ( MiApp_ProtocolInit(TRUE) == FALSE ) )
    if (PUSH_BUTTON_1 == 1)
    {  

        MiApp_ProtocolInit(FALSE);


        LED_1 = 0;
        LED_2 = 0;

        #ifdef ENABLE_ACTIVE_SCAN
        
            myChannel = 0xFF;
            ConsolePutROMString((ROM char *)"\r\nStarting Active Scan...");
            
            LCDDisplay((char *)"Active Scanning", 0, FALSE);
    
            /*******************************************************************/
            // Function MiApp_SearchConnection will return the number of 
            // existing connections in all channels. It will help to decide 
            // which channel to operate on and which connection to add.
            // The return value is the number of connections. The connection 
            //     data are stored in global variable ActiveScanResults. 
            //     Maximum active scan result is defined as 
            //     ACTIVE_SCAN_RESULT_SIZE
            // The first parameter is the scan duration, which has the same 
            //     definition in Energy Scan. 10 is roughly 1 second. 9 is a 
            //     half second and 11 is 2 seconds. Maximum scan duration is 14, 
            //     or roughly 16 seconds.
            // The second parameter is the channel map. Bit 0 of the 
            //     double word parameter represents channel 0. For the 2.4GHz 
            //     frequency band, all possible channels are channel 11 to 
            //     channel 26. As the result, the bit map is 0x07FFF800. Stack 
            //     will filter out all invalid channels, so the application 
            //     only needs to pay attention to the channels that are not 
            //     preferred.
            /*******************************************************************/
            i = MiApp_SearchConnection(10, 0x02000000);
            
            if( i > 0 )
            {
                // now print out the scan result.
                Printf("\r\nActive Scan Results: \r\n");
                for(j = 0; j < i; j++)
                {
                    Printf("Channel: ");
                    PrintDec(ActiveScanResults[j].Channel );
                    Printf("   RSSI: ");
                    PrintChar(ActiveScanResults[j].RSSIValue);
                    Printf("\r\n");
                    myChannel = ActiveScanResults[j].Channel;
                    Printf("PeerInfo: ");
                    PrintChar( ActiveScanResults[j].PeerInfo[0]);
                }
            }
        #endif

    

        /*******************************************************************/
        // Function MiApp_ConnectionMode sets the connection mode for the 
        // protocol stack. Possible connection modes are:
        //  - ENABLE_ALL_CONN       accept all connection request
        //  - ENABLE_PREV_CONN      accept only known device to connect
        //  - ENABL_ACTIVE_SCAN_RSP do not accept connection request, but 
        //                          allow response to active scan
        //  - DISABLE_ALL_CONN      disable all connection request, including
        //                          active scan request
        /*******************************************************************/
        MiApp_ConnectionMode(ENABLE_ALL_CONN);
    
    
        if( i > 0 )
        {
            /*******************************************************************/
            // Function MiApp_EstablishConnection try to establish a new 
            // connection with peer device. 
            // The first parameter is the index to the active scan result, which 
            //      is acquired by discovery process (active scan). If the value
            //      of the index is 0xFF, try to establish a connection with any 
            //      peer.
            // The second parameter is the mode to establish connection, either 
            //      direct or indirect. Direct mode means connection within the 
            //      radio range; Indirect mode means connection may or may not 
            //      in the radio range. 
            /*******************************************************************/
            if( MiApp_EstablishConnection(0, CONN_MODE_DIRECT) == 0xFF )
            {
                Printf("\r\nJoin Fail");
            }
        }    
        else
        {
            /*******************************************************************/
            // Function MiApp_StartConnection tries to start a new network 
            //
            // The first parameter is the mode of start connection. There are 
            // two valid connection modes:
            //   - START_CONN_DIRECT        start the connection on current 
            //                              channel
            //   - START_CONN_ENERGY_SCN    perform an energy scan first, 
            //                              before starting the connection on 
            //                              the channel with least noise
            //   - START_CONN_CS_SCN        perform a carrier sense scan 
            //                              first, before starting the 
            //                              connection on the channel with 
            //                              least carrier sense noise. Not 
            //                              supported on currrent radios
            //
            // The second parameter is the scan duration, which has the same 
            //     definition in Energy Scan. 10 is roughly 1 second. 9 is a 
            //     half second and 11 is 2 seconds. Maximum scan duration is 
            //     14, or roughly 16 seconds.
            //
            // The third parameter is the channel map. Bit 0 of the 
            //     double word parameter represents channel 0. For the 2.4GHz 
            //     frequency band, all possible channels are channel 11 to 
            //     channel 26. As the result, the bit map is 0x07FFF800. Stack 
            //     will filter out all invalid channels, so the application 
            //     only needs to pay attention to the channels that are not 
            //     preferred.
            /*******************************************************************/
            #ifdef ENABLE_ED_SCAN
                //LCDDisplay((char *)"Active Scanning Energy Scanning", 0, FALSE);
                ConsolePutROMString((ROM char *)"\r\nActive Scanning Energy Scanning");
                MiApp_StartConnection(START_CONN_ENERGY_SCN, 10, 0x02000000);
            #endif
        }
        
        // Turn on LED 1 to indicate ready to accept new connections
        LED_1 = 1;
    }
    else
    {
        //LCDDisplay((char *)" Network Freezer    ENABLED", 0, TRUE);
        Printf("\r\nNetwork Freezer Feature is enabled. There will be no hand-shake process.\r\n");
        LED_1 = 1;
        DumpConnection(0xFF);
    }
                   
    LCDDisplay((char *)"Start Connection on Channel %d", currentChannel, TRUE);
    LCDDisplay((char *)"Testing Menu on  Hyper Terminal", 0, FALSE);

    while(1)
    {
        /*******************************************************************/
        // Function MiApp_MessageAvailable will return a boolean to indicate 
        // if a message for application layer has been received by the 
        // transceiver. If a message has been received, all information will 
        // be stored in the rxMessage, structure of RECEIVED_MESSAGE.
        /*******************************************************************/
        if( MiApp_MessageAvailable() )
        {
            /*******************************************************************/
            // If a packet has been received, following code prints out some of
            // the information available in rxFrame.
            /*******************************************************************/
            if( rxMessage.flags.bits.secEn )
            {
                ConsolePutROMString((ROM char *)"Secured ");
            }

            if( rxMessage.flags.bits.broadcast )
            {
                ConsolePutROMString((ROM char *)"Broadcast Packet with RSSI ");
            }
            else
            {
                ConsolePutROMString((ROM char *)"Unicast Packet with RSSI ");
            }
            PrintChar(rxMessage.PacketRSSI);
            if( rxMessage.flags.bits.srcPrsnt )
            {
                ConsolePutROMString((ROM char *)" from ");
                if( rxMessage.flags.bits.altSrcAddr )
                {
                    PrintChar(rxMessage.SourceAddress[1]);
                    PrintChar(rxMessage.SourceAddress[0]);
                }
                else
                {    
                    for(i = 0; i < MY_ADDRESS_LENGTH; i++)
                    {
                        PrintChar(rxMessage.SourceAddress[MY_ADDRESS_LENGTH-1-i]);
                    }
                }    
            }

            ConsolePutROMString((ROM char *)": ");
            
            
            for(i = 0; i < rxMessage.PayloadSize; i++)
            {
                ConsolePut(rxMessage.Payload[i]);
            }
            
            // Toggle LED2 to indicate receiving a packet.
            LED_2 ^= 1;
            
            /*******************************************************************/
            // Function MiApp_DiscardMessage is used to release the current 
            // received message. After calling this function, the stack can 
            // start to process the next received message.
            /*******************************************************************/          
            MiApp_DiscardMessage();
            
            bReceivedMessage = TRUE;
            
            /*******************************************************************/
            // Following block update the total received and transmitted messages
            // on the LCD of the demo board. 
            /*******************************************************************/
            LCDTRXCount(TxNum, ++RxNum);
        }
        else
        {
         ++m;

         if(m > 8000)
         {
             m=0;
             //LED_1 ^= 1;
             
                MiApp_FlushTx();
    	        MiApp_WriteData('H');
    	        MiApp_WriteData('o');
    	        MiApp_WriteData('l');
    	        MiApp_WriteData('a');
                MiApp_WriteData('a');
                MiApp_WriteData('a');
    	        MiApp_WriteData(0x0D);
    	        MiApp_WriteData(0x0A);
               MiApp_BroadcastPacket(FALSE);

         }



            if ( ConsoleIsGetReady() )
            {
                //ProcessMenu();
            } 
        }
    }
}
Пример #21
0
void main(void)
{
     #define BAUDRG 77

    BYTE SecNum = 0;

   BOOL Tx_Success = FALSE;
   BYTE Tx_Trials = 0, scanresult = 0;
    /*******************************************************************/
    // Initialize the system
    /*******************************************************************/

    ANCON0 = 0XFF;     /*desactiva entradas analogicas*/
    ANCON1 = 0XFF;     /*desactiva entradas analogicas*/



    PPSUnLock();

    PPSOutput(PPS_RP10, PPS_TX2CK2);    // TX2 RP17/RC6     icsp
    PPSInput(PPS_RX2DT2, PPS_RP9);     // RX2 RP18/RC7

    PPSOutput(PPS_RP23, PPS_SDO2);    // SDO2 RP23/RD6
    PPSInput(PPS_SDI2, PPS_RP24);     // SDI2 RP24/RD7
    PPSOutput(PPS_RP22, PPS_SCK2);    // SCK2 RP22/RD5

    PPSLock();

     System_PeripheralPinSelect( ExternalInterrupt3, 19);  /*external interrupt 3 B3*/

     BoardInit();
     ConsoleInit();

     Gpios_PinDirection(GPIOS_PORTC, 7, GPIOS_INPUT);  /*pin C0 como salida para SDI*/
     Gpios_PinDirection(GPIOS_PORTC, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/
     
     //Gpios_PinDirection(GPIOS_PORTD, 4, GPIOS_OUTPUT);  /*pin D4 como salida */

     Open1USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG);
     baud1USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF);


     Open2USART(USART_TX_INT_OFF & USART_RX_INT_OFF & USART_EIGHT_BIT & USART_ASYNCH_MODE & USART_ADDEN_OFF, BAUDRG);
     baud2USART(BAUD_IDLE_TX_PIN_STATE_HIGH & BAUD_IDLE_RX_PIN_STATE_HIGH & BAUD_AUTO_OFF & BAUD_WAKEUP_OFF & BAUD_16_BIT_RATE & USART_RX_INT_OFF);


     OpenTimer1( TIMER_INT_OFF &T1_16BIT_RW &T1_SOURCE_FOSC_4 & T1_PS_1_8 &T1_OSC1EN_OFF &T1_SYNC_EXT_OFF, TIMER_GATE_OFF  & TIMER_GATE_INT_OFF);



     Gpios_PinDirection(GPIOS_PORTD, 7, GPIOS_INPUT);  /*pin C0 como salida para SDI*/
     Gpios_PinDirection(GPIOS_PORTD, 6, GPIOS_OUTPUT); /*pin C1 como salida para SDO*/
     Gpios_PinDirection(GPIOS_PORTD, 5, GPIOS_OUTPUT); /*pin C2 como salida para SCK*/

     Spi_Init(SPI_PORT1, SPI_64DIV); /*Inicializamos SPI2*/
     Spi_Init(SPI_PORT2, SPI_64DIV); /*Inicializamos SPI2*/

     //Adc_Init(ADC_10BITS);

     LED_1 = 1;
     LED_2 = 0;
     //RLY_1 = 0;
     RLY_2 = 0;

     ON_RADIO = 1;
     ON_MAC = 1;
     ON_TEMP = 1;
     
     StartWirelessConnection();
     
     
     
     //myDevicesRequiredStatus[0] = 0x55;
     
     
     EEPROMRead(&myDevicesRequiredStatus, 0, 1);
     
     if(myDevicesRequiredStatus[0] == 0x55)
     {
         RLY_1 = 1;
         EEPROMCHG = 1;
         ConsolePutROMString((ROM char *)"RELAY ON ");
     }
     
     if(myDevicesRequiredStatus[0] == 0xAA)
     {
         RLY_1 = 0;
         EEPROMCHG = 0;
         ConsolePutROMString((ROM char *)"RELAY OFF ");
     }
     
     
     
     
     

     for(j=0;j<10;j++)
     {
         DelayMs(50);

         LED_1 ^= 1;
         LED_2 ^= 1;
     }
     
     

     LED_1 = 0;
     LED_2 = 0;
     //RLY_1 = 0;
     RLY_2 = 0;
     
    
     
     TickScaler = 4;
     EndDevStateMachine =0;



/*
                                

                                while(!Tx_Success)
                                {
                                    if(myChannel < 8)
                                        scanresult = MiApp_SearchConnection(10, (0x00000001 << myChannel));
                                    else if(myChannel < 16)
                    				    scanresult = MiApp_SearchConnection(10, (0x00000100 << (myChannel-8)));
                                    else if(myChannel < 24)
                    				    scanresult = MiApp_SearchConnection(10, (0x00010000 << (myChannel-16)));
                                    else
                    				    scanresult = MiApp_SearchConnection(10, (0x01000000 << (myChannel-24)));
                                    if(scanresult == 0)
                                    {
                                        Tx_Trials++;
                                        if(Tx_Trials > 2) break;

                                    }
                                    else Tx_Success = TRUE;

                                }
                                if(Tx_Success)
                                {
                                    ConsolePutROMString((ROM char *)"RADIO OK ");
                                }
                                else
                                {
                                    ConsolePutROMString((ROM char *)"RADIO FAIL ");
                                }

*/


     //.VBGOE = 0;
     //ANCON1bits.VBGEN = 1;		// Enable Band gap reference voltage
     //DelayMs(10);
     //VBGResult = Adc_u16Read(15);
     //ANCON1bits.VBGEN = 0;	    // Disable Bandgap

      //Adc_Init(ADC_10BITS);
     
     
     ANCON0 = 0xFF;
     ANCON1 = 0x9F;
     ANCON1bits.VBGEN = 1;		// Enable Band gap reference voltage
     
     
     ADCON0bits.VCFG = 0;    // vreff VDD-VSS
     ADCON0bits.CHS = 0x0F;  // VBG channel select
     
     ADCON1 = 0xBE;
     ADCON0bits.ADON = 1;
     
     //for(j=0;j<16;j++)
     //{
        //myDevicesOutputStatus[j] = j;
     //}
    
     
     //EEPROMWRITE(myDevicesOutputStatus,0,16);
     
     
     //for(j=0;j<16;j++)
     //{
        //myDevicesOutputStatus[j] = 0;
     //}
     
     //DelayMs(500);
     
     EEPROMRead(&myDevicesOutputStatus, 0, 16);
     ConsolePutROMString((ROM char *)"EEPROM READ: ");
     //PrintChar(TemperatureCalibrationValue);
     
     
     for(j=0;j<1;j++)
     {
         PrintChar(myDevicesOutputStatus[j]);
     }
	

     SwTimer3 = 0;
     SwTimer4 = 0;
     
     TRISB&=0xEF;   //JL: Configuro el pin B4 como salida si modificar el estado de los demas pines
     
     while(1)
     {
     /*
         WirelessTxRx();
         WirelesStatus();
         Bypass();
         */
         
         
         //No se utilizaron
         //Menu();
         //Timer1Tick();
         //WirelessTxRxPANCOORD();
         //TaskScheduler();
         
         //JLEstas funciones deben habilitarse para trabajar como repetidora
         
         Timer1Tick();
         Repeater();
        
     }

}
Пример #22
0
int main(void) {
    int a = 0;
    unsigned char data_mix = 0, data_mix_old = 0;
    SDEV_TYPE1 S1 = {0}, *S1_p = &S1;
    char comm_buffer[MAXSTRLEN];
    int update_rate = 4;
    int eresult = 0, records = 0, file_errors = 0;


    // Init remote device data
    S1.obits.out_byte = 0xff;

    // Enable multi-vectored interrupts
    INTEnableSystemMultiVectoredInt();
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //STEP 1. Configure cache, wait states and peripheral bus clock
    // Configure the device for maximum performance but do not change the PBDIV
    // Given the options, this function will change the flash wait states, RAM
    // wait state and enable prefetch cache but will not change the PBDIV.
    // The PBDIV value is already set via the pragma FPBDIV option above..
    SYSTEMConfig(SYS_FREQ, SYS_CFG_WAIT_STATES | SYS_CFG_PCACHE);
    srand(ReadCoreTimer()); // Seed the pseudo random generator

    // SCLK1 pin 25 - SD pin 5
    PORTSetPinsDigitalOut(IOPORT_B, BIT_14); // Clock output
    // SCLK2 pin 26 - PIC pin 18
    PORTSetPinsDigitalOut(IOPORT_B, BIT_15); // Clock output

    PPSInput(2, SDI1, RPB8); //Assign SDI1 to pin 17 - SD pin 7
    PORTSetPinsDigitalIn(IOPORT_B, BIT_8); // Input for SDI1
    PPSInput(3, SDI2, RPB13); //Assign SDI2 to pin 24
    PORTSetPinsDigitalIn(IOPORT_B, BIT_13); // Input for SDI2
    PPSOutput(2, RPB11, SDO1); // Set 22 pin as output for SDO1 - SD pin 2
    PPSOutput(2, RPB5, SDO2); // Set 14 pin as output for SDO2
    PORTSetPinsDigitalOut(IOPORT_B, BIT_2); // CS line pin 6 - SD pin 1
    mPORTBSetBits(BIT_2); // deselect SDCARD
    PORTSetPinsDigitalOut(IOPORT_B, BIT_3); // select pin enable for SPI slaves bit 2 to 74hc138
    mPORTBSetBits(BIT_3); // deselect Slave1 bit2
    PORTSetPinsDigitalOut(IOPORT_A, BIT_3); // spare digital output
    mPORTASetBits(BIT_3); // 
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Diag Led pins
    PORTSetPinsDigitalOut(IOPORT_A, BIT_0 | BIT_1); // bi-color LED
    PORTSetPinsDigitalOut(IOPORT_B, BIT_0 | BIT_1); // programming inputs /device select outputs address for SPI slaves bits [0..1] 74hc138

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // STEP 3. initialize the port pin states = outputs low
    mPORTASetBits(BIT_0 | BIT_1);
    mPORTBClearBits(BIT_0 | BIT_1);
    RTC_Init(); // Start Timer5 for background processes and 1ms soft timers
    Blink_Init(); // Start Timer4 background blink driver
    blink_led(RED_LED, LED_ON, FALSE);

    init_spi_ports();
    ps_select(0); // select the pic18 slave1 on spi port 2, select 0
    // send some text to clean the buffers
    SpiStringWrite("\r\n                                                                              \n\r");

    eresult = f_mount(&FatFs, "0:", 1);
    if (eresult) {
        sprintf(comm_buffer, "\r\n Mount error %i ", eresult);
        SpiStringWrite(comm_buffer); /* Register work area to the logical drive 1 */
        blink_led(GREEN_LED, LED_OFF, FALSE);
        blink_led(RED_LED, LED_ON, FALSE);
    } else {
        Show_MMC_Info();
        blink_led(RED_LED, LED_OFF, FALSE);
        blink_led(GREEN_LED, LED_ON, TRUE);
    }

    /* Create destination file on the drive 1 */
    eresult = f_open(&File[0], "0:logfile.txt", FA_CREATE_ALWAYS | FA_WRITE);

    while (1) { // loop and move data
        V.Timer1 = update_rate;
        while (V.Timer1);

        /* loop back testing */
        data_mix_old = data_mix; // save the old data
        data_mix = rand(); // make new data
        if (S1_p->char_ready || !S1_p->ibits.in_bits.eject) {
            S1_p->rec_data = S1_p->rec_tmp;

            //			led1_green();
        } else {

            //			led1_off();
        }

        S1_p->ibits.in_byte = SpiPortWrite(S1_p->obits.out_byte);
        if (S1_p->ibits.in_bits.card_detect) {
            S1_p->obits.out_bits.eject_led = OFF;
            SD_NOTRDY = STA_NOINIT;
        } else {
            S1_p->obits.out_bits.eject_led = ~S1_p->obits.out_bits.eject_led;
        }
        for (S1_p->chan_no = 0; S1_p->chan_no < 4; S1_p->chan_no++) {
            S1_p->adc_data[S1_p->chan_no] = SpiADCRead(S1_p->chan_no);
        }
        a = 0;

        if (((records % 100)) == 0 && !eresult) {
            if (S1_p->char_ready) {
                snprintf(comm_buffer, 64, "\r\n %x , %i, %x , %i , %i , %i , %i ", S1_p->rec_data, records, S1_p->ibits.in_byte, S1_p->adc_data[0], S1_p->adc_data[1], S1_p->adc_data[2], S1_p->adc_data[3]);
            } else {
                snprintf(comm_buffer, 64, "\r\n %x , %i , %i , %i , %i , %i ", S1_p->ibits.in_byte, records, S1_p->adc_data[0], S1_p->adc_data[1], S1_p->adc_data[2], S1_p->adc_data[3]);
            }
            S1_p->rec_tmp = SpiStringWrite(comm_buffer);
        }
        if (SpiSerialReadOk() || !S1_p->ibits.in_bits.eject) {
            S1_p->char_ready = TRUE;
            if ((S1_p->rec_tmp == 'f') || !S1_p->ibits.in_bits.eject) {
                if (S1_p->ibits.in_bits.card_detect) { // no disk
                    blink_led(0, LED_ON, FALSE);
                    S1_p->obits.out_bits.eject_led = OFF;
                    S1_p->ibits.in_byte = SpiPortWrite(S1_p->obits.out_byte);
                    SpiStringWrite("\r\n Insert Disk! y/n ");
                    while (!SpiSerialReadReady() && S1_p->ibits.in_bits.card_detect) S1_p->ibits.in_byte = SpiPortWrite(S1_p->obits.out_byte);
                    V.Timer1 = update_rate;
                    while (V.Timer1);
                    if (!S1_p->ibits.in_bits.card_detect) {
                        SpiStringWrite("/\r\n Mounting Disk ");
                        S1_p->obits.out_bits.eject_led = ON;
                        S1_p->ibits.in_byte = SpiPortWrite(S1_p->obits.out_byte);
                        eresult = f_mount(&FatFs, "0:", 1);
                        if (eresult) {
                            sprintf(comm_buffer, "\r\n Mount error %i ", eresult);
                            SpiStringWrite(comm_buffer); /* Register work area to the logical drive 1 */
                            blink_led(GREEN_LED, LED_OFF, FALSE);
                            blink_led(RED_LED, LED_ON, FALSE);
                        } else {
                            Show_MMC_Info();
                            blink_led(RED_LED, LED_OFF, FALSE);
                            blink_led(GREEN_LED, LED_ON, TRUE);
                        }
                        /* Create destination file on the drive 1 */
                        eresult = f_open(&File[0], "0:logfile.txt", FA_CREATE_ALWAYS | FA_WRITE);
                        SpiStringWrite("\r\n Mount Complete ");

                        S1_p->ibits.in_byte = SpiPortWrite(S1_p->obits.out_byte);
                        if (S1_p->ibits.in_bits.card_detect) SD_NOTRDY = STA_NOINIT;
                    }
                } else { // Eject current disk
                    blink_led(0, LED_ON, FALSE);
                    S1_p->obits.out_bits.eject_led = OFF;
                    S1_p->ibits.in_byte = SpiPortWrite(S1_p->obits.out_byte);
                    f_close(&File[0]);
                    SpiStringWrite("\r\n Eject Disk? y/n ");
                    while (!SpiSerialReadReady() && !S1_p->ibits.in_bits.card_detect) S1_p->ibits.in_byte = SpiPortWrite(S1_p->obits.out_byte);
                    V.Timer1 = update_rate;
                    while (V.Timer1);
                    if (S1_p->ibits.in_bits.card_detect) {
                        SpiStringWrite("\r\n Ejecting Disk ");
                        S1_p->obits.out_bits.eject_led = ON;
                        S1_p->ibits.in_byte = SpiPortWrite(S1_p->obits.out_byte);

                        if (f_mount(0, "0:", 0)) SpiStringWrite("\r\n UMount error "); /* Unregister work area from the logical drive 1 */
                        SpiStringWrite("\r\n Ejection Complete ");
                        eresult = 1;

                        S1_p->ibits.in_byte = SpiPortWrite(S1_p->obits.out_byte);
                        if (S1_p->ibits.in_bits.card_detect) SD_NOTRDY = STA_NOINIT;
                    }
                }
            }
        } else {
            S1_p->char_ready = FALSE;
        }

        V.Timer1 = update_rate;
        while (V.Timer1);

        // only GREEN if the data sent and received match or eject button is pressed
        if (S1_p->ibits.in_bits.eject && (S1_p->rec_data != data_mix_old)) {
            //            blink_led(0, LED_ON, TRUE);
        } else {
            //            blink_led(0, LED_ON, FALSE);
        }

        if (!eresult) {
            a = f_puts(comm_buffer, &File[0]);
            blink_led(RED_LED, LED_OFF, FALSE);
            blink_led(GREEN_LED, LED_ON, TRUE);
            records++;
        } else {
            file_errors++;
            if ((file_errors % 100) == 0) {
                SpiStringWrite("\r\n not logged ");
                blink_led(GREEN_LED, LED_OFF, FALSE);
                blink_led(RED_LED, LED_ON, FALSE);
            }
        }

        if (a == (-1)) {
            if ((file_errors % 100) == 0) {
                sprintf(comm_buffer, "\r\n File Write error %i ", a);
                SpiStringWrite(comm_buffer);
                blink_led(GREEN_LED, LED_OFF, FALSE);
                blink_led(RED_LED, LED_ON, FALSE);
            }
        }
        f_sync(&File[0]);
    }
}
Пример #23
0
/**************************************************************************************************
Initialise the video components
***************************************************************************************************/
void initVideo(void) {

    AutoLineWrap = 1;

    // test if there is a monitor plugged into the VGA connector
    CNPUASET = (1 << 4);                                            // set a pullup on the video output pin
    uSec(300);                                                      // allow it to settle
    //vga = !PORTAbits.RA4;                                           // the pin will be pulled low if the monitor is there
    CNPUACLR = (1 << 4);

    ////////////////////////////
    // setup SPI2 which is the video generator.  the output of this module is a stream of bits which are the pixels in a horiz scan line
    //if(vga)
        PPSOutput(3, RPA4, SDO2);                                    // B5 is the video out for VGA [color]]
    //else
    //    PPSOutput(3, RPB2, SDO2);                                   // B2 is the video out for composite
    PPSInput(4, SS2, RPB9);                                         // B9 is the framing input [horizontal synch]
    #define P_VIDEO_SPI         2                                   // the SPI peripheral used for video
    #define P_SPI_INPUT         SPI2BUF                             // input buffer for the SPI peripheral
    #define P_SPI_INTERRUPT     _SPI2_TX_IRQ                        // interrupt used by the SPI peripheral when it needs more data

    ////////////////////////////
    // the horizontal sync uses Timer 3 and Output Compare 3 to generate the pulse and interrupt level 7
    PPSOutput(4, RPB14, OC3);                                       // B14 is the horizontal sync output (ie, the output from OC3)
    #define P_VID_OC_OPEN       OpenOC3                             // the function used to open the output compare
    #define P_VID_OC_REG        OC3R                                // the output compare register

    ////////////////////////////
    // the vertical sync uses B13
    TRISBCLR = (1<<13);                                             // Vert sync output used by VGA
    #define P_VERT_SET_HI		LATBSET = (1 << 13)                 // set vert sync hi
    #define P_VERT_SET_LO		LATBCLR = (1 << 13)                 // set vert sync lo

    // calculate the paramaters for each video mode and setup Timer 3 to generate the horiz synch and interrupt on its leading edge
    //if(vga) {
        // set up for VGA output
	    HRes = VGA_HRES;                                            // HRes is the number of horiz pixels to use
	    HBuf = VGA_HBUFF * 32;                                      // HBuf is the horiz buffer size (in pixels)
        ConfigBuffers(Option[O_LINES24]);                           // setup the buffer pointers and VBuf, VRes
		VC[0] = VGA_VSYNC_N;										// setup the table used to count lines
		VC[1] = VGA_POSTEQ_N;
	    P_VID_OC_OPEN(OC_ON | OC_TIMER3_SRC | OC_CONTINUE_PULSE, 0, VGA_HSYNC_T);	// enable the output compare which is used to time the width of the horiz sync pulse
	    OpenTimer3( T3_ON | T3_PS_1_1 | T3_SOURCE_INT, VGA_LINE_T-1);	            // enable timer 3 and set to the horizontal scanning frequency
	//}
    /*else if(Option[O_PAL]) {
		// this is for the PAL composite output and is the same as VGA with timing differences
	    VBuf = VRes = PAL_VRES;
	    HRes = PAL_HRES;
	    HBuf = PAL_HBUFF * 32;                                      // HBuf is the horiz buffer size (in pixels)
        ConfigBuffers(0);
	    SvSyncT = PAL_LINE_T - C_HSYNC_T;
		VC[0] = C_VSYNC_N;
		VC[1] = PAL_POSTEQ_N;
		VC[2] = PAL_VRES;
		VC[3] = PAL_PREEQ_N;
	    P_VID_OC_OPEN(OC_ON | OC_TIMER3_SRC | OC_CONTINUE_PULSE, 0, C_HSYNC_T);	    // enable the output compare which is used to time the width of the horiz sync pulse
	    OpenTimer3(T3_ON | T3_PS_1_1 | T3_SOURCE_INT, PAL_LINE_T-1);	            // enable timer 3 and set to the horizontal scanning frequency
    }
    */
    
    /*
	else {
		// this is for the NTSC composite output and is similar again
	    VBuf = VRes = NTSC_VRES;
	    HRes = NTSC_HRES;
	    HBuf = NTSC_HBUFF * 32;                                     // HBuf is the horiz buffer size (in pixels)
        ConfigBuffers(0);
	    SvSyncT = NTSC_LINE_T - C_HSYNC_T;
		VC[0] = C_VSYNC_N;
		VC[1] = NTSC_POSTEQ_N;
		VC[2] = NTSC_VRES;
		VC[3] = NTSC_PREEQ_N;
	    P_VID_OC_OPEN(OC_ON | OC_TIMER3_SRC | OC_CONTINUE_PULSE, 0, C_HSYNC_T);	    // enable the output compare which is used to time the width of the horiz sync pulse
	    OpenTimer3(T3_ON | T3_PS_1_1 | T3_SOURCE_INT, NTSC_LINE_T-1);	            // enable timer 3 and set to the horizontal scanning frequency
	}
    */

    // set priority level 7 for the timer 3 interrupt (horiz synch) and enable it
    mT3SetIntPriority(7);
    mT3IntEnable(1);

    // initialise the state machine and set the count so that the first interrupt will increment the state
	VState = SV_PREEQ;
    VCount = 1;

    // setup the SPI channel then DMA channel which will copy the memory bitmap buffer to the SPI channel
    //if(vga) {
        // open the SPI in framing mode.  Note that SPI_OPEN_DISSDI will disable the input (which we do not need)
	    SpiChnOpen(P_VIDEO_SPI, SPICON_ON | SPICON_MSTEN | SPICON_MODE32 | SPICON_FRMEN | SPICON_FRMSYNC | SPICON_FRMPOL | SPI_OPEN_DISSDI, VGA_PIX_T);
        SPI2CON2 = (1<<9) | (1<<8);                                         // instruct the SPI module to ignore any errors that might occur
        DmaChnOpen(1, 1, DMA_OPEN_DEFAULT);                                 // setup DMA 1 to send data to SPI channel 2
        DmaChnSetEventControl(1, DMA_EV_START_IRQ_EN | DMA_EV_START_IRQ(P_SPI_INTERRUPT));
	    DmaChnSetTxfer(1, (void*)VideoBuf, (void *)&P_SPI_INPUT, HBuf/8, 4, 4);
    //}
    /*
    else {
	    SpiChnOpen(P_VIDEO_SPI, SPICON_ON | SPICON_MSTEN | SPICON_MODE32 | SPICON_FRMEN | SPICON_FRMSYNC | SPICON_FRMPOL | SPI_OPEN_DISSDI, C_PIX_T);
        SPI2CON2 = (1<<9) | (1<<8);                                         // instruct the SPI module to ignore any errors that might occur
        DmaChnOpen(1, 1, DMA_OPEN_DEFAULT);    	                            // setup DMA 1 is the blank padding at the start of a scan line
        DmaChnSetEventControl(1, DMA_EV_START_IRQ_EN | DMA_EV_START_IRQ(P_SPI_INTERRUPT));
	    DmaChnSetTxfer(1, (void*)zero, (void *)&P_SPI_INPUT, C_BLANKPAD, 4, 4);
    	DmaChnOpen( 0, 0, DMA_OPEN_DEFAULT);		                        // setup DMA 0 to pump the data from the graphics buffer to the SPI peripheral
    	DmaChnSetEventControl(0, DMA_EV_START_IRQ_EN | DMA_EV_START_IRQ(P_SPI_INTERRUPT));
	    DmaChnSetTxfer(0, (void*)VideoBuf, (void *)&P_SPI_INPUT, HBuf/8 + 6, 4, 4);
    	DmaChnSetControlFlags(0, DMA_CTL_CHAIN_EN | DMA_CTL_CHAIN_DIR);    	// chain DMA 0 so that it will start on completion of the DMA 1 transfer
    }
     */
}
Пример #24
0
void ImuNodeInit(uint32_t f_osc)
{
    // And configure the Peripheral Pin Select pins:
    PPSUnLock;
	PPSUnLock;

#ifdef __dsPIC33FJ128MC802__
	// To enable ECAN1 pins: TX on 7, RX on 4
	PPSOutput(OUT_FN_PPS_C1TX, OUT_PIN_PPS_RP7);
	PPSInput(IN_FN_PPS_C1RX, IN_PIN_PPS_RP4);

	// To enable UART1 pins: TX on 9, RX on 8
	PPSOutput(OUT_FN_PPS_U1TX, OUT_PIN_PPS_RP9);
	PPSInput(IN_FN_PPS_U1RX, IN_PIN_PPS_RP8);
#elif __dsPIC33EP256MC502__
	// To enable ECAN1 pins: TX on 39, RX on 36
	PPSOutput(OUT_FN_PPS_C1TX, OUT_PIN_PPS_RP39);
	PPSInput(IN_FN_PPS_C1RX, IN_PIN_PPS_RP36);

	// To enable UART1 pins: TX on 41, RX on 40
	PPSOutput(OUT_FN_PPS_U1TX, OUT_PIN_PPS_RP41);
	PPSInput(IN_FN_PPS_U1RX, IN_PIN_PPS_RP40);
#endif

    PPSLock;
	
	// Also disable analog functionality on B8 so we can use it for UART1 RX.
	// This only applies to the dsPIC33E family.
#ifdef __dsPIC33EP256MC502__
	ANSELBbits.ANSB8 = 0;
#endif

    // Initialize status LEDs for use.
	// A3 (output): Red LED, off by default, and is solid when the system hit a fatal error.
    _TRISA3 = 0; 
    _LATA3 = 0;
	// A4 (output): Amber LED, blinks at 1Hz when disconnected from the IMU, 2Hz otherwise.
    _TRISA4 = 0;
    _LATA4 = 0;

	_TRISB7 = 0; // Set ECAN1_TX pin to an output
	_TRISB4 = 1; // Set ECAN1_RX pin to an input;

    // Set up UART1 for 115200 baud. There's no round() on the dsPICs, so we implement our own.
	double brg = (double)f_osc / 2.0 / 16.0 / 115200.0 - 1.0;
	if (brg - floor(brg) >= 0.5) {
		brg = ceil(brg);
	} else {
		brg = floor(brg);
	}
	Uart1Init((uint16_t)brg);

    // Initialize ECAN1 for input and output using DMA buffers 0 & 2
    Ecan1Init(f_osc, NODE_CAN_BAUD);

    // Set the node ID
    nodeId = CAN_NODE_IMU_SENSOR;

    // Set up all of our tasks.
    // Blink at 1Hz
    if (!AddMessageRepeating(&taskSchedule, TASK_BLINK, RATE_TRANSMIT_BLINK_DEFAULT)) {
            FATAL_ERROR();
    }
    // Transmit node status at 2Hz
    if (!AddMessageRepeating(&taskSchedule, TASK_TRANSMIT_STATUS, RATE_TRANSMIT_NODE_STATUS)) {
            FATAL_ERROR();
    }
    // Transmit IMU data at 25Hz
    if (!AddMessageRepeating(&taskSchedule, TASK_TRANSMIT_IMU, RATE_TRANSMIT_IMU_DATA)) {
            FATAL_ERROR();
    }
}