Beispiel #1
0
int main (void)
{
  uint32_t analogValue;

  //Set segment A-G+DP pins as outputs
  GPIOSetDir( SEG_A_PORT, SEG_A_PIN, GPIO_OUTPUT);
  GPIOSetValue( SEG_A_PORT, SEG_A_PIN, LED_OFF);
  GPIOSetDir( SEG_B_PORT, SEG_B_PIN, GPIO_OUTPUT);
  GPIOSetValue( SEG_B_PORT, SEG_B_PIN, LED_OFF);
  GPIOSetDir( SEG_C_PORT, SEG_C_PIN, GPIO_OUTPUT);
  GPIOSetValue( SEG_C_PORT, SEG_C_PIN, LED_OFF);
  GPIOSetDir( SEG_D_PORT, SEG_D_PIN, GPIO_OUTPUT);
  GPIOSetValue( SEG_D_PORT, SEG_D_PIN, LED_OFF);
  GPIOSetDir( SEG_E_PORT, SEG_E_PIN, GPIO_OUTPUT);
  GPIOSetValue( SEG_E_PORT, SEG_E_PIN, LED_OFF);
  GPIOSetDir( SEG_F_PORT, SEG_F_PIN, GPIO_OUTPUT);
  GPIOSetValue( SEG_F_PORT, SEG_F_PIN, LED_OFF);
  GPIOSetDir( SEG_G_PORT, SEG_G_PIN, GPIO_OUTPUT);
  GPIOSetValue( SEG_G_PORT, SEG_G_PIN, LED_OFF);
  GPIOSetDir( SEG_DP_PORT, SEG_DP_PIN, GPIO_OUTPUT);
  GPIOSetValue( SEG_DP_PORT, SEG_DP_PIN, LED_OFF);

  GPIOSetDir( DIG1_PORT, DIG1_PIN, GPIO_OUTPUT);
  GPIOSetValue( DIG1_PORT, DIG1_PIN, 1);
  GPIOSetDir( DIG2_PORT, DIG2_PIN, GPIO_OUTPUT);
  GPIOSetValue( DIG2_PORT, DIG2_PIN, 1);

  //Set SW2/SW3 pins as inputs
  GPIOSetDir( SW2_PORT, SW2_PIN, GPIO_INPUT);
  GPIOSetDir( SW3_PORT, SW3_PIN, GPIO_INPUT);

  //Extra, turn buzzer off
  GPIOSetDir( BUZZ_PORT, BUZZ_PIN, GPIO_OUTPUT);
  GPIOSetValue( BUZZ_PORT, BUZZ_PIN, BUZZ_OFF);

  //Initialize ADC peripheral and pin-mixing
  ADCInit(4500000);  //4.5MHz ADC clock

  //get initial value
  analogValue = getADC(AIN0);   //AIN0 = trimming pot for intensity

  while(1)
  {
    uint8_t outputValue;

    outputValue = convert00_99(getADC(AIN0));

    GPIOSetValue( DIG1_PORT, DIG1_PIN, 1);
    GPIOSetValue( DIG2_PORT, DIG2_PIN, 0);
    setSegment(outputValue / 10);
    delayMS(10);
    GPIOSetValue( DIG2_PORT, DIG2_PIN, 1);
    GPIOSetValue( DIG1_PORT, DIG1_PIN, 0);
    setSegment(outputValue % 10);
    delayMS(10);
  }

  return 0;
}
Beispiel #2
0
int main ( void ) {
	initADC();
	init_stdusart0( BAUD, DB8 | P_N | SB1 );
	init_timer0_ctc( T0_PRESCALER_1024, PIN_DISCONNECT, PIN_DISCONNECT );// initalize timer 0 in ctc mode with a 1024 prescale
	DDRD |= (1 << PORTD4) | (1 << PORTD5);                              //set status LED pins to outputs
	set_ocr0a( 108 );                                                    // compare match every 156 ticks, producing 10ms interrupts
	enable_interrupt_t0a();                                             //enable interrupt on timer0 channel A          
	static FATFS FATFS_Obj;                                             //file system descriptor
	disk_timerproc();                                                   //produce a base timer clock
	FIL logfile;       													//file descriptor for datalogging file
	FILINFO info;                                                       //file info structure
	DSTATUS status = disk_initialize(0);                                //initalize the SD card
	if( status & STA_NOINIT ) {                                         //check for an error
		printf( "Disk Error\n\r" );
		PORTD |= (1 << PORTD4);                                         //Set LED to Error
		PORTD &= ~(1 << PORTD5);
		while (1);
	}
	PORTD |= (1 << PORTD5);                                             //set LED to Success
	PORTD &= ~(1 << PORTD4);
	f_mount(0, &FATFS_Obj);                                             //mount the filesystem
	double vout = 0.0;
	unsigned photo = 0, therm = 0, in = 0;
	while(1) {
		_delay_ms(5000);             //delay 5 seconds
		PORTD |= (1 << PORTD4);      //turn on the writing status
		int res = f_stat( "/avr/datalog.txt", &info );    //find the length of the datalog file
		if(f_open(&logfile, "/avr/datalog.txt", FA_OPEN_ALWAYS | FA_WRITE) != FR_OK) { //open the datalog and create anew ifnot present
			printf("System Error"); 
			PORTD |= (1 << PORTD4);                        //Set LED to Error
			PORTD &= ~(1 << PORTD5);	
			while(1);
        }		
		if(res == FR_OK) f_lseek( &logfile, info.fsize ); //If the file existed seek to the end
		in = getADC(0);                                   //Log the values
		vout = 3.3 * (in/1023.0);
		photo = (vout*10000.0)/(3.3-vout);
		printf( "Photo: %u ohms(%u raw) ", photo, in );
		f_printf( &logfile, "Photo: %u ohms(%u raw) ", photo, in );
		in = getADC(1);
		vout = 3.3 * (in/1023.0);
		therm = (vout*10000.0)/(3.3-vout);
		printf( "Therm: %u ohms(%u raw) \r\n", therm, in );
		f_printf( &logfile, "Therm: %u ohms(%u raw)\n", therm, in );
		f_close( &logfile );       //close the file
		PORTD &= ~(1 << PORTD4);   //off with the writing status
	}
	return 0;
}
//MCP3004 4-chanell SPI 10bit ADC...(only 8bits used) 
void SPIADCworker(void)
{
	unsigned char token, instruction, chanel, fInst=0,fb=0,bf=0;
	initSPI();
	SSP2BUF = 0xFD;
	enableTS;
	while (1)
	{
		while(PORTCbits.RC0 ==0)//CS LOW
 	  	{
  	 		if(SSP2STATbits.BF)	// we received something :)
			{
				SSP2STATbits.BF=0;
				bf=1;
				if(fb==0)
					{
					if(SSP2BUF==1)fb=1;
					SSP2BUF=0;	
					}
				else if(fb==1)
				{
					chanel = SSP2BUF &0b00110000;
					chanel = chanel>>4;
					SSP2BUF = getADC(chanel);
				}
			
			}
		}
Beispiel #4
0
int main ( void ) {
    // Initalize the a2d converter and the servo controller
    initADC();
    init_timer1_servos();

    // Forever run the servos
    while (1) {
        unsigned short dist = calcgp2d12(getADC(0));
        if(dist > 15) {
            // If the distance is greater than 15 centimeters, move forward
            set_servo_1a(1000);
            set_servo_1b(2000);
        } else {
            // If not, we have found an obstical!  Reverse and turn....
            set_servo_1a(2000);
            set_servo_1b(1000);
            _delay_ms(1500);

            // Spin for 1 second
            set_servo_1a(2000);
            set_servo_1b(2000);
            _delay_ms(750);
        }
    }
    return 0;
}
//this loop services user input and passes it to be processed on <enter>
int main(void){

   CLKDIVbits.RCDIV0=0; //clock divider to 0
   AD1PCFG = 0xFFFF;    // Default all pins to digital
   OSCCONbits.SOSCEN=0; //Oscilator setup, registar-OSCON bits-SOSCEN
   MODE_LED_DIR = 0;    //Mode LED set as output
   VREG_DIR =0;       //VREG is set as output
   VREG_EN = 1;       //Sets the VREG pin to 1, turns on the Voltage regulators.
   MODE_LED = 1;    //Turns the MOD LED 0N

   InitializeUART1(); //Initialize UART1
   initADC();         //Initialise ADC  

   unsigned int voltage;

   /////FOREVER///LOOP//////////
   while(1)
   {
      if(UART1RX() == 'a')  //Checks if the recived byte is 'a' if so it sends the two RAW bytes form ADC
      {
         voltage = getADC(); //reads the ADC pin
         UART1TX(voltage>>8); //seds the top byte of ADC to UART
         UART1TX(voltage);    //sends the bottom byte of ADC to UART
      }   
   }
Beispiel #6
0
unsigned int getCurrentCode() {
	unsigned int in = getADC(0);

	unsigned int best = 0;
	unsigned int bestDist = 0xffff;
	for (int i=0;i<6;i++) {
		int dist = in-adc2code[i].adc;
		if (dist < 0) {
			dist = -dist;
		}

		if (dist < bestDist) {
			best = adc2code[i].code;
			bestDist = dist;
		}
	}

	if (best != 0 || bestDist >= 10) {
		fprintf(stdout, "adc:%d code:%d dist:%d\n", in, best, bestDist);
	}

	if (bestDist < 100) {
		return best;
	} else {
		return 0;
	}
}
Beispiel #7
0
//发送数据, 最后可能出现问题点的地方
void putDate()
{
  //status=1;
  reset_value();
  printf("AT+CIPSEND=60\r\n");//发送10个字符
  
  do
  {

    ptr1 = putstrstr(RxBuffer1, sipsendrs);  //判断是否存在Linked 表示 还没连接成功  +i 
    ptr2 = putstrstr(RxBuffer1, sipsendretn3);  //
    ptr3 = putstrstr(RxBuffer1, cipEnd2); //监控服务器是否断开
    if(ptr2 !=NULL )
    {
      status=0;
      //types=2;
    }
    if(ptr1 !=NULL )
    {
      Refresh_WWDG_Window();
      status=0;
    } 
    if(ptr3 !=NULL )
    {
      restart();//重启MCU
    } 
     
    
  }while(status);
  
  //Refresh_WWDG_Window();
  /**/
  
//  Delayms(10);
  Refresh_WWDG_Window();
  ////暂时定数据
 // char *datas="set,12345,3.7V,0.2A,7777777777777777";
 // unsigned char *pIDStart=(unsigned char *)(ID_BaseAddress); 
   
    reset_value();
    getADC();
     //printf("set,123123,123123mV,123123mA,123123Tc,777777777111111111111177" );
    printf("set,123123,%d,%d,%d,7777777771111111111111777777777777777777777777777777777",stmsV,stmsI,stmsIADC,tci);//发送数据
    do
    {
      ptr1 = putstrstr(RxBuffer1, sipsendretn);  //判断是否存在服务器返回错误 sipsendretn sipsendretn
      ptr2 = putstrstr(RxBuffer1, retrunok);  //判断是否存在OK  
      ptr3 = putstrstr(RxBuffer1, sipsendretn2);
      if(ptr1 !=NULL || ptr3 != NULL)
      {
        status=0;
      }
      
    }while(status);
  
}
Beispiel #8
0
/**
 * @brief Streams timestamp, adcval, potmv, and potangle to PC w/ USART
 * Transmits timestamps, ADC value in counts, pot output in millivolts, and pot angle
 * in degrees over the serial port to the screen in the Terminal.
 *
 * @param channel The ADC channel to read from
 */
void ADCToSerial(int channel) {
	cli(); //stop interrupts
	unsigned int time = timer0Count;
	sei(); // start interrupts
	unsigned int adcval = getADC(channel);
	unsigned int potmv = (5000.0 * adcval)/1023.0; //calc pot millivolts todo use defined voltage
	unsigned int potangle = (300.0 * adcval)/1023.0; // calc pot angle todo use defined angle

	printf("%.2f,%u,%u,%u\n\r", time/100.0, adcval, potmv, potangle);
}
Beispiel #9
0
int GetPressure()
{
	// Slegio daviklis butinai turi but uzmaitintas 5v lygiai
	float a=(((getADC(ADC_PRESSURE_SENSOR)*ADC_DALIKLIO_DAUGIKLIS)/0.008) -21.2)/1;
	
	if (a<0)
	return 0;
	else
	return (int)a;
}
Beispiel #10
0
/**
 * @brief Generates signals w/particular duty cycles set by pot
 *
 * Also reads buttons 5-7 to determine which frequency to output
 *
 * @param channel The ADC channel to read the pot from
 */
void signalGeneratorMain(int channel) {
	unsigned int adcval = getADC(channel);
	float dutyCycle = (100.0 * adcval) / 1023.0; // calc dudy cycle
	//printf("dutyCycle %f\n\r",dutyCycle);

	// storing button states
	static unsigned whichButton = 5;
	static unsigned b5LastState = 2;
	static unsigned b6LastState = 1;
	static unsigned b7LastState = 1;

	static unsigned freq = 0; // store frequency
	// read buttons
	unsigned char b5 = PINDbits._P5;
	unsigned char b6 = PINDbits._P6;
	unsigned char b7 = PINDbits._P7;
	//switch frequency based on which button was last pressed
	if (b5LastState != b5) {
		whichButton = 5;
		b5LastState = b5;
		setFrequencyForPostScale(1);
		freq = 1;
	} else if (b6LastState != b6) {
		whichButton = 6;
		b6LastState = b6;
		setFrequencyForPostScale(20);
		freq = 20;
	} else if (b7LastState != b7) {
		whichButton = 7;
		b7LastState = b7;
		setFrequencyForPostScale(100);
		freq = 100;
	}

	// while we haven't counted up for the full duty cycle high time, keep pin high
	while (timer2Count < dutyCycle) {
		PORTBbits._P3 = 1;
		// Prints the duty cycle, frequency, state, and pot value to the serial port
		printf("%.2f,%u,%u,%u\n\r", dutyCycle, freq, 1, adcval);
	}
	//now we've hit the point where the pin needs to go low
	// so set the pin low until we are done with this cycle
	while ((timer2Count > dutyCycle) && (timer2Count < 100)) {
		PORTBbits._P3 = 0;
		// Prints the duty cycle, frequency, state, and pot value to the serial port
		printf("%.2f,%u,%u,%u\n\r", dutyCycle, freq, 0, adcval);
	}
	if (timer2Count > 99) { // after period completes for one high low cycle, reset
		timer2Count = 0;  // reset timers
	}

}
Beispiel #11
0
/**
 * @brief Streams timestamp and ADC values to the serial port for 1 second
 * Transmits timestamps, ADC value in counts
 * in degrees over the serial port to the screen in the Terminal.
 *
 * @param channel The ADC channel to read
 */
void ADCToSerialPart7(int channel) {
	cli(); //stop interrupts
	unsigned int time = timer0Count;
	sei(); // start interrupts
	unsigned int adcval = getADC(channel);
	static int lastTimerCount = -1; // store the last timer count, inits to something invalid
	// print data for 225 runs (1 second of logging)
	if(timer0Count <225 && lastTimerCount !=time){
		printf("%.4f,%u\n\r", time*0.00444, adcval);
		lastTimerCount = time;
	}

}
Beispiel #12
0
int main ( void ) {
	init_stdusart0(51, DB8 | P_N | SB1);  //init stdio uart at 19.2k baud 8N1 (51 is ubrr value for 19.2k at 16 MHz)
	initADC();                            //initalize the A2D converter
	uint16_t channelnum;                  //create 2 16 bit variables
	uint16_t value;
	printf("AVR ADC Test Program\r:");    //print a welcome message
	while (1) {                           //repeat forever
		scanf("%d", &channelnum);         //get the requested channel number
		value = getADC((uint8_t)(channelnum & 0x07)); //get the value of that channel  channel num is 16 bits, we need the lower three.  mask the non required bits
	    printf("Channel: %d = %d\r:", channelnum, value); //print the result
	}
	return 0;
}
Beispiel #13
0
/*
 * @brief Check the "battery voltage" and display it
 * @params None
 * @retval None
 */
static void check_battery(void) {
  // Grab the ADC value, convert to uV and then to battery voltage
  uint16_t adcVal = getADC();
  uint32_t uVoltage = adcVal * ADC_GRAIN;
  batVoltage = 7.21*(uVoltage/ADC_MULTIPLIER);

  // Check for voltage threshold and change the LED accordingly
  if (batVoltage <= BAT_THRESHOLD) {
    GPIOB->ODR &= ~(1 << 11);
    GPIOB->ODR |= (1 << 10);
  } else {
    GPIOB->ODR &= ~(1 << 10);
    GPIOB->ODR |= (1 << 11);
  }
}
Beispiel #14
0
uint16_t getHandleTemperature() {
	// We return the current handle temperature in X10 C
	// TMP36 in handle, 0.5V offset and then 10mV per deg C (0.75V @ 25C for example)
	// STM32 = 4096 count @ 3.3V input -> But
	// We oversample by 32/(2^2) = 8 times oversampling
	// Therefore 32768 is the 3.3V input, so 0.201416015625 mV per count
	// So we need to subtract an offset of 0.5V to center on 0C (2482*2 counts)
	//
	uint16_t result = getADC(0);
	if (result < 4964)
		return 0;
	result -= 4964;    //remove 0.5V offset
	result /= 10;    //convert to X10 C
	return result;

}
Beispiel #15
0
void main (void)
{
	unsigned char command;
	unsigned int adc;

	while(1) {
		//wait_bit_time();
		//getADC(0);	//Garbage value (hack)
		adc = getADC(0);
		//printf("ADC: %u\r\n", adc);
		
		
		if(adc <= BACKGROUND0_B) {
			//printf("ADC: %u\r\n", adc);
			printf("Start receive\r\n");
			command = yap_receive(BACKGROUND0_B);
			printf("Command: %u\r\n", command);
		}
	}
}
Beispiel #16
0
static unsigned short function_adc_status(char* buffer, int bufsize, char* parameters) {
    #if ADC_CHANNELS > 0
        int i=atoi(parameters);
        if (i<ADC_CHANNELS) {
            // wait until no other thread executes this function
            while (isBusy);
            isBusy=1;
            // read ADC input
            int value=getADC(i);
            isBusy=0;
            // print the result
            #ifdef EXT_AREF
               return snprintf_P(buffer, bufsize, PSTR("0x0%03X = %.2f V"),value,getAREF()*value);
            #else
                return snprintf_P(buffer, bufsize, PSTR("0x0%03X"),value);
            #endif
        }
    #endif
    strcpy_P(buffer,PSTR("n.a."));
    return 4;
}
Beispiel #17
0
int getCurrentAngle(enum Axle axle)
{
	return getADC(axle);
}
Beispiel #18
0
void reportADC() {

    m_red(ON);
    m_green(ON);


    m_red(OFF);
    m_green(OFF);

    char rx_buffer; //computer interactions
    int index = 0;
    int maxval = 0;
    float deg = 0.0;
    float diff = 0.0;

    
    

    getADC();
    index = 0;
    maxval = 0;
    //m_green(TOGGLE);
    for(int i = 0; i < 8; i++) {
        if (ADCarr[i] > maxval) {
            index = i;
            maxval = ADCarr[i];
        }
    }
    switch (index) {
        case 0:
        diff = ADCarr[0] - ADCarr[6];
        deg = exp(-1.0*fabs(((float)diff))/400.0);
        //m_green(ON);
        //m_red(OFF);
        break;
        case 6:
        diff = ADCarr[6] - ADCarr[0];
        deg = exp(-1.0*fabs(((float)diff))/400.0);
        //m_green(OFF);
        //m_red(ON);
        break;
        
    }
    //while(!m_usb_rx_available());     //wait for an indication from the computer
        //rx_buffer = m_usb_rx_char();     //grab the computer packet

        //m_usb_rx_flush();                 //clear buffer

        //if(rx_buffer == 1) {             //computer wants ir buffer
            //write ir buffer as concatenated hex:  i.e. f0f1f4f5
            m_usb_tx_int(ADCarr[0]);
            m_usb_tx_char('\t');
            m_usb_tx_int(ADCarr[1]);
            m_usb_tx_char('\t');
            m_usb_tx_int(ADCarr[2]);
            m_usb_tx_char('\t');
            m_usb_tx_int(ADCarr[3]);
            m_usb_tx_char('\t');
            m_usb_tx_int(ADCarr[4]);
            m_usb_tx_char('\t');
            m_usb_tx_int(ADCarr[5]);
            m_usb_tx_char('\t');
            m_usb_tx_int(ADCarr[6]);
            m_usb_tx_char('\t');
            m_usb_tx_int(ADCarr[7]);
            m_usb_tx_char('\t');
            m_usb_tx_int(index);
            m_usb_tx_char('\t');
            m_usb_tx_int((int)(deg*100));
            m_usb_tx_char('\t');

        //}
        m_usb_tx_char('\n');  //MATLAB serial command reads 1 line at a time
        //}
}
Beispiel #19
0
/*char isStuck() {
    m_wait(100);
    //localize(data);
    distfrombound = data[1] + ((float)BOUNDARYTHRESHOLD)*sin((data[2]+90.0)*3.14/180.0*-1.0);
    if (distfrombound > 60.0 || distfrombound < -60.0) {
        return 1;
    }
    m_usb_tx_int((int)distfrombound);
    m_usb_tx_char('\n');
}

long loccounter = 0;
float prevx = 0.0;
float prevy = 0.0;
*/
int main(void)
{
	//goal side
	clear(DDRB,1);
	clear(PORTB,1);
	if (check(PINB,1)) {
		goal = 1;
	}
	
    set(DDRB,0);
    set(PORTB,0);
    set(DDRD,5);
    set(DDRD,3);
    //wireless stuffs
    m_bus_init();
    
    m_rf_open(CHANNEL, RXADDRESS, PACKET_LENGTH);

    int counter = 0;
    //
    
    //m_num_init();
    int flag;
    
    m_clockdivide(0);
    
    m_disableJTAG();
    
    //TIMER 0: For Controlling the solenoid
//     
//     set(TCCR0B, WGM02);
//     set(TCCR0A, WGM01);
//     set(TCCR0A, WGM01);
//     
//     set(TCCR0A, COM0B1);
//     clear(TCCR0A, COM0B0);
//     
//     set(TCCR0B, CS02);
//     set(TCCR0B, CS01);
//     set(TCCR0B, CS00);
//     
    set(DDRB,7);
    
//     OCR0A = 0xFF;
//     OCR0B = 0xff;
//     
    //TIMER 1: For Controlling the left wheel
    
    set(TCCR1B, WGM13);
    set(TCCR1B, WGM12);
    set(TCCR1A, WGM11);
    set(TCCR1A, WGM10);
    
    set(TCCR1A, COM1B1);
    clear(TCCR1A, COM1B0);
    
    clear(TCCR1B, CS12);
    clear(TCCR1B, CS11);
    set(TCCR1B, CS10);
    
    set(DDRB,6);
    
    OCR1A = 0xFFFF;
    OCR1B = 0;
    
    //TIMER 3: For Controlling the right wheel
    //up to ICR3, clear at OCR3A & set at rollover
    
    set(TCCR3B, WGM33);
    set(TCCR3B, WGM32);
    set(TCCR3A, WGM31);
    clear(TCCR3A, WGM30);
    
    set(TCCR3A, COM3A1);
    clear(TCCR3A, COM3A0);
    
    clear(TCCR3B, CS32);
    clear(TCCR3B, CS31);
    set(TCCR3B, CS30);
    
    ICR3 = 0xFFFF;
    OCR3A = 0;
    
//     //Set TCNT0 to go up to OCR0A
//     clear(TCCR0B, WGM02);
//     set    (TCCR0A, WGM01);
//     clear(TCCR0A, WGM00);
//     
//     // Don't change pin upon hitting OCR0B
//     clear(TCCR0A, COM0A1);
//     clear(TCCR0A, COM0A0);
//     
//     // Set clock scale to /1024
//     set(TCCR0B, CS02);
//     clear(TCCR0B, CS01);
//     set(TCCR0B, CS00);
//     
//     // Set Frequency of readings to 1/SAMPLERATE; dt = 1/SAMPLERATE
//     OCR0A = (unsigned int) ((float) F_CPU / 1024 / REPORTRATE);
//      OCR0B = 1;
    
    // Set up interrupt for reading values at sampling rate

    
    //Pin for controlling solenoid pulse
    set(DDRB,7);
    
    //Pins for controlling speed of left and right wheel
    set(DDRB,6);
    set(DDRC,6);
    
    //Pins for determining direction of wheels
    set(DDRB,2);
    set(DDRB,3);
    
    //Blue LED for Comm Test
    //set(DDRB,5);
    
    //ADC's
    sei();                    //Set up interrupts
    set(ADCSRA, ADIE);
    
    clear(ADMUX, REFS1);    //Voltage reference is AR pin (5V)
    clear(ADMUX, REFS0);    //^
    
    set(ADCSRA, ADPS2);    //Set scale to /128
    set(ADCSRA, ADPS1);    //^
    set(ADCSRA, ADPS0);    //^
    
    set(DIDR0, ADC0D);    //Disable digital input for F0
    set(DIDR0, ADC1D),
    set(DIDR0, ADC4D);
    set(DIDR0, ADC5D);
    set(DIDR0, ADC6D);
    set(DIDR0, ADC7D);
    set(DIDR2, ADC8D);
    set(DIDR2, ADC9D);
    
    set(ADCSRA, ADATE);    //Set trigger to free-running mode
    
    chooseInput(0);
    
    set(ADCSRA, ADEN);    //Enable/Start conversion
    set(ADCSRA, ADSC);    //^
    
    set(ADCSRA, ADIF);    //Enable reading results
    
    
    //Limit Switch stuffs
//     clear(DDRB,0); //set to input, RIGHT LIMIT SWITCH
//     clear(DDRB,1); //set to input, LEFT LIMIT SWITCH
//     
//     clear(PORTB,0); //disable internal pull up resistor
//     clear(PORTB,1); //disable internal pull up resistor
    
    //int state; // state variable
    state = 0; //set state
    play = 0;
    long count = 0;
    
    if (state == 70) {
            m_usb_init(); // connect usb
            while(!m_usb_isconnected());  //wait for connection
    }

    //m_bus_init();
    m_wii_open();
    //m_usb_init();
    m_red(ON);
    local_init();
    localize(data);
    m_red(OFF);

    //set(TIMSK0, OCIE0A);
    while(1)
    {
		if (play) {m_red(ON);}
		else {m_red(OFF);}
// 		m_wait(100);
// 		m_red(TOGGLE);
// 		localize(data);
        /*if (loccounter == LOCCOUNT) {
            if (sqrt((data[0]-prevx)*(data[0]-prevx)+(data[1]-prevy)-(data[1]-prevy)) < 1.0) {
                m_red(ON);
                reverse();
                m_wait(100);
                state = 6;
            }
            else {
                m_red(OFF);
                state = 2;
            }
            prevx = data[0];
            prevy = data[1];
            loccounter = 0;
        }*/
        //loccounter++;
//         localize(data);
//         locdata[1] = (char)data[0];
//         locdata[2] = (char)data[1];
//         toggle(PORTD,3);
        changedState = 0;
        angle_dif = 0;
       
        //Detect weather we have the puck
        getADC();
        //if (!play) game_pause();
        if (ADCarr[7] > 500) {
            //set(PORTD,5);
			//set(PORTD,5);
            iHaveThePuck = 1;
			m_green(ON);
			if (play && goal == A) state = 3;
			if (play && goal == B) state = 4;
        } else {
            //clear(PORTD,5);
            iHaveThePuck = 0;
			m_green(OFF);
			if (play) state = 2;
        }
       
        if(iHaveThePuck && state == 2) {
            //set(PORTB,5);
			//drive_to_goalA();
        }
        else {
            //clear(PORTB,5);
            //if (state != 0) state = 2;
        }
//         if(isStuck()) {
//             //set(PORTD,5);u
//         }
//         else {
//             //clear(PORTD,5);
//         }

        //localize(data);
       
//         if (check(PINB,0)) {
//             set(PORTD,5);
//             state = 0x1A;
//         } else {
//             clear(PORTD,5);
//             state = 2;
//         }
    
		if (!play) state = buffer[0];
        //switch states
        switch (state) {
           
            case -2:
            getADC();
            if (ADCarr[0] > 500) {
                m_green(ON);
            }
            else {m_green(OFF)}
            break;
           
            case -1: //test Limit switches
                //m_green(ON);
                if (check(PINB,1)) {
                   
                    m_green(ON);
                }
               
                else if (check(PINB,0)) {
                   
                    m_red(ON);
                }
               
                else {
                    m_red(OFF);
                    m_green(OFF);
                }
               
            break;

            case 0:
            //drive_to_point2(-100,0);
            game_pause();
            break;
           
            case 1:
            findPuck();
            break;
           
            case 2:
            //m_red(ON);
			if (!iHaveThePuck) {
				if (play)
            drive_to_puck();
			}
            break;
           
            case 3:
			if (play)
            drive_to_goalA();
            break;
           
            case 4:
			if (play)
            drive_to_goalB();
            break;    
           
            case 5:
           
            getADC();
            if (ADCarr[7] > 500) {
                //set(PORTD,5);
            } else {
                //clear(PORTD,5);
            }
           
            break;
           
            case 6:
            if (data[2] > 0) {
                rotate(RIGHT,1);
            } else {
                rotate(LEFT,1);
            }
            break;
			
            case 7:
		    drive_to_point2(-50,0);
		    break;
           
           
            case 0xA0:
            comm_test();
            break;
           
            case 0xA1:
            play = 1;
            drive_to_puck();
            break;
           
            case 0xA2:
			play = 0;
            game_pause();
            break;
           
            case 0xA3:
			play = 0;
            game_pause();
            break;
           
            case 0xA4:
			play = 0;
            game_pause();
            break;
           
            case 0xA6:
			play = 0;
            game_pause();
            break;
           
            case 0xA7:
            game_pause();
            break;
           
            case 69:
                set(PORTB,2);
                set(PORTB,3);
                OCR1B = OCR1A;
                OCR3A = ICR3;
                break;
               
            case 70:
                reportADC();
                break;
           
            default:
            game_pause();
            break;
        }
        
    }
}
int main(void)
{
char temp, i;
LCD_Initialize();
DDRB = 0b00000000;
PORTB = 0b00001111;

DDRA = 0xFF;
ADC_Init();
int value = 0;
int calculations = 0;

	char dzialanie = 0;

	
	int digit = 0;




	do{

	int digit  = getADC(0);

	char sw0 = PINB & 0b00000001;
	char sw1 = PINB & 0b00000010;
	if(sw0 != 0b00000001) {
		state++;
		_delay_ms(300);
	}
	

	  char str[15];


	  sprintf(str, "%15d", lastValue);
	LCD_GoTo(1,0);
	LCD_WriteText(str);


	switch(state){
		case 0:		
			if(sw1 != 0b00000010){
				setNewValue(mappingLogToLinear(digit, digitMap, 10));			
				_delay_ms(300);
			}
				sprintf(str, "%15d", mappingLogToLinear(digit, digitMap,10));
				LCD_GoTo(1,1);
				LCD_WriteText(str);	
			break;
		case 1:
			if(sw1 != 0b00000010){
				setSign(mappingLogToLinear(digit, signMap, 2));
				power = 0;				
				_delay_ms(300);
			}
				switch(mappingLogToLinear(digit, signMap,2)){
					case 0:
					LCD_GoTo(1,1);
					LCD_WriteText("-");
					break;
					case 1:
					LCD_GoTo(1,1);
					LCD_WriteText("+");
					break;
				}
			break;
		case 2:
			if(sw1 != 0b00000010){
				doCalculations(mappingLogToLinear(digit, expressionMap, 4));
				power = 0;
				newValue=0;
				state = 0;			
				_delay_ms(300);
			}
				
				switch(mappingLogToLinear(digit, expressionMap,4)){
					case 0:
					LCD_GoTo(1,1);
					LCD_WriteText("+");
					break;
					case 1:
					LCD_GoTo(1,1);
					LCD_WriteText("-");
					break;
					case 2:
					LCD_GoTo(1,1);
					LCD_WriteText("*");
					break;
					case 3:
					LCD_GoTo(1,1);
					LCD_WriteText("/");
					break;
				}
			break;
		}


/*
	char sw0 = PINB & 0b00000001;
	char sw1 = PINB & 0b00000010;
	char sw2 = PINB & 0b00000100;
	char sw3 = PINB & 0b00001000;

	if(sw0 != 0b00000001) value++;
	if(sw1 != 0b00000010) value--;

	if(sw2 != 0b00000100) {
		if(dzialanie == 0) calculations += value;
		if(dzialanie == 1) calculations -= value;
		if(dzialanie == 2) calculations /= value;
		if(dzialanie == 3) calculations *= value;
			value = 0;
	}


	if(sw3 != 0b00001000) {
		dzialanie++;
		dzialanie = dzialanie % 4;
	}




	  char str[15];


	  sprintf(str, "%15d", calculations);
	LCD_GoTo(1,0);
	LCD_WriteText(str);

	  sprintf(str, "%15d", value);
	LCD_GoTo(1,1);
	LCD_WriteText(str);
	_delay_ms(300);

	
	if(dzialanie == 0){
		LCD_GoTo(0,0);
		LCD_WriteText("+");
	}

	if(dzialanie == 1){
		LCD_GoTo(0,0);
		LCD_WriteText("-");
	}
	
	if(dzialanie == 2){
		LCD_GoTo(0,0);
		LCD_WriteText("/");
	}
	
	if(dzialanie == 3){
		LCD_GoTo(0,0);
		LCD_WriteText("*");
	}*/
	}while(1);

return 0;
}
Beispiel #21
0
int main (void)
{
  uint32_t analogValue;
  uint8_t wantedDutyCycle, wantedDutyCycleB=100;
  uint8_t state = 0;

  //Set LED1-LED8 pins as outputs
  GPIOSetDir( LED1_PORT, LED1_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED1_PORT, LED1_PIN, LED_OFF);
  GPIOSetDir( LED2_PORT, LED2_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED2_PORT, LED2_PIN, LED_OFF);
  GPIOSetDir( LED3_PORT, LED3_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED3_PORT, LED3_PIN, LED_OFF);
  GPIOSetDir( LED4_PORT, LED4_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED4_PORT, LED4_PIN, LED_OFF);
  GPIOSetDir( LED5_PORT, LED5_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED5_PORT, LED5_PIN, LED_OFF);
  GPIOSetDir( LED6_PORT, LED6_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED6_PORT, LED6_PIN, LED_OFF);
  GPIOSetDir( LED7_PORT, LED7_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED7_PORT, LED7_PIN, LED_OFF);
  GPIOSetDir( LED8_PORT, LED8_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED8_PORT, LED8_PIN, LED_OFF);

  //Set SW2/SW3 pins as inputs
  GPIOSetDir( SW2_PORT, SW2_PIN, GPIO_INPUT);
  GPIOSetDir( SW3_PORT, SW3_PIN, GPIO_INPUT);

  //Extra, turn buzzer off
  GPIOSetDir( BUZZ_PORT, BUZZ_PIN, GPIO_OUTPUT);
  GPIOSetValue( BUZZ_PORT, BUZZ_PIN, BUZZ_OFF);

  //Set RGB-LED pins as outputs
  GPIOSetDir( LEDB_PORT, LEDB_PIN, GPIO_OUTPUT);
  GPIOSetValue( LEDB_PORT, LEDB_PIN, LED_OFF);

  initPWM(1000);       //1000us = 1kHz PWM frequency
  updatePWM(0, 100);   //set 100% duty cycle for channel #0 (RED LED will be off)
  updatePWM(1, 100);   //set 100% duty cycle for channel #1 (GREEN LED will be off)
  startPWM();

  //Initialize ADC peripheral and pin-mixing
  ADCInit(4500000);  //4.5MHz ADC clock

  //get initial value
  analogValue = getADC(AIN0);   //AIN0 = trimming pot for intensity

  wantedDutyCycleB = 100;
  state = 0;

  while(1)
  {
    uint8_t loopCounter;
    uint16_t adcCounter;

    //Set BLUE LED output high
    GPIOSetValue( LEDB_PORT, LEDB_PIN, 1);

    //check if time to read analog input
    if (adcCounter++ > 100)
    {
      adcCounter = 0;

      //check push-button SW2
      if (GPIOGetValue(SW2_PORT, SW2_PIN) == SW_PRESSED)
      {
        state++;
        if (state > 2)
          state = 0;

        //wait until push-button is released
        while(GPIOGetValue(SW2_PORT, SW2_PIN) == SW_PRESSED)
          ;
      }

      //Set wanted duty cycle - valid numbers: 0..100 (low number = LED on more)
      wantedDutyCycle = getADC(AIN0) / 10;   //trimming pot

      //extra check to that range is valid
      if (wantedDutyCycle > 99)
        wantedDutyCycle = 99;

      switch(state)
      {
      case 0: updatePWM(0, wantedDutyCycle); break;
      case 1: updatePWM(1, wantedDutyCycle); break;
      case 2: wantedDutyCycleB = wantedDutyCycle;  break;
      default: state = 0;
      }
    }

    //Enter duty cycle generating loop
    for (loopCounter=0; loopCounter<100; loopCounter++)
    {
      //10 corresponds to 1kHz (100*10us), LED flickering starts at around 30-40Hz PWM frequency
      delayUS(10);
      if (loopCounter == wantedDutyCycleB)
        GPIOSetValue( LEDB_PORT, LEDB_PIN, 0);   //Set output low
    }
  }

  return 0;
}
Beispiel #22
0
void drive_to_puck() {
        getADC();
        index = 0;
        maxval = 0;
        for(int i = 0; i < 7; i++) {
            if (ADCarr[i] > maxval) {
                index = i;
                maxval = ADCarr[i];
            }
        }
        switch (index) {
            case 0:
                puckdistance = (log(((double) ADCarr[0])) * -1.0 * 89.64) + 664.58;
                diff = ADCarr[0] - ADCarr[6];
                deg = exp(-1.0*(fabs((float)diff))/40.0);
                turn(RIGHT,1.0,deg);
                //m_green(ON);
                //m_red(OFF);
                break;
            case 1:
                if (ADCarr[1] > 800 && ADCarr[2] > 800) {
                    rotate(LEFT,1);
                }else {
                turn(RIGHT,1.0,0.05);
                }
                break;
            case 2:
				if (ADCarr[1] > 800 && ADCarr[2] > 800) {
					rotate(LEFT,1);
					}else {
					turn(RIGHT,1.0,0);
				}
				break;
            case 3:
                if (ADCarr[2] > ADCarr[4]) {
                    rotate(RIGHT, 1);
                }
                else {
                    rotate(LEFT, 1);
                }
                break;
            case 4:
				if (ADCarr[4] > 800 && ADCarr[5] > 800) {
					rotate(LEFT,1);
				}
				else {
					turn(LEFT,1.0,0);
				}
				break;
            case 5:
				if (ADCarr[4] > 800 && ADCarr[5] > 800) {
					rotate(LEFT,1);
					}else {
					turn(LEFT,1.0,0.15);
				}
				break;
            case 6:
                puckdistance = (log(((double) ADCarr[0])) * -1.0 * 89.64) + 664.58;
                diff = ADCarr[6] - ADCarr[0];
                deg = exp(-1.0*(fabs((float)diff))/70.0);
                turn(LEFT,1.0,deg);
                //m_green(OFF);
                //m_red(ON);
                break;
            default:
                //m_red(ON);
                //m_green(ON);
                break;
        }
    //}
}
Beispiel #23
0
uint8_t getADC8 ( uint8_t channel ) {
	uint16_t o = getADC(channel);
	o >>= 2;
	return (o & 0xFF);
}
Beispiel #24
0
/*------------------MAIN FUNCTION------------------*/
int main(void)
{  
    __builtin_write_OSCCONL(2); // Enable secondary oscillator with unlock sequence
    T1CON = 0x8012; // Enable T1 from external oscillator (SECONDARY), pre-scaler of 8)
    T2CON = 0x8000;
    PR1 = 410;      // this value generates an interrupt every 100 milliseconds (Primary)

    /*------------------CONFIGURE INTERRUPTS------------------*/
    INTCON2bits.INT0EP = 0;     // interrupt on positive edge
    INTCON2bits.ALTIVT = 0;     // use primary IVT
    IPC0bits.T1IP = 4;          // set priority level to 4 (100)
    IFS0bits.T1IF = 0;          // initialize T1 flag to zero
    IEC0bits.T1IE = 1;          // enable the T1 timer interrupt source
    
    TRISBbits.TRISB2 = 0; // Used as Register Select for LCD
    initPMP();
    initLCD();
    
    setLCDG(0);
    putLCD(0b00000);
    putLCD(0b10001);
    putLCD(0b00000);
    putLCD(0b00100);
    putLCD(0b00000);
    putLCD(0b10001);
    putLCD(0b01110);
    putLCD(0);
    
    putLCD(0b00000);
    putLCD(0b10001);
    putLCD(0b00000);
    putLCD(0b00100);
    putLCD(0b00000);
    putLCD(0b00000);
    putLCD(0b11111);
    putLCD(0);
    
    putLCD(0b00000);
    putLCD(0b10001);
    putLCD(0b00000);
    putLCD(0b00100);
    putLCD(0b00000);
    putLCD(0b01110);
    putLCD(0b10001);
    putLCD(0);

    int Buf = 0;
    initADC();
    //TRISB = 0xFF00; // configure LED port as outputs
    char BufString[20];
    char BufString2[5];
    char BufString3[16];
    double voltage, vAvg, avgTime;
    int i, time;
    unsigned long bufAvg;
    int nAvg = 100;
    TMR1 = 0;
    /*------------------INFINITE LOOP------------------*/
    while(1)
    {
        vAvg = 0;
        voltage = 0;
        bufAvg = 0;
        time = 0;
        avgTime = 0;
        for(i=0;i<nAvg;i++)
        {
            TMR2 = 0;
            Buf = getADC(0);    // read channel 1 of ADC
            time = TMR2;
            voltage = Buf*3.3/1023;
            vAvg = vAvg + voltage;
            bufAvg = bufAvg + Buf;
            avgTime = avgTime + time;
        }
        vAvg = vAvg/nAvg;
        bufAvg = bufAvg/nAvg;
        avgTime = avgTime/nAvg/16/1000;
        if(myBOOLs.timer_flag == TRUE)
        {
            setCursor(1,0);
            putsLCD("Voltage: ");
            sprintf(BufString,"%.02f",vAvg);
            sprintf(BufString2,"%lu",bufAvg);
            sprintf(BufString3,"%.05f",avgTime);
            setCursor(1,9);
            putsLCD(BufString);
            setCursor(1,16);
            putsLCD(BufString2);
            putsLCD("   ");
            setCursor(2,0);
            putsLCD("Time: ");
            setCursor(2,6);
            putsLCD(BufString3);
            setCursor(2,14);
            putsLCD("ms");
            setCursor(2,19);
            if(bufAvg > 1023*2/3)
                putLCD(0);
            if(bufAvg < 1023*2/3 && bufAvg > 1023*1/3)
                putLCD(1);
            if(bufAvg < 1023*1/3 && bufAvg > 0)
                putLCD(2);
            myBOOLs.timer_flag = FALSE;
        }
    }
    return (EXIT_SUCCESS);
}
Beispiel #25
0
int main (int argc, char* argv[]){
	int i,k;
	float myTemp,myVolts;
	unsigned int periods, valueADC;

	initializeBoard();
/*
	setRS485ServoPosition(SERVO1, 0, 0);
	printf("Sending IFC to GPIB instruments on bridge %02x\n",GPIBBRIDGE1);
	i=resetGPIBBridge(GPIBBRIDGE1);
	printf("Status %d\n",i);
	delay(200);
	i=initializeK485(K485AMMETER,GPIBBRIDGE1);
	printf("Init K485\nStatus %d\n",i);
	i=initializeF8840(FLUKE8840,GPIBBRIDGE1);
	printf("Init Fluke 8840\nStatus %d\n",i);
	i=initSorensen120(SORENSEN120,GPIBBRIDGE1);
	printf("Init Sorensen\nStatus %d\n",i);
	i=initializeBK1696(RS232BRIDGE1);
	printf("Init BK1696 instrument #1\nStatus %d\n",i);

	i=getPVCN7500(OMEGA1,&myTemp);
	if (!i) printf("Omega 1 temperature = %.1f°\n",myTemp); else printf("Status %d\n",i);
	i=getPVCN7500(OMEGA2,&myTemp);
	if (!i) printf("Omega 2 temperature = %.1f°\n",myTemp); else printf("Status %d\n",i);

	i = getRS485AnalogRecorderPeriod(ANALOGRECORD, &periods);
	printf("Analog recorder sampling every %dmS\n",periods*16);
	for (k=0; k<4; k++){
	i=readRS485AnalogRecorder(ANALOGRECORD, k, 5.0, &myVolts, &myTemp);
	delay(100);
	printf("Analog recorder chan %d = %.2f ± %.2f\n",k,myVolts, myTemp);
	}
	
	i=getReadingK485(&myTemp, K485AMMETER,GPIBBRIDGE1);
	if (!i) printf("K485 reading = %E\n",myTemp);else printf("Status %d\n",i);
	delay(100);
	i=getReadingF8840(&myTemp, FLUKE8840,GPIBBRIDGE1);
	if (!i)	printf("Fluke 8840 reading = %E\n",myTemp);else printf("Status %d\n",i);

	for (k=0;k<8;k++){
	i=setVoltsBK1696(RS232BRIDGE1, (float) k * 1.2+1.1);
	delay(100);
	printf("Set Servo %d\t",k);
	setRS485ServoPosition(SERVO1, 0, k);
	getRS485ServoPosition(SERVO1,0,&i);
	printf("Return pos %d\n",i);
	delay (100);
	i=getReadingF8840(&myTemp, FLUKE8840,GPIBBRIDGE1);
	if (!i) printf("Fluke = %E\t",myTemp); else printf("Status %d\n",i);
	delay (100);
	i=getReadingF8840(&myTemp, FLUKE8840,GPIBBRIDGE1);
	if (!i) printf("Fluke = %E\n",myTemp);else printf("Status %d\n",i);
	}

	for (k=0; k<10; k++){
	myTemp = (float)k * 12.2;
	i = setSorensen120Volts(myTemp,SORENSEN120,GPIBBRIDGE1);
	printf("Setting Sorensen %.1f\t",myTemp);
	delay(200);
	i = getSorensen120Volts(&myVolts,SORENSEN120,GPIBBRIDGE1);
	i = getSorensen120Amps(&myTemp,SORENSEN120,GPIBBRIDGE1);
	printf("Measured: %.2fV\t %.3fA\t %.1fW\n",myVolts,myTemp,myVolts*myTemp);
	delay(200);
	}
	i = setSorensen120Volts(0.0,SORENSEN120,GPIBBRIDGE1);
	setRS485ServoPosition(SERVO1, 0, 0);
*/

for (i=0;i<8;i++){

	getADC(i,&valueADC);
	printf("ADC: %d\t",valueADC);
	delay(100);

}


	return 0 ;
}
u8 getVoltage(void)
{
    return ( gbVoltageTable[ (getADC(0)) >>4 ] );
}
Beispiel #27
0
void main (void) {
	vuint32_t i = 0;
	initModesAndClock(); /* Initialize mode entries and system clock */
	disableWatchdog(); /* Disable watchdog */
	initPeriClkGen(); /* Initialize peripheral clock generation for DSPIs */
	
	initADC();
	initLED();
	
	//can stuff	
	initDSPI_1();                /* Initialize DSPI_1 as Slave SPI and init CTAR0 */
	canSetup();
	
	initEnergizeButton();
	
	energizePacket.ID = ENERGIZE_ID;
	energizePacket.DATA.W[0] = 0xFFFFFFFF;
	energizePacket.DATA.W[1] = 0xFFFFFFFF;
	
	deenergizePacket.ID = DEENERGIZE_ID;
	deenergizePacket.DATA.W[0] = 0x00000000;
	deenergizePacket.DATA.W[1] = 0x00000000;
	
	torquePacket.ID = TORQUE_ID;
	speedPacket.ID = SPEED_ID;
	
	shutdownPacket.ID = SHUTDOWN_ID;
	shutdownPacket.DATA.W[0] = 0xDEADBEEF;
	shutdownPacket.DATA.W[1] = 0xDEADBEEF;
	
	/* Loop forever */
	while (1) 
	{
		prevEnergizeButton = energizeButton;
		getEnergizeButton();
		switch (currentState) {
			case NOT_ENERGIZED:
				if (!energizeButton && prevEnergizeButton) {
					currentState = ENERGIZED;
					canSend(energizePacket);
				}
				break;
			case ENERGIZED:
				if (!energizeButton && prevEnergizeButton) {
					currentState = NOT_ENERGIZED;
					canSend(deenergizePacket);
				} else {
					getADC();
					processAnalog();
					if (imp_count < 2 || torque0 < 20) {
						convertSpeed();
						convertTorque();
						if (MODE == 0) {
							canSend(speedPacket);
						} else {
							canSend(torquePacket);
						}
					} else {
						currentState = SHUTDOWN;
						canSend(deenergizePacket);
					}
				}
				break;
			case SHUTDOWN:
				canSend(shutdownPacket);
				SHUTDOWN_CIRCUIT = TRUE;
				break;
		}
		
		toLED(currentState);
		
		//canReceive();
		
		delay();
		i++;
	}
}
void UARTworker(void)
{
	unsigned char c,mode=0,addr=0,instruction=0,EEaddrF=0,EEaddr=0,adcc=0,helpC;
	initUART();
	//write start message (menu)
	UARTwriteString(msgMenu[0]);
	UARTwrite('\n');
	while(1)
	{	

		if(RCIF)						
		{	
			RCIF=0;
			LED2ON;						
			if(!(RCSTA&0b00000110))		
			{	rhead++;				
				rhead&=RINGBUFFMASK;	
				ringbuff[rhead]=RCREG;	
			}							
			LED2OFF;
			c=UARTread();
			UARTwrite(c);
			//c=UARTcharFromString(c);
			switch (mode)
			{
				case 0:
					mode=c-48;
					UARTwriteString(msgMenu[c-48]);
					if(mode==2)enablePWM();
					else if(mode==3)enableDAC();
					break;
				case 1://ADC
					switch(c)
					{
						case 'r'://single read
							UARTwriteString("\n\nADC value: ");
							helpC=getADC(adcc);
							UARTwriteDecimal(helpC);
							UARTwriteString(msgMenu[1]);
							break;
						case '1'://chanell one
							UARTwriteString("\n\nchannel 1 selected");
							adcc=0;
							UARTwriteString(msgMenu[1]);
							break;
						case '2'://chanel two
							UARTwriteString("\n\nchannel 2 selected");
							adcc=1;
							UARTwriteString(msgMenu[1]);
							break;
						case '3'://chanell three
							UARTwriteString("\n\nchannel 3 selected");
							adcc=2;
							UARTwriteString(msgMenu[1]);
							break;
						case 't'://temp
							UARTwriteString("\n\nTemp sensor selected");
							adcc=3;
							UARTwriteString(msgMenu[1]);
							break;
						case 'm'://back to start
							mode = 0;
							UARTwriteString(msgMenu[0]);	
							break;
						default:
							break;
					}
					break;
				case 2://PWM
					if(instruction)
					{
						switch(instruction)
						{	
							case 'p':
								//pwm period = c;
								setPeriod(UARTcharFromString(c));
								UARTwriteString(msgMenu[2]);
								break;
							case 'd':
								setDuty(UARTcharFromString(c));
								UARTwriteString(msgMenu[2]);
								//pwm period =c;	
								break;
							case 'm':
								mode =0;
								//pwm off
								UARTwriteString(msgMenu[0]);	
								break;
							default:
								break;
						}
						instruction = 0;						
					}
					else
					{
						instruction = c;				//loads the instruction
						if(instruction == 'p')
						{
							UARTwriteString("\n\nEnter the PWM Period: ");
							
						}
						else if(instruction == 'd')
						{
							UARTwriteString("\n\nEnter the PWM Duty Cycle: ");
						}
						else if(instruction == 'm')		//if it's m goes back to the start menu...
						{
							mode =0;						
							instruction =0;
							disablePWM();
							UARTwriteString(msgMenu[0]);
						}
					}
					break;
				case 3://DAC
					if(instruction)
					{
						switch(instruction)
						{
							case 'v':	//enter woltage
								setDAC(UARTcharFromString(c));
								UARTwriteString(msgMenu[3]);
								break;
							case 'm':
								mode = 0;
								UARTwriteString(msgMenu[0]);
								break;
							default:	
								break;
						}
						instruction =0;
					}
					else
					{
						instruction = c;				//loads the instruction
						if(instruction == 'v')
						{
							UARTwriteString(msgDACsetV);
						}
						else if(instruction == 'm')		//if it's m goes back to the start menu...
						{
							mode =0;						
							instruction =0;
							disableDAC();
							UARTwriteString(msgMenu[0]);
						}
					}
					break;
				case 4://MEM
					if(instruction)		//if instruction has been sent previusly
					{
						if(EEaddrF)			//instruction was sent previusly, check if address was sent
						{						//address was sent
							if(instruction == 'w')		//if instruction was W-writes recived character to EEProm[ADDR]
							{
								EEPROMwrite(EEaddr,UARTcharFromString(c));
								UARTwriteString(msgMenu[4]);
								//write c to eeprom
							}
							else if (instruction == 'r')	//if instruction was R-reads EEprom[addr] from eeprom
							{
								UARTwriteDecimal(EEPROMread(EEaddr));
								UARTwriteString(msgMenu[4]);
							}
							else if (instruction == 'm')	//if instruction was m --returns to start menu...
							{
								mode = 0;
								UARTwriteString(msgMenu[0]);
							}
							EEaddrF=0;							//clears the addressing flag
							instruction =0;					//clears the istruction flag
						}
						else
						{
							EEaddrF=1;						//sets the address flage
							EEaddr=UARTcharFromString(c);
							
							if(instruction=='w')UARTwriteString(msgEEw);
							else if(instruction == 'r')UARTwriteString("\n\nHit any key to read from EEPROM.\n\n"); 
						}
					}
					else 
					{
						instruction = c;				//loads the instruction
						if((instruction == 'w')||(instruction == 'r'))
						{
							UARTwriteString(msgEEaddr);
						}
						else if(instruction == 'm')		//if it's m goes back to the start menu...
						{
							mode =0;						
							instruction =0;
							UARTwriteString(msgMenu[0]);
						}
					}
					break;
				default:
					mode=0;
					UARTwriteString(msgMenu[0]);
					break;				
			}				
		}								
	}
}
Beispiel #29
0
int main (void)
{
  uint32_t analogValue;

  //Set LED1-LED8 pins as outputs
  GPIOSetDir( LED1_PORT, LED1_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED1_PORT, LED1_PIN, LED_OFF);
  GPIOSetDir( LED2_PORT, LED2_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED2_PORT, LED2_PIN, LED_OFF);
  GPIOSetDir( LED3_PORT, LED3_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED3_PORT, LED3_PIN, LED_OFF);
  GPIOSetDir( LED4_PORT, LED4_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED4_PORT, LED4_PIN, LED_OFF);
  GPIOSetDir( LED5_PORT, LED5_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED5_PORT, LED5_PIN, LED_OFF);
  GPIOSetDir( LED6_PORT, LED6_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED6_PORT, LED6_PIN, LED_OFF);
  GPIOSetDir( LED7_PORT, LED7_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED7_PORT, LED7_PIN, LED_OFF);
  GPIOSetDir( LED8_PORT, LED8_PIN, GPIO_OUTPUT);
  GPIOSetValue( LED8_PORT, LED8_PIN, LED_OFF);

  //Set SW2/SW3 pins as inputs
  GPIOSetDir( SW2_PORT, SW2_PIN, GPIO_INPUT);
  GPIOSetDir( SW3_PORT, SW3_PIN, GPIO_INPUT);

  //Extra, turn buzzer off
  GPIOSetDir( BUZZ_PORT, BUZZ_PIN, GPIO_OUTPUT);
  GPIOSetValue( BUZZ_PORT, BUZZ_PIN, BUZZ_OFF);

  //Initialize ADC peripheral and pin-mixing
  ADCInit(4500000);  //4.5MHz ADC clock

  //get initial value
  analogValue = getADC(AIN0);   //AIN0 = trimming pot for intensity LED1
  analogValue = getADC(AIN1);   //AIN1 = trimming pot for intensity LED2

  while(1)
  {
    uint8_t wantedDutyCycle0, wantedDutyCycle1;
    uint8_t loopCounter;
    uint16_t adcCounter;

    //check if time to read analog input
    if (adcCounter++ > 100)
    {
      adcCounter = 0;

      //Set wanted duty cycle - valid numbers: 0..100 (low number = LED on more)
      wantedDutyCycle0 = getADC(AIN0) / 10;   //trimming pot
      wantedDutyCycle1 = getADC(AIN1) / 10;   //trimming pot

      //extra check to that range is valid
      if (wantedDutyCycle0 > 99)
        wantedDutyCycle0 = 99;
      if (wantedDutyCycle1 > 99)
        wantedDutyCycle1 = 99;
    }

    //Set outputs high
    GPIOSetValue( LED1_PORT, LED1_PIN, 1);
    GPIOSetValue( LED2_PORT, LED2_PIN, 1);

    //Enter duty cycle generating loop
    for (loopCounter=0; loopCounter<100; loopCounter++)
    {
      //10 corresponds to 1kHz (100*10us), LED flickering starts at around 30-40Hz PWM frequency
      delayUS(10);
      if (loopCounter == wantedDutyCycle0)
        //Set output low
        GPIOSetValue( LED1_PORT, LED1_PIN, 0);
      if (loopCounter == wantedDutyCycle1)
        //Set output low
        GPIOSetValue( LED2_PORT, LED2_PIN, 0);
    }
  }

  return 0;
}