Beispiel #1
0
void quad_read(_QUAD *self) {
    disable_interrupts();
    // pin_set(&D[2]);  // debug pin
    self -> a_curr = pin_read(self -> A);
    self -> b_curr = pin_read(self -> B);
    unsigned char latest_read = (self -> a_curr << 1) + self -> b_curr;
    self -> encoder_read = ((self -> encoder_read << 2) + latest_read) & 0xF;
    int8_t delta = quad_lut[self -> encoder_read];
    self -> delta = delta;
    if (self -> counter == 0) {
        if (delta == -1) {
            self -> overflow += -1;
        }
    }

    self -> counter += delta;

    if (self -> counter == 0) {
        if (delta == 1) {
            self -> overflow += 1;
        }
    }
    
    self -> a_prev = self -> a_curr;
    self -> b_prev = self -> b_curr;
    // pin_clear(&D[2]);    // debug pin
    enable_interrupts();
}
Beispiel #2
0
void pwm_set_direction(unsigned char direction) {
    // Direction is a bit [0 or 1] specifying the direction
    // the motor should be commanded to turn. 1 is "forwards",
    // and 0 is "reverse". Assumes fast decay mode operation.
    if (pwm_direction != direction) {
        // The direction to be set is different than the motor's current
        // direction. A change should be made.
        uint16_t prev_duty;
        pwm_direction = direction;  // Update pwm_direction
        if (direction == 1) {
            // If 1, PWM_I1 should PWM, PWM_I2 should be 0.
            // printf("Setting motor direction FORWARD...\r\n");
            prev_duty = pin_read(PWM_I2);
            pin_write(PWM_I2, (uint16_t)(0));
            pin_write(PWM_I1, prev_duty);
        } else if (direction == 0) {
            // If 0, PWM_I1 should 0, PWM_I2 should be 1.
            // printf("Setting motor direction REVERSE...\r\n");
            prev_duty = pin_read(PWM_I1);
            pin_write(PWM_I1, (uint16_t)(0));
            pin_write(PWM_I2, prev_duty);
        } else {
            printf("ERR: Invalid PWM direction %d received.\r\n", direction);
        }
    }
}
Beispiel #3
0
// Declared int for compatiblity with Arduino digitalRead
// However added return of ERROR as -1 since the Arduino way
// of returning LOW for NOT_A_PIN is doesn't inform on the error
int8_t digital_read(uint8_t pin)
{
#if defined (__AVR_ATmega169__) || defined (__AVR_ATmega169P__)
	if ( pin < 8) // it is PORTB
	{
		pin_read(PINB,pin);
	}
	else if  // it is PORTD
	{
		pin -= 8; // converts it to numbering for PORTD
		pin_read(PIND,pin);
	}
	else // out of range 
	{
		return(-1); // returen ERROR
/*!
 * Advances the program counter.  If the branching logic tells the processor
 * that it's time to jump somewhere else, the branch address is read and used.
 * Otherwise, the program counter is simply incremented.
 */
void nextPC(ProgramCounter *pc) {
    busdata_t next_pc;

    /*
     * increment the program counter, or load the program counter from the
     * branch address.
     */
    if (pin_read(pc->branch) == BRANCH)
        next_pc = pin_read(pc->branch_addr);
    else
        next_pc = pin_read(pc->pc_pin) + 1;

    /* Set the new value for the program counter. */
    pin_set(pc->pc_pin, next_pc);
}
Beispiel #5
0
/*! 
 * This function performs the branching test.  It reads the current opcode and
 * the output from the first source register, and then writes either BRANCH or
 * NOBRANCH to the branch pin.
 */
void branch_test(BranchUnit *bru) {
    int A;
    int aluop;

    A = pin_read(bru->in1);
    aluop = pin_read(bru->op);

    // If aluop is BNZ, and A is nonzero, set bru->branch to BRANCH
    if (aluop == ALUOP_BNZ && A) {
        pin_set(bru->branch, BRANCH);
    }
    // Otherwise NOBRANCH
    else {
        pin_set(bru->branch, NOBRANCH);
    }
}
Beispiel #6
0
void get_readings() {
    /*
    Get readings for current, raw angle, wraps, unwrapped angle, and velocity
    */
    // Read current pin and zero-center
    CURRENT.w = pin_read(&A[0]) - CUR_OFFSET;

    // Read the encoder, check parity, and subtract initial offset
    LAST_ANGLE = ANGLE;
    WORD result = enc_readReg((WORD) REG_ANG_ADDR);
    if (!parity(result.w)) {
        ANGLE.w = ((result.w & ENC_MASK) - ANG_OFFSET.w) & ENC_MASK;
    }

    // Check for wrapping; if the angle jumps from <~20 degrees
    // to >~340 degrees, or vice-versa, we wrapped
    if ((ANGLE.w < 0x038E) && (LAST_ANGLE.w > 0x3C71)) {
        WRAPS += 1;
    } else if ((ANGLE.w > 0x3C71) && (LAST_ANGLE.w < 0x038E)) {
        WRAPS -= 1;
    }

    // Apply wrapping to the raw angle
    uint16_t last = UNWRAPPED_ANGLE.w;
    UNWRAPPED_ANGLE.w = ANGLE.w + ENC_MASK * WRAPS;

    // Calculate velocity as (change in angle) / (time between readings)
    // Divide by 16 to avoid overflow
    VELOCITY.w = (UNWRAPPED_ANGLE.w - last) * (READ_FREQ / 16);
}
Beispiel #7
0
/**
 * The interrupt service routine is called on falling edges. Read a
 * byte and write it on the receive channel.
 */
static void rx_isr(void *arg_p)
{
    int i;
    uint8_t data = 0, sample;
    struct uart_soft_driver_t *self_p = arg_p;

    /* Wait half the sample time so following samples are taken in the
       middle of the sample period.*/
    time_busy_wait_us(self_p->sample_time / 3);

    /* Get 8 bits. */
    for (i = 0; i < 8; i++) {
        time_busy_wait_us(self_p->sample_time);

        /* Sample the pin. */
        data >>= 1;
        sample = pin_read(&self_p->rx_pin);
        data |= (0x80 * sample);
    }

    /* Write data to input channel. */
    queue_write_isr(&self_p->chin, &data, sizeof(data));

    /* During the execution of this routinue multiple falling edges
       are detected by the hardware. The interrupt flag will be set
       and should be cleared to inhibit that the routine is executed
       twise per 8 bits.*/
    exti_clear(&self_p->rx_exti);
}
Beispiel #8
0
void over_game(void) {
    if (game.state != game.last_state) {  // if we are entering the state, do intitialization stuff
        game.last_state = game.state;

        game.hit_flag = 0;
        game.level_ticks = 0;

        game.level_limit = MAX_LEVEL;
        game.level = 0;

        game.decay_ticks = 0;
        game.decay_limit = MAX_DECAY;

        timer_lower(game.level_timer);
        timer_lower(game.decay_timer);
        update_bar_pix(0, &start_color, &end_color);

        if (game.score > game.high) {
            game.high = game.score;
        }

        write_display(game.high_display, game.high, 0);
        write_display(game.score_display, game.score, 0);
        blink_display(game.score_display, 1);
    }

    //run state logic
    if (game.lose_flag) {
        if (timer_flag(game.level_timer)) {
            timer_lower(game.level_timer);
            game.lose_ticks++;
            if (game.lose_ticks == MAX_LOSE) {
                trigger_audio(LOSE);
                game.lose_flag = 0;
            }
        }
    }

    if (pin_read(game.coin_op)) {
        game.coin_flag = 1;
        trigger_audio(START);
    }

    if (game.hit_flag && game.coin_flag) {
        game.state = rest_game;
        game.hit_flag = 0;
        game.coin_flag = 0;
    }

    if (game.state != game.last_state) {  // if we are leaving the state, do clean up stuff
        game.level = 1;
        game.life = MAX_LIFE;
        game.score = 0;
        game.lose_flag = 0;
        game.lose_ticks = 0;
        blink_display(game.score_display, 0);
        write_display(game.score_display, game.score, 0);
    }
}
Beispiel #9
0
void get_direction(void){
    uint16_t d = pin_read(CURRENT_PIN);
    if (d >= 0x8000){
        SENSED_DIRECTION = 0;
    } else {
        SENSED_DIRECTION = 1;
    }
}
Beispiel #10
0
/**
 * def read(self)
 */
static mp_obj_t class_pin_read(mp_obj_t self_in)
{
    struct class_pin_t *self_p;

    self_p = MP_OBJ_TO_PTR(self_in);

    return (MP_OBJ_NEW_SMALL_INT(pin_read(&self_p->drv)));
}
Beispiel #11
0
void __attribute__((interrupt, auto_psv)) _CNInterrupt(void) {
    IFS1bits.CNIF = 0; //lower the flag
    if (SENSED_DIRECTION) //count in the right direction
    {
        REV++;
    } else {
        REV--;
    }
    pin_read(REV_PIN); //clear the pin
}
/*!
 * This function decodes the instruction on the input pin, and writes all of the
 * various components to output pins.  Other components can then read their
 * respective parts of the instruction.
 */
void idecode(Decode *d) {
    busdata_t instr = pin_read(d->input);

    pin_set(d->aluop,       ((instr >> ALUOP_POS) & ALUOP_MASK));
    pin_set(d->write,       ((instr >> WRITE_POS) & WRITE_MASK));
    pin_set(d->src1_addr,   ((instr >> SRC1_POS)  & SRC1_MASK));
    pin_set(d->src2_addr,   ((instr >> SRC2_POS)  & SRC2_MASK));
    pin_set(d->dst_addr,    ((instr >> DST_POS)   & DST_MASK));
    pin_set(d->branch_addr, ((instr >> BRANCH_ADDR_POS) & BRANCH_ADDR_MASK));
}
Beispiel #13
0
void launch_launcher(void) {
    if (launcher.state != launcher.last_state) {  // if we are entering the state, do initialization stuff
        launcher.last_state =  launcher.state;
    }

    if (!pin_read(launcher.load_sensor)) {
        launcher.loaded = 1;
        led_on(&led1);
        pin_clear(launcher.elevator_motor);
    }

    if (launcher.loaded) {
        pin_set(launcher.launch_motor);
        if (!pin_read(launcher.launch_sensor)) {
            limit_flag = 1;
        }

        if (pin_read(launcher.launch_sensor) && limit_flag) {
            limit_counter++;
        }

        if (limit_counter >= 100) {
            launcher.state = rest_launcher;
        }
    } else {
        if (launcher.over) {
            launcher.state = over_launcher;
        }
    }

    if (launcher.state != launcher.last_state) {  // if we are leaving the state, do clean up stuff
        pin_clear(launcher.launch_motor);
        pin_set(launcher.elevator_motor);
        launcher.launch = 0;
        launcher.loaded = 0;
        led_off(&led1);
        limit_flag = 0;
        limit_counter = 0;
    }
}
int16_t main(void) {
    init_clock();
    init_timer();
    init_pin();
    init_oc();
    init_md();

    pin_analogIn(&A[0]);

    md_velocity(&md1, 0xF000, 1);

    InitUSB();                              // initialize the USB registers and serial interface engine
    while (USB_USWSTAT!=CONFIG_STATE) {     // while the peripheral is not configured...
        LAST_CURRENT = CURRENT_CURRENT;
        CURRENT_CURRENT.w = pin_read(&A[0]);
        ServiceUSB();                       // ...service USB requests
    }
    while (1) {
        LAST_CURRENT = CURRENT_CURRENT;
        CURRENT_CURRENT.w = pin_read(&A[0]);
        ServiceUSB();                       // service any pending USB requests
    }
}
Beispiel #15
0
void Keypad::scanKeys() {
	// Re-intialize the row pins. Allows sharing these pins with other hardware.
	for (byte r=0; r<sizeKpd.rows; r++) {
		pin_mode(rowPins[r],INPUT_PULLUP);
	}

	// bitMap stores ALL the keys that are being pressed.
	for (byte c=0; c<sizeKpd.columns; c++) {
		shiftOut(srdatPin, srclkPin, MSBFIRST, ~(4 >> c));

		for (byte r=0; r<sizeKpd.rows; r++) {
			bitWrite(bitMap[r], c, !pin_read(rowPins[r]));  // keypress is active low so invert to high.
		}
	}
}
Beispiel #16
0
int readDHT(int* temp,int* humi)
{

    u8_t bits[5];
    int rv = pin_read(bits);
    if(rv != 0)return rv;

    *humi = bits[0];
    *temp = bits[2];

    u8_t sum = bits[0] + bits[2];
    if(bits[4] != sum)return -1;

    return 0;

}
uint16_t PIDcalc(uint16_t set_point){
    actual_position = pin_read(potentiometer);
    uint16_t error;
    uint16_t duty; 
    uint16_t threshold = 500;
    // printf("actual_position %u\n\r",  actual_position);
    error = abs((set_point - actual_position));
    // printf("error %u\n\r",  error);
    if (error > threshold){
        duty = (Kp * error);
        // printf("duty %u\n\r",  duty);
        pin_write(pwmpin, duty);
        PIDcalc(set_point);  
    }
    else{
        pin_write(pwmpin, 0); 
    } 
}
Beispiel #18
0
// Private : Hardware scan
void Keypad_MAX::scanKeys() {
	// Re-intialize the pins every time for sharing with other hardware.
	for (byte r=0; r<sizeKpd.rows; r++) {
		pin_mode(rowPins[r],INPUT_PULLUP);
	}

	// bitMap stores ALL the keys that are being pressed.
	for (byte c=0; c<sizeKpd.columns; c++) {
		pin_mode(columnPins[c],OUTPUT);
		pin_write(columnPins[c], LOW);	// Begin column pulse output.
		for (byte r=0; r<sizeKpd.rows; r++) {
			bitWrite(bitMap[r], c, !pin_read(rowPins[r]));  // keypress is active low so invert to high.
		}
		// Set pin to high impedance input. Effectively ends column pulse.
		pin_write(columnPins[c],HIGH);
		pin_mode(columnPins[c],INPUT);
	}
}
Beispiel #19
0
void receive(_TIMER *self) {
	timer_setPeriod(&timer5, 50e-3);
	timer_start(&timer5);
	led_toggle(&led1);
	overflowing = 0;
	while(pin_read(&D[12]) == 0){
		if (timer_flag(&timer5) != 0){
			led_toggle(&led3);
			overflowFlag += 1;
			overflowing = 1;
			break;
		}
	}
	if (overflowing == 0) {
		overflowFlag = 0;
	}
	readTime = timer_read(&timer5);
	led_toggle(&led2);
	timer_stop(&timer5);
}
Beispiel #20
0
void rest_launcher(void) {
    if (launcher.state != launcher.last_state) {  // if we are entering the state, do intitialization stuff
        launcher.last_state = launcher.state;
    }

    if (!pin_read(launcher.load_sensor)) {
        launcher.loaded = 1;
        led_on(&led1);
        pin_clear(launcher.elevator_motor);
    }

    if (launcher.over) {
        launcher.state = over_launcher;
    }

    if (launcher.launch) {
        launcher.state = launch_launcher;
    }

    /*if (state_launcher != last_state_launcher) {  // if we are leaving the state, do clean up stuff
      }*/
}
Beispiel #21
0
/*! Routine for exercising the ALU with a number of simple inputs. */
void testops(ALU* alu, pin in1, pin in2, pin op, pin out) {
    pin_set(op, ALUOP_INV);
    alu_eval(alu);
    printf("\t~0x%X = 0x%X\n", pin_read(in1), pin_read(out));

    pin_set(op, ALUOP_ADD);
    alu_eval(alu);
    printf("\t0x%X (%d) + 0x%X (%d) = 0x%X (%d)\n",
         pin_read(in1), pin_read(in1),
         pin_read(in2), pin_read(in2),
         pin_read(out), pin_read(out));

    pin_set(op, ALUOP_SUB);
    alu_eval(alu);
    printf("\t0x%X (%d) - 0x%X (%d) = 0x%X (%d)\n",
         pin_read(in1), pin_read(in1),
         pin_read(in2), pin_read(in2),
         pin_read(out), pin_read(out));

    pin_set(op, ALUOP_INCR);
    alu_eval(alu);
    printf("\t0x%X (%d) + 1 = 0x%X (%d)\n",
         pin_read(in1), pin_read(in1),
         pin_read(out), pin_read(out));

    pin_set(op, ALUOP_AND);
    alu_eval(alu);
    printf("\t0x%X (%d) & 0x%X (%d) = 0x%X (%d)\n",
         pin_read(in1), pin_read(in1),
         pin_read(in2), pin_read(in2),
         pin_read(out), pin_read(out));

    pin_set(op, ALUOP_OR);
    alu_eval(alu);
    printf("\t0x%X (%d) | 0x%X (%d) = 0x%X (%d)\n",
         pin_read(in1), pin_read(in1),
         pin_read(in2), pin_read(in2),
         pin_read(out), pin_read(out));

    pin_set(op, ALUOP_XOR);
    alu_eval(alu);
    printf("\t0x%X (%d) ^ 0x%X (%d) = 0x%X (%d)\n",
         pin_read(in1), pin_read(in1),
         pin_read(in2), pin_read(in2),
         pin_read(out), pin_read(out));

    pin_set(op, ALUOP_SLL);
    alu_eval(alu);
    printf("\tLogical 0x%X (%d) << 1 = 0x%X (%d)\n",
         pin_read(in1), pin_read(in1),
         pin_read(out), pin_read(out));

    pin_set(op, ALUOP_SRL);
    alu_eval(alu);
    printf("\tLogical 0x%X (%d) >> 1 = 0x%X (%d)\n",
         pin_read(in1), pin_read(in1),
         pin_read(out), pin_read(out));

    pin_set(op, ALUOP_SLA);
    alu_eval(alu);
    printf("\tArithmetic 0x%X (%d) << 1 = 0x%X (%d)\n",
         pin_read(in1), pin_read(in1),
         pin_read(out), pin_read(out));

    pin_set(op, ALUOP_SRA);
    alu_eval(alu);
    printf("\tArithmetic 0x%X (%d) >> 1 = 0x%X (%d)\n",
         pin_read(in1), pin_read(in1),
         pin_read(out), pin_read(out));
}
Beispiel #22
0
/*!
 * This function implements the logic of the ALU.  It reads the inputs and
 * opcode, then sets the output accordingly.  Note that if the ALU does not
 * recognize the opcode, it should simply produce a zero result.
 */
void alu_eval(ALU *alu) {
    uint32_t A, B, aluop;
    uint32_t result;

    A = pin_read(alu->in1);
    B = pin_read(alu->in2);
    aluop = pin_read(alu->op);

    result = 0;

    /*======================================*/
    /* TODO:  Implement the ALU logic here. */
    /*======================================*/
    switch (aluop) {
    
    case ALUOP_ADD:
        result = A + B;
        break;
    
    case ALUOP_INV:
        result = ~A;
        break;
    
    case ALUOP_SUB:
        result = A - B;
        break;
    
    case ALUOP_XOR:
        result = A ^ B;
        break;
    
    case ALUOP_OR:
        result = A | B;
        break;
    
    case ALUOP_INCR:
        result = A + 1;
        break;
    
    case ALUOP_AND:
        result = A & B;
        break;
    
    case ALUOP_SRA:
        result = A >> 1;
        /* ensuring the 32nd bits of result and A are equal */
        if (A < LEFT_BIT) { /* if A < 2^31 the 32nd bit is 0 */
            if (result > LEFT_BIT) { /* result's 32nd bit is 1 */
                result -= LEFT_BIT;
            }
            /* otherwise result's 32nd bit is 0 and they are equal */
        }
        else {/* A's 32nd bit is 1 */
            if (result < LEFT_BIT) { /* result's 32nd bit is 0 */
                result += LEFT_BIT;
            }
        }
        break;
    
    case ALUOP_SRL:
        result = A >> 1;
        /* ensuring the 32nd bit of result is zero */
        if (result > LEFT_BIT) { /* result's 32nd bit is 1 */
            result -= LEFT_BIT;
        }
        /* otherwise the 32nd bit is already zero */
        break;
    
    case ALUOP_SLA:
        result = A << 1;
        break;
    
    case ALUOP_SLL:
        result = A << 1;
        break;
    }
    pin_set(alu->out, result);
}
Beispiel #23
0
/*!
 * This function implements the logic of the ALU.  It reads the inputs and
 * opcode, then sets the output accordingly.  Note that if the ALU does not
 * recognize the opcode, it should simply produce a zero result.
 */
void alu_eval(ALU *alu) {
    uint32_t A, B, aluop;
    uint32_t result;

    A = pin_read(alu->in1);
    B = pin_read(alu->in2);
    aluop = pin_read(alu->op);

    result = 0;

    /*======================================*/
    /* TODO:  Implement the ALU logic here. */
    /*======================================*/
    switch (aluop) {
        
        case ALUOP_ADD:
        /*The opcode for simple addition*/
            result = A + B;
            break;
        case ALUOP_INV:
        /*The opcode for bitwise invert*/
            /*if (A) {
                result = ~A;
            } else if (B) {
                result = ~B;
            } else {
                result = 0;
            };*/
            result = ~A;
            break;
        case ALUOP_SUB:
        /*!< The opcode for simple subtraction. */
            result = A - B;
            break;
        case ALUOP_XOR:
        /*!< The opcode for bitwise exclusive-or. */
            result = A ^ B;
            break;
        case ALUOP_OR:
        /*!< The opcode for bitwise or. */
            result = A | B;
            break;
        case ALUOP_INCR:
        /*!< The opcode for incrementing a register. */
            result = A + 1;
            break;
        case ALUOP_AND:
        /*!< The opcode for bitwise and. */
            result = A & B;
            break;
        case ALUOP_SRA:
        /*!< The opcode for arithmetic shift-right. */
            result = A >> 1;
            result[31] = A[31];
            break;
        case ALUOP_SRL:
        /*!< The opcode for logical shift-right. */
            result = A >> 1;
            break;
        case ALUOP_SLA:
        /*!< The opcode for arithmetic shift-left. */
            result = A << 1;
            break;
        case ALUOP_SLL:
        /*!< The opcode for logical shift-left. */
            result = A << 1;
            break;
        default:
            result = 0;
            break;
    }
    /*======================================*/
    /* END:  Implement the ALU logic. */
    /*======================================*/

    pin_set(alu->out, result);
}
Beispiel #24
0
/*!
 * This function implements the logic of the bus arbiter.  Based on the
 * inputs and the arbiter's internal state, the outputs are updated
 * accordingly.  The important rules are:
 *
 *   - AT MOST ONE grant signal may be 1.  All other grant signals
 *     must be 0.
 *
 *   - The grant signal whose value is 1 must correspond to the processor
 *     whose turn it currently is.
 *
 *   - As long as no processors are requesting the bus, the Turn value
 *     should toggle between 0 (processor A) and 1 (processor B).  Otherwise,
 *     the Turn value should remain set on the processor that is currently
 *     granted access to the bus.  (See previous point.)
 */
void clock_arbiter(BusArbiter *arb) {
    /* Current state and inputs. */
    unsigned long CurrentTurn;
    unsigned long ReqA, ReqB;

    /* Outputs and next state. */
    unsigned long GrantA, GrantB;
    unsigned long NextTurn;

    /* Bring in the current state and inputs, for the logic to use. */

    ReqA = pin_read(arb->req_a);
    ReqB = pin_read(arb->req_b);
    CurrentTurn = arb->turn;

    assert(ReqA == 0 || ReqA == 1);
    assert(ReqB == 0 || ReqB == 1);
    assert(CurrentTurn == 0 || CurrentTurn == 1);



    /* Initially, grant no one access */
    GrantA = 0;
    GrantB = 0;

    /* If it is A's Turn */
    if (CurrentTurn == 0) {
        /* If A wants access */
        if (ReqA) {
            /* Leave it A's turn */
            NextTurn = 0;
            /* Grant A access */
            GrantA = 1;
        }
        /* If A does not want access */
        else {
            /* Make it B's turn and continue granting no one access */
            NextTurn = 1;
        }
    }

    /* If it is B's Turn */
    else {
        /* If B wants access */
        if (ReqB) {
            /* Leave it B's turn */
            NextTurn = 1;
            /* Grant B access */
            GrantB = 1;
        }
        /* If B does not want access */
        else {
            /* Make it A's turn and continue granting no one access */
            NextTurn = 0;
        }
    }



    /* Set outputs and update the state! */

    assert(GrantA == 0 || GrantA == 1);
    assert(GrantB == 0 || GrantB == 1);
    assert(NextTurn == 0 || NextTurn == 1);

    pin_set(arb->grant_a, GrantA);
    pin_set(arb->grant_b, GrantB);
    arb->turn = NextTurn;
}
Beispiel #25
0
int16_t main(void) {
    init_pin();
    init_clock();
    init_uart();
    init_ui();
    init_timer();
    init_oc();

    //setup the signal input pin
    pin_digitalIn(&D[4]);

    val1 = 0;
    val2 = 0;
    pos = 0; //16 bit int with binary point in front of the MSB

    led_on(&led2);
    timer_setPeriod(&timer2, PULSE_FREQUENCY); //how often we send a pulse
    timer_start(&timer2);
    timer_setPeriod(&timer3, 0.5); //heartbeat
    timer_start(&timer3);

    oc_servo(&oc1,&D[0],&timer4, INTERVAL,MIN_WIDTH, MAX_WIDTH, pos);
    oc_servo(&oc2,&D[2],&timer5, INTERVAL,MIN_WIDTH, MAX_WIDTH, pos);
    oc_pwm(&oc3,&D[3],NULL,FREQ,ZERO_DUTY);

    printf("Good morning\n");

    InitUSB();                              // initialize the USB registers and serial interface engine
    while (USB_USWSTAT!=CONFIG_STATE) {     // while the peripheral is not configured...
        ServiceUSB();                       // ...service USB requests
    }
    while (1) {
        ServiceUSB();
        pin_write(&D[0],val1);
        pin_write(&D[2],val2); 
        //adapted from Patrick and Charlie's approach
        if (!send_pulse && timer_read(&timer2) < PULSE_WIDTH){
            send_pulse = 1;
            pin_write(&D[3],HALF_DUTY);     
            get_distance = 1;
        } else if (send_pulse && timer_read(&timer2) >= PULSE_WIDTH) {
            send_pulse = 0;
            pin_write(&D[3],ZERO_DUTY); 
        }

        if (timer_read(&timer2) >= ECHO_TIME)
        {
            if (pin_read(&D[4]) && get_distance)
            {
                printf("%d\n", timer_read(&timer2));
                get_distance = 0;
            }
        }
       if (timer_flag(&timer3)) {
            //show a heartbeat and a status message
            timer_lower(&timer3);
            led_toggle(&led1);
        }

    }
}
Beispiel #26
0
void VendorRequests(void) {
    WORD temp;
	uint16_t i = 1;
    switch (USB_setup.bRequest) {
        case HELLO:
            printf("Hello World!\n");
            BD[EP0IN].bytecount = 0;    // set EP0 IN byte count to 0 
            BD[EP0IN].status = 0xC8;    // send packet as DATA1, set UOWN bit
            break;
        case SET_VALS:
            pan_set_val = USB_setup.wValue.w;
            tilt_set_val = USB_setup.wIndex.w;
            BD[EP0IN].bytecount = 0;    // set EP0 IN byte count to 0 
            BD[EP0IN].status = 0xC8;    // send packet as DATA1, set UOWN bit
            break;
        case GET_VALS:
            temp.w = x_gout;
            BD[EP0IN].address[0] = temp.b[0];
            BD[EP0IN].address[1] = temp.b[1];
            temp.w = tilt_set_val;
            BD[EP0IN].address[2] = temp.b[0];
            BD[EP0IN].address[3] = temp.b[1];
            BD[EP0IN].bytecount = 4;    // set EP0 IN byte count to 4
            BD[EP0IN].status = 0xC8;    // send packet as DATA1, set UOWN bit
            break;            
        case PRINT_VALS:
            printf("pan_set_val = %u, tilt_set_val = %u\n", pan_set_val, tilt_set_val);
            BD[EP0IN].bytecount = 0;    // set EP0 IN byte count to 0
            BD[EP0IN].status = 0xC8;    // send packet as DATA1, set UOWN bit
            break;
		case GET_DIST:
            //Configure timer for transducer burst
            timer_setPeriod(PWM_TIM, 0.0005);
            timer_start(PWM_TIM);		//start the timer for the PWM signal
            timer_start(DIST_TIM);		//start the timer for the distance measurement
			pin_write(SONIC_OUT_PIN, 0x8000);		//send the sonic burst by setting it to 50% duty cycle

            while (1) {
                if (timer_flag(PWM_TIM)) {			//If the timer runs out for PWM
                    pin_write(SONIC_OUT_PIN, 0x0000);	//Stopping the sonic burst transmission by setting it to 0% duty cycle
                    timer_stop(PWM_TIM);				//stop PWM timer
                    break;
                }
            }

            timer_setPeriod(PWM_TIM, 0.001);		//reset the PWM timer period to 1 milliseconds
            timer_start(PWM_TIM);				

            while(1) {
                if (timer_flag(PWM_TIM)) {			//If the timer runs out for PWM
                    if(pin_read(SONIC_IN_PIN) == 1){	//If the pin gets back a value, the echo is received
                        temp.w = timer_read(DIST_TIM);	//Get the value of the timer for Distance and store in temp.w to be sent to laptop
                        break;
                    }
                    else if(timer_flag(DIST_TIM)) {     //timeout period will be set based on experimentation
                        temp.w = 0xFFFF;
                        break;
                    }   
                }
            }

            timer_stop(DIST_TIM);
            timer_stop(PWM_TIM);
			/*while(pin_read(SONIC_IN_PIN) == 0 && i != 0) {
				i++;
			} */
			
			
            BD[EP0IN].address[0] = temp.b[0];
            BD[EP0IN].address[1] = temp.b[1];
            temp.w = pan_set_val;
            BD[EP0IN].address[2] = temp.b[0];
            BD[EP0IN].address[3] = temp.b[1];
			temp.w = tilt_set_val;
			BD[EP0IN].address[4] = temp.b[0];
            BD[EP0IN].address[5] = temp.b[1];
            BD[EP0IN].bytecount = 6;    // set EP0 IN byte count to 6
            BD[EP0IN].status = 0xC8;    // send packet as DATA1, set UOWN bit
            break;
        default:
            USB_error_flags |= 0x01;    // set Request Error Flag
    }
}
Beispiel #27
0
void __attribute__((interrupt, auto_psv)) _OC1Interrupt(void) {
	IFS0bits.OC1IF = 0; 		//reset oc flag

	if (petal == 0){
		Vin0 = pin_read(inPin0);
		if (Vin0 != 0){
			VatTime0 = Vin0;
			if (Vin0 > threshold){
				touching0 = 0;
			} else {
				touching0 = 10;
			}
		}
		petal = 1;
	}
	else if (petal == 1){
		Vin1 = pin_read(inPin1);
		if (Vin1 != 0){
			VatTime1 = Vin1;
			if (Vin1 > threshold){
				touching1 = 1;
			} else {
				touching1 = 11;
			}
		}
		petal = 2;
	}
	else if (petal == 2){
		Vin2 = pin_read(inPin2);
		if (Vin2 != 0){
			VatTime2 = Vin2;
			if (Vin2 > threshold){
				touching2 = 2;
			} else {
				touching2 = 12;
			}
		}
		petal = 3;
	}
	else if (petal == 3){
		Vin3 = pin_read(inPin3);
		if (Vin3 != 0){
			VatTime3 = Vin3;
			if (Vin3 > threshold){
				touching3 = 3;
			} else {
				touching3 = 13;
			}
		}
		petal = 4;
	}
	else if (petal == 4){
		Vin4 = pin_read(inPin4);
		if (Vin4 != 0){
			VatTime4 = Vin4;
			if (Vin4 > threshold){
				touching4 = 4;
			} else {
				touching4 = 14;
			}
		}
		petal = 0;
	}
}
Beispiel #28
0
void get_vemf(void){
    VEMF = pin_read(VEMF_PIN);
}
Beispiel #29
0
void get_feedback(void){
    FB = pin_read(FB_PIN);
}
Beispiel #30
0
int16_t main(void) {
	init_clock();
	init_timer();
	init_pin();
	init_oc();
	init_ui();

	InitUSB();							  // initialize the USB registers and serial interface engine
	while (USB_USWSTAT!=CONFIG_STATE) {	 // while the peripheral is not configured...
		ServiceUSB();					   // ...service USB requests
	}

	// Configure Interrupts on the pic
	IEC1bits.CNIE = 1;
	CNEN1bits.CN2IE = 1;
	IFS1bits.CNIF = 0;

	IEC0bits.OC1IE = 1;
	IFS0bits.OC1IF = 0;
	timer_enableInterrupt(&timer1);
	timer_lower(&timer1);
	timer_enableInterrupt(&timer2);
	timer_lower(&timer2);
	timer_enableInterrupt(&timer4);
	timer_lower(&timer4);
	timer_enableInterrupt(&timer5);
	timer_lower(&timer5);



	// Configure Pins
	inPin0 = &A[0];	
	pin_analogIn(inPin0);
	inPin1 = &A[1];	
	pin_analogIn(inPin1);
	inPin2 = &A[2];	
	pin_analogIn(inPin2);
	inPin3 = &A[3];	
	pin_analogIn(inPin3);
	inPin4 = &A[4];	
	pin_analogIn(inPin4);

	irPin = &A[5];	
	pin_analogIn(irPin);

	outPin = &D[6];
	pin_digitalOut(outPin);
	oc_pwm(&oc1, outPin, NULL, 10, (uint16_t)(0));		// write to D2 with a 10Hz PWM signal
	pin_write(outPin, 10000);	//duty doesn't matter, really. 

	redPin = &D[7];
	pin_digitalOut(redPin);
	oc_pwm(&oc2, redPin, NULL, 100, (uint16_t)(0));	
	greenPin = &D[10];
	pin_digitalOut(greenPin);
	oc_pwm(&oc3, greenPin, NULL, 100, (uint16_t)(0));	
	bluePin = &D[8];
	pin_digitalOut(bluePin);
	oc_pwm(&oc4, bluePin, NULL, 100, (uint16_t)(0));	

	pingPin = &D[4];
	pin_digitalOut(pingPin);
	oc_pwm(&oc5, pingPin, &timer3, 40000, 0);
	receivePin = &D[12];
	pin_digitalIn(receivePin);

	// Motor controller pins
	dirPin = &D[0];
	pin_digitalOut(dirPin);
	nSleepPin = &D[3];
	pin_digitalOut(nSleepPin);
	pin_write(nSleepPin, 1);
	stepPin = &D[2];
	pin_digitalOut(stepPin);

	testPin = &D[13];
	pin_digitalOut(testPin);

	timer_setFreq(&timer1, 100);


	while (1) {
		ServiceUSB(); // service any pending USB requests


		
		irVoltage = pin_read(irPin);
		if (irVoltage < 40000){
			dist = 32768;
		}
		if (irVoltage >= 40000){
			dist = 32900;
		}


		if (dist != stepCount) {
			changeFlag += 1;
		} else {
			changeFlag = 0;
		}

		if (changeFlag >= 3){
			changeFlag = 0;
			motorControl(dist);
		}


		if (touching0 == 10){
			greenTarget = 40000;
			redTarget = 60000;
			blueTarget = 0;
			if (currentPetal == 0){
				greenTarget = 0;
				redTarget = 0;
				blueTarget = 0;
			}
			currentPetal == 0;
		}
		if (touching1 == 11){
			greenTarget = 20000;
			redTarget = 20000;
			blueTarget = 20000;
			if (currentPetal == 1){
				greenTarget = 0;
				redTarget = 0;
				blueTarget = 0;
			}
			currentPetal == 1;
		}
		if (touching2 == 12){
			greenTarget = 0;
			redTarget = 60000;
			blueTarget = 40000;
			if (currentPetal == 2){
				greenTarget = 0;
				redTarget = 0;
				blueTarget = 0;
			}
			currentPetal == 2;
		}
		if (touching3 == 13){
			greenTarget = 0;
			redTarget = 60000;
			blueTarget = 0;
			if (currentPetal == 3){
				greenTarget = 0;
				redTarget = 0;
				blueTarget = 0;
			}
			currentPetal == 3;
			
		}
		if (touching4 == 14){
			greenTarget = 60000;
			redTarget = 0;
			blueTarget = 0;
			if (currentPetal == 4){
				greenTarget = 0;
				redTarget = 0;
				blueTarget = 0;
			}
			currentPetal == 4;

		}
		if (greenDuty < greenTarget) {
			greenChange = 1;
		} else if (greenDuty > greenTarget) {
			greenChange = -1;
		} else {
			greenChange = 0;
			onTarget += 1;
		}
		if (redDuty < redTarget) {
			redChange = 1;
		} else if (redDuty > redTarget) {
			redChange = -1;
		} else {
			redChange = 0;
			onTarget += 1;
		}
		if (blueDuty < blueTarget) {
			blueChange = 1;
		} else if (blueDuty > blueTarget) {
			blueChange = -1;
		} else {
			blueChange = 0;
			onTarget += 1;
		}
		greenDuty += greenChange;
		redDuty += redChange;
		blueDuty += blueChange;
		pin_write(greenPin, greenDuty);
		pin_write(redPin, redDuty);
		pin_write(bluePin, blueDuty);


		/*
		// fade on when touched
		if (touching0 == 10){
			if (greenOn == 0){
				greenChange = 1;
			}
			if (greenOn == 1){
				greenChange = -1;
			}
			redChange = -1;
			blueChange = -1;
		}
		if (touching1 == 11){
			if (redOn == 1){
				redChange = -1;
			}
			if (redOn == 0){
				redChange = 1;
			}
			blueChange = -1;
			greenChange = -1;
		}
		if (touching2 == 12){
			if (blueOn == 1){
				blueChange = -1;
			}
			if (blueOn == 0){
				blueChange = 1;
			}
			greenChange = -1;
			redChange = -1;
		}
		greenDuty = greenDuty + greenChange;
		if (greenDuty == MAX_INT){
			greenDuty = MAX_INT -1;
			greenOn = 1;
			greenChange = 0;
		}
		if (greenDuty == 0){
			greenDuty = 1;
			greenOn = 0;
			greenChange = 0;
		}
		redDuty = redDuty + redChange;
		if (redDuty == MAX_INT){
			redDuty = MAX_INT - 1;
			redOn = 1;
			redChange = 0;
		}
		if (redDuty == 0){
			redDuty = 1;
			redOn = 0;
			redChange = 0;
		}
		blueDuty = blueDuty + blueChange;
		if (blueDuty == MAX_INT){
			blueDuty = MAX_INT - 1;
			blueOn = 1;
			blueChange = 0;
		}
		if (blueDuty == 0){
			blueDuty = 1;
			blueOn = 0;
			blueChange = 0;
		}
		pin_write(greenPin, greenDuty);
		pin_write(redPin, redDuty);
		pin_write(bluePin, blueDuty);
		*/

		/*
		if (iteration > 10000) {
			ping();
			iteration = 0;
		}
		iteration += 1;
		*/
	}
}