Exemplo n.º 1
0
void initLCD(unsigned char cursor) {
    msDelay(100);
    PMADDR=0;
    PMDIN1 = 0b00111100;//8bit mode
    PMADDR = 0x8000; //chip select enable
    msDelay(30);
    PMADDR = 0;
    PMDIN1 = 0b00001111;//cursor on
    PMADDR = 0x8000; //chip select enable
    _10usDelay(4); //macro for 40us
    PMADDR=0;

    PMDIN1 = 0b00000010; //return home
    PMADDR = 0x8000; //chip select enable
    msDelay(2); //macro for 2ms
    PMADDR=0;

    PMDIN1 = 0b00000110; //entry mode no shifting
    PMADDR = 0x8000; //chip select enable
    _10usDelay(4); //macro for 40us
    PMADDR = 0;
    PMDIN1 = 0b00001000 | cursor;
}
Exemplo n.º 2
0
/*************************************************************************
Author: Josiah Snarr
Date: April 11, 2015

stepperHome finds the stepper limits on the platform, and centers the
  stepper at the midpoint between them
*************************************************************************/
void stepperHome(void)
{
  unsigned int midpoint;

  //Delay stops it from going "ttttttzzzhhggggghhghhzzzzzttttt"
  msDelay(25);

  //Go fully left
  while(IS_CLR(STEP_SWI_PORT, SWI_LEFT))
  {
    stepperStep();
    msDelay(2);
  }
  
  //All the way left, 0-position, switch direction
  currStep = 0;
  SWI_DIR(direction);

  //Go all the way right
  while(IS_CLR(STEP_SWI_PORT, SWI_RIGHT))
  {
    stepperStep();
    msDelay(2);
  }
  
  //All the way right, number of steps is current step, find midpoint and switch direction
  numSteps = currStep;
  midpoint = currStep/2;
  SWI_DIR(direction);

  //Move to midpoint
  while(currStep != midpoint)
  {
    stepperStep();
    msDelay(2);
  }
}
Exemplo n.º 3
0
int main(void)
{
	  SystemInit();

	  /* Enable GPIO clock */
	  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);

	  /* Enable UART clock */
	  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);

	  /* Connect PXx to USARTx_Tx*/
	  GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_USART3);

	  /* Connect PXx to USARTx_Rx*/
	  GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_USART3);

	  /* Configure USART Tx as alternate function  */
	  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
	  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
	  GPIO_Init(GPIOB, &GPIO_InitStructure);

	  /* Configure USART Rx as alternate function  */
	  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
	  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	  GPIO_Init(GPIOB, &GPIO_InitStructure);

	  USART_InitStructure.USART_BaudRate = 921600;
	  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
	  USART_InitStructure.USART_StopBits = USART_StopBits_1;
	  USART_InitStructure.USART_Parity = USART_Parity_No;
	  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

	  /* USART configuration */
	  USART_Init(USART3, &USART_InitStructure);

	  /* Enable USART */
	  USART_Cmd(USART3, ENABLE);


	  while(1)
	  {
		  PrintChar(0x55);
		  msDelay(1000);
	  }
}
Exemplo n.º 4
0
short uartRead()
{
  // if the head isn't ahead of the tail, we don't have any characters
  while(rxHead == rxTail)
    msDelay(500); 

  if (rxHead == rxTail)
  {
    return -1;
  } else {
    unsigned char c = rxBuffer[rxTail];
    rxTail = (unsigned char)(rxTail+1) % SERIAL_BUFFER_SIZE;
    return c;
  }
}
Exemplo n.º 5
0
void flashled(int led)
{
    switch (led)
    {
    case 0:
        led = 0;
        break;
    case 1:
        led = 1;
        break;
    case 2:
        led = 2;
        break;
    case 3:
        led = 3;
        break;
    default:
        led = 6;
    }
    dispLedOut(led,1);
    msDelay(400);
    dispLedOut(led,0);
    msDelay(400);
}
Exemplo n.º 6
0
//------------------------------------------------------------------------
// Milli-sec delay function that also monitors the keypad
//------------------------------------------------------------------------
nodebug
int key_msDelay(int delay)
{
	auto int loop;

	for(loop=0; loop < delay; loop++)
	{
		msDelay(1);
		keyProcess ();
		if(keyGet() != 0)
		{
			return(TRUE);
		}
	}
}
Exemplo n.º 7
0
/******************************** MPU6050 Functions ********************************/
void initializeIMU()
{

	//Init Interrupt Output Pin
	P1REN |= BIT4;
	P1OUT |= BIT4;
	P1IFG &= ~BIT4;                           // P1.4 IFG cleared
	P1IE |= BIT4;                             // P1.4 interrupt enabled

	P4SEL |= BIT1 + BIT2;					  // P4.1 & P4.2 SDA/SCL Select

	// Delays do not need to be this long. Delays are present to keep I2C line clear.
	// This functions can be altered by the user. Check MPU6050.h file by Jeff Rowberg to determine the sensitivty variables.
	setClockSource(MPU6050_CLOCK_PLL_XGYRO);	// Set MPU6050 clock
	msDelay(100);
	setFullScaleGyroRange(MPU6050_GYRO_FS_2000);	// Gyroscope sensitivity set to 2000 degrees/sec
	msDelay(100);
	setFullScaleAccelRange(MPU6050_ACCEL_FS_4);	// Accelerometer sensitivity set to 4g
	msDelay(100);
	setDLPFConfig(MPU6050_DLPF_BW_5);		// Digital Low Pass Filter Configuration
	setInterruptPin();
	setSleepEnabled(0);	// Wake up device.
	msDelay(100);
}
unsigned char imposta_stato(unsigned char presa) {
    unsigned char level,press;
    y_pos(1,1);
    lcd_printf("Scegli lo stato");
    y_pos(6,2);
    lcd_printf(" 0     1");
    level=presa_read_level(presa);
    //porta il cursore sullivello del pin
    if (!level) 	y_pos(6,2);
    else		y_pos(12,2);
    lcd_printf(">");
    press=0;
    while(p_status() != P_OK) {
        press=p_status();
        if (press!=0)	{
            if (press==P_LEFT)	{
                y_pos(12,2);
                lcd_printf(" ");
                y_pos(6,2);
                lcd_printf(">");
                level=0;
                while (p_status()==P_LEFT) msDelay(1);
            }
            if (press==P_RIGHT)	{
                y_pos(6,2);
                lcd_printf(" ");
                y_pos(12,2);
                lcd_printf(">");
                level=1;
                while (p_status()==P_RIGHT) msDelay(1);
            }
        }
    }
    printf("restituisco %d",level);
    return level;
}
Exemplo n.º 9
0
/** \brief  Initialize the LAN8720 PHY.
 *
 *  This function initializes the LAN8720 PHY. It will block until
 *  complete. This function is called as part of the EMAC driver
 *  initialization. Configuration of the PHY at startup is
 *  controlled by setting up configuration defines in
 *  lpc_emac_config.h.
 *
 *  \param[in]     netif   NETIF structure
 *  \param[in]     rmii    If set, configures the PHY for RMII mode
 *  \return        ERR_OK if the setup was successful, otherwise ERR_TIMEOUT
 */
err_t lpc_phy_init(struct netif *netif, int rmii)
{
	u32_t tmp, tmp1;
	s32_t i;

	physts.phy_speed_100mbs = olddphysts.phy_speed_100mbs = 2;
	physts.phy_full_duplex = olddphysts.phy_full_duplex = 2;
	physts.phy_link_active = olddphysts.phy_link_active = 2;
	phyustate = 0;

	/* Only first read and write are checked for failure */
	/* Put the LAN8720 in reset mode and wait for completion */
	if (lpc_mii_write(LAN8_BCR_REG, LAN8_RESET) != 0)
		return ERR_TIMEOUT;
	i = 400;
	while (i > 0) {
		msDelay(1);   /* 1 ms */
		if (lpc_mii_read(LAN8_BCR_REG, &tmp) != 0)
			return ERR_TIMEOUT;

		if (!(tmp & (LAN8_RESET | LAN8_POWER_DOWN)))
			i = -1;
		else
			i--;
	}
	/* Timeout? */
	if (i == 0)
		return ERR_TIMEOUT;

	/* Setup link based on configuration options */
#if PHY_USE_AUTONEG==1
	tmp = LAN8_AUTONEG;
#else
	tmp = 0;
#endif
#if PHY_USE_100MBS==1
	tmp |= LAN8_SPEED_SELECT;
#endif
#if PHY_USE_FULL_DUPLEX==1
	tmp |= LAN8_DUPLEX_MODE;
#endif
	lpc_mii_write(LAN8_BCR_REG, tmp);

	/* The link is not set active at this point, but will be detected
       later */

	return ERR_OK;
}
Exemplo n.º 10
0
//-------------------------------------------------------------------
//  Description:
//     Send a break on the com port for "len" msec
//
//  portnum    - number 0 to MAX_PORTNUM-1.  This number is provided to
//                 indicate the symbolic port number.
//
void BreakCOM(int portnum)
{
   // start the reset pulse
   SetCommBreak(ComID[portnum]);

   // delay
   msDelay(2);

   // clear the reset pulse and return
   // PROGRAMMER'S NOTE: ClearCommBreak is returning 24:an undefined code
   ClearCommBreak(ComID[portnum]);

   // Win3.1 bug, close and then open port
   CloseCOM(portnum);
   OpenCOM(portnum,&port[0]);
}
Exemplo n.º 11
0
uint8_t initMPU(uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t source)
{
	uint8_t b = 0;

	readByte(devAddr, regAddr, &b);
	msDelay(2);
	uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
	source <<= (bitStart - length + 1);	// shift data into correct position
	source &= mask;	// zero all non-important bits in data

	b &= ~(mask); // zero all important bits in existing byte
	b |= source; // combine data with existing byte

	writeByte(devAddr, regAddr, b);
	return b;
}
int main() {

    unsigned char Lcd_LINE1[6] = {'\0'};
    unsigned char Lcd_LINE2[16] = {'\0'};
    unsigned int i;
    InitCan();
    InitQEI();
    InitPwm();
//    InitInt();
    InitAdc();
//    InitUart();
    
    //pid
    unsigned int *pwmOUT;
    pid_t mypid;
    float degPOT = 0.0;
    float degMTR = 0.0;


    while (1) {

        if(InData0[1] > 0){
//            if(InData0[2] == 1){
//                PDC2 = (unsigned int)(InData0[1]* 2 *.5914);
//                PDC1 = 0;
//            }
//            else{
//                PDC1 = (unsigned int)(InData0[1]* 2* .5914);
//                PDC2 = 0;
//            }
            pwmOUT = CalcPid(&mypid, degPOT, degMTR);
            PDC1 = *(pwmOUT + 0); // 16-bit register
            PDC2 = *(pwmOUT + 1); // 16-bit register
        }

        if (InData0[3] == 1) {
            C1TX0B4 = 2;
            C1TX0B1 = POSCNT;
            C1TX0B2 = C1RX0B2;
            C1TX0B3 = C1RX0B3;
            C1TX0CONbits.TXREQ = 1;
            while (C1TX0CONbits.TXREQ != 0);
        }
        msDelay(10);

    } //while
} // main
Exemplo n.º 13
0
static void handleBootloaderCmd(struct esbPacket_s *packet)
{
  static bool resetInit = false;
  static struct esbPacket_s txpk;

  switch (packet->data[2]) {
    case BOOTLOADER_CMD_RESET_INIT:

      resetInit = true;

      txpk.data[0] = 0xff;
      txpk.data[1] = 0xfe;
      txpk.data[2] = BOOTLOADER_CMD_RESET_INIT;

      memcpy(&(txpk.data[3]), (uint32_t*)NRF_FICR->DEVICEADDR, 6);

      txpk.size = 9;
#if BLE
      bleCrazyfliesSendPacket(&txpk);
#endif
      if (esbCanTxPacket()) {
        struct esbPacket_s *pk = esbGetTxPacket();
        memcpy(pk, &txpk, sizeof(struct esbPacket_s));
        esbSendTxPacket(pk);
      }

      break;
    case BOOTLOADER_CMD_RESET:
      if (resetInit && (packet->size == 4)) {
        msDelay(100);
        if (packet->data[3] == 0) {
          NRF_POWER->GPREGRET |= 0x40;
        } else {
          //Set bit 0x20 forces boot to firmware
          NRF_POWER->GPREGRET |= 0x20U;
        }
#ifdef BLE
        sd_nvic_SystemReset();
#else
        NVIC_SystemReset();
#endif
      }
      break;
    default:
      break;
  }
}
Exemplo n.º 14
0
unsigned char  scegli_sonda(){

// ritorna 1..7
	unsigned char scelta,press,i,sonda;
	y_pos(1,1);
	lcd_printf("Scegli la sonda");
	y_pos(4,2);
	lcd_printf(">1 2 3 4 5 6 7");
	y_pos(3,3);	
	for (i=0;i<15;i++) lcd_printf(sonde_nomi[0][i]);
	scelta=4;
	y_pos(scelta,2);
	sonda=1;
	while(p_status() != P_OK){
		press=p_status();
		if (press!=0)	{
			y_pos(scelta,2);
			lcd_printf(" ");	
			if (press==P_RIGHT)	{
				scelta+=2;
				sonda++; 			
				if (scelta>17){
					scelta=4;
					sonda=1;
				}
			}
			else if (press==P_LEFT)	{
				scelta-=2;
				sonda--; 			
				if (scelta<4){
					scelta=16;
					sonda=7;
				}
			}
			y_pos(scelta,2);
			lcd_printf(">");
			y_pos(3,3);
			for (i=0;i<15;i++) lcd_printf(sonde_nomi[sonda-1][i]);
			while (p_status()!=0) msDelay(1);		
		}
	}
	clean_row(2);
	return sonda; // da1..7



}
Exemplo n.º 15
0
void sk_menu_1_1(){
	
	char valore[5];
//	int intervalli[6];
	// leggi rtc
	y_pos(0,0);
	lcd_printf("<<  CAMBIA  DATA");			
	y_pos(2,2);
	//lcd_printf("15:00   25/04/07");
//ora 
  valore[0]=read_hour();
  lcd_printf("%02d:",valore[0]);
  valore[1]=read_min();
  lcd_printf("%02d  ",valore[1]);

//data 
  valore[2]=read_day();
  lcd_printf("%02d",valore[2]);
  valore[3]=read_month();
  lcd_printf("/%02d",valore[3]);
  valore[4]=read_year();
  lcd_printf("/%02d",valore[4]);

	// x,y,partenza,min,max
	valore[0]=inc_cifra(2,2,valore[0],0,24);// hh 
	valore[1]=inc_cifra(5,2,valore[1],0,59);// mm
	set_ora(valore[0],valore[1]);
	
	valore[2]=inc_cifra(9,2,valore[2],0,31);// gg
	valore[3]=inc_cifra(12,2,valore[3],0,12);// m
	valore[4]=inc_cifra(15,2,valore[4],7,20);// aa
	// verifica data x gg bisestili e gg de mesi
	set_data(valore[2],valore[3],valore[4]);
	
	//se ok salva il valore
	y_pos(4,3);
		
	if (true) lcd_printf("DATA SALVATA");
	else lcd_printf("DATA ERRATA");
	msDelay(2000);		

}
Exemplo n.º 16
0
//------------------------------------------------------------------------------
int HWDeInit(void)
{
	// Reset PHY
	(void) HYPHYReset();

	// Reset all MAC logic
	ENETMAC->mac1 = (MAC1_SOFT_RESET | MAC1_SIMULATION_RESET |
		MAC1_RESET_MCS_TX | MAC1_RESET_TX | MAC1_RESET_MCS_RX |
		MAC1_RESET_RX);
	ENETMAC->command = (COMMAND_REG_RESET | COMMAND_TXRESET |
		COMMAND_RXRESET);
	msDelay(2);

	// Disable MAC clocks, but keep MAC interface active
#ifdef USE_PHY_RMII
	CLKPWR->clkpwr_macclk_ctrl = CLKPWR_MACCTRL_USE_RMII_PINS;
#else
	CLKPWR->clkpwr_macclk_ctrl = CLKPWR_MACCTRL_USE_MII_PINS;
#endif

	return 1;
}
int main() {

    unsigned char Lcd_LINE1[6] = {'\0'};
    unsigned char Lcd_LINE2[16] = {'\0'};
    unsigned int i;
    InitCan();
    InitQEI();
    InitPwm();
//    InitInt();
    InitAdc();
//    InitUart();
    

    while (1) {

        if(InData0[1] > 0){
            if(InData0[2] == 1){
                PDC2 = (unsigned int)(InData0[1]* 2 *.5914);
                PDC1 = 0;
            }
            else{
                PDC1 = (unsigned int)(InData0[1]* 2* .5914);
                PDC2 = 0;
            }
        }
        
        if (InData0[3] == 1) {
            C1TX0B4 = 2;
            C1TX0B1 = POSCNT;
            C1TX0B2 = C1RX0B2;
            C1TX0B3 = C1RX0B3;
            C1TX0CONbits.TXREQ = 1;
            while (C1TX0CONbits.TXREQ != 0);
        }
        msDelay(10);

    } //while
} // main
Exemplo n.º 18
0
main ()
{
    auto int channel;
    auto unsigned int avg_sample;
    auto char s[80];
    auto char display[80];
    auto float ad_inputs[ENDCHAN+1];

    brdInit();

    //initially start up A/D oscillator and charge up cap
    anaIn(0,SINGLE,GAINSET);

    DispStr(1, 1, "\t\t<<< Analog input channels 0 - 6: >>>");
    DispStr(1, 3, "\t LN0IN\t LN1IN\t LN2IN\t LN3IN\t LN4IN\t LN5IN\t LN6IN");
    DispStr(1, 4, "\t------\t------\t------\t------\t------\t------\t------");

    for(;;)
    {
        for(channel = STARTCHAN; channel <= ENDCHAN; channel++)
        {
            // sample each channel
            avg_sample = sample_ad(channel, NUMSAMPLES);
            ad_inputs[channel] = convert_volt(channel, avg_sample);
        }

        display[0] = '\0';
        for(channel =  STARTCHAN; channel <= ENDCHAN; channel++)
        {
            sprintf(s, "\t%6.3f", ad_inputs[channel]);
            strcat(display, s);
        }

        DispStr(1, 5, display);
        msDelay(1000);				//delay one second for viewing
    }
}
Exemplo n.º 19
0
static int phy_get_link_status (void)
{
        unsigned long status;

        /* Status is read once to clear old link state */
        RMII_Read(PHY_BMSR,&status);

        /*
	 * Wait if the link is up, and autonegotiation is in progress
	 * (ie - we're capable and it's not done)
	 */
        status = 0;
        RMII_Read(PHY_BMSR,&status);
        if ((status & PHY_BMSR_LS) && (status & PHY_BMSR_AUTN_ABLE)
            && !(status & PHY_BMSR_AUTN_COMP)) {
                int i = 0;

                while (!(status & PHY_BMSR_AUTN_COMP)) {
                        /* Timeout reached */
                        if (i > 1000) {
                                printf("Timeout\n");
                                return 1;
                        }
                        i++;
                        msDelay(1);   /* 1 ms */
                        RMII_Read(PHY_BMSR,&status);
                }
                return 0;
        } else {
                if (status & PHY_BMSR_LS)
                        return 0;
                else
                        return 1;
        }
        return 1;
}
Exemplo n.º 20
0
/* Write a value via the MII link (blocking) */
err_t lpc_mii_write(u32_t PhyReg, u32_t Value)
{
	u32_t mst = 250;
	err_t sts = ERR_OK;

	/* Write value at PHY address and register */
	lpc_mii_write_noblock(PhyReg, Value);

	/* Wait for unbusy status */
	while (mst > 0) {
		sts = LPC_ETHERNET->MAC_MII_ADDR & MAC_MIIA_GB;
		if (sts == 0)
			mst = 0;
		else {
			mst--;
			msDelay(1);
		}
	}

	if (sts != 0)
		sts = ERR_TIMEOUT;

	return sts;
}
Exemplo n.º 21
0
//-------------------------------------
void DriverFSU()
{
	BYTE i, j, k,  send, tmp;
	int data;
	//------------------------------------------------
	// обновление адреса блока
	Fsu.Info.bits.Addr	=ADDR;
	if(stStartBlock == FALSE)
	{
		if(getTimer(&TimerStartBlock) == 0)	
		{
			stStartBlock = TRUE;
			
			for(i=0; i<6; i++)
			{
				ChipSelekt(i, CS_ON);
				obmen_spi(i/3, 0); // Обнуление всех флагов ошибок
				ChipSelekt(i, CS_OFF);
			}
			msDelay(50);
			for(i=0; i<6; i++)
			{
				ChipSelekt(i, CS_ON);
				obmen_spi(i/3, 0xFF); // Выключение реле
				ChipSelekt(i, CS_OFF);
			}
		}else
		{
			msDelay(10);
			for(i=0; i<6; i++)
			{
				ChipSelekt(i, CS_ON);
				obmen_spi(i/3, 0xFF); // Выключение реле
				ChipSelekt(i, CS_OFF);
			}
		}
	}
	//========================================================
	if(stStartBlock == TRUE)
	{
		if(getTimer(&TimerStartBlock) == 0)	
		{
		
			setTimer(&TimerStartBlock, 10);
		
			i = K_1 | (K_2<<1) | (K_3<<2) | (K_4<<3) | (K_5<<4) | (K_6<<5) | (K_7<<6) | (K_8<<7);
			Fsu.K[0] = ~i;
			
			i = K_9 | (K_10<<1)| (K_11<<2)| (K_12<<3)| (K_13<<4)| (K_14<<5)| (K_15<<6)| (K_16<<7);
			Fsu.K[1] = ~i;
			
			i = K_17| (K_18<<1)| (K_19<<2)| (K_20<<3)| (K_21<<4)| (K_22<<5)| (K_23<<6)| (K_24<<7);
			Fsu.K[2] = ~i;
			//-------------------------------------------------------------------------------------------
			for(i=0; i<3; i++)
			{
				Fsu.SetData[i] = Fsu.NewData[i];
				Fsu.OL[i]	= 0;
				Fsu.Diag[i]	= 0;
				Fsu.DiagSum[i]	=0;
						
				for(j=0; j<2; j++)
				{
					ChipSelekt(2*i+j, CS_ON);
					
					// 0x2 - ON  0x3 - OFF
					send = 0;
					tmp = Fsu.SetData[i]>>(4*j);
					
					for(k=0; k<4; k++)
					{
						if(digit(tmp,k) == 0)
							send|=0x3<<(2*k);
						else
							send|=0x2<<(2*k);		
					}
					
					data = obmen_spi((i+j)/2, send);
					
					if(data >= 0)
					{
						tmp = data;
						for(k=0; k<4; k++)
						{
							Fsu.OL[i]	|= digit(tmp,1+2*k)<<(4*j+k);
							Fsu.Diag[i]	|= digit(tmp,2*k)<<(4*j+k);
						}
						
						Fsu.DiagSum[i]	=Fsu.OL[i]|Fsu.Diag[i];
					}else
					{
						Fsu.DiagSum[i]	=0xFF;
					}
					ChipSelekt(2*i+j, CS_OFF);
				}
			}
		}
	}	
void COpenProgDlg::Write18Fx(int dim,int dim2,int wbuf=8,int eraseW1=0x10000,int eraseW2=0x10000,int options=0)
// write 16 bit PIC 18Fxxxx
// dim=program size 	dim2=eeprom size	wbuf=write buffer size {<=64}
// eraseW1=erase word @3C0005	(not used if > 0x10000)
// eraseW2=erase word @3C0004	(not used if > 0x10000)
// options:
//	bit [3:0]
//     0 = vdd before vpp (12V)
//     1 = vdd before vpp (9V)
//     2 = low voltage entry with 32 bit key
//	bit [7:4]
//     0 = normal eeprom write algoritm
//     1 = with unlock sequence 55 AA
//	bit [11:8]
//     0 = 5ms erase delay, 1ms code write time, 5ms EE write delay, 5ms config write time
//     1 = 550ms erase delay, 1.2ms code write time, no config or EEPROM
//     2 = 550ms erase delay, 3.4ms code write time, no config or EEPROM
{
	CString str;
	int size=memCODE.GetSize(),sizeEE=memEE.GetSize();
	int k=0,k2,z=0,i,j;
	int err=0,devID=0;
	int EEalgo=(options>>4)&0xF,entry=options&0xF,optWrite=(options>>8)&0xF;
	if(dim>0x1FFFFF||dim<0){
		PrintMessage(strings[S_CodeLim]);	//"Code size out of limits\r\n"
		return;
	}
	if(dim2>0x800||dim2<0){
		PrintMessage(strings[S_EELim]);	//"EEPROM size out of limits\r\n"
		return;
	}
	if(wbuf>64){
		PrintMessage(strings[S_WbufLim]);	//"Write buffer size out of limits\r\n"
		return;
	}
	if(entry==2&&!CheckV33Regulator()){
		PrintMessage(strings[S_noV33reg]);	//Can't find 3.3V expansion board
		return;
	}
	double vpp=entry<2?(entry==0?12:8.5):-1;
	if(!StartHVReg(vpp)){
		PrintMessage(strings[S_HVregErr]); //"HV regulator error\r\n"
		return;
	}
	if(saveLog){
		OpenLogFile();	//"log.txt"
		fprintf(logfile,"Write18F(%d,%d,%d,%d)    (0x%X,0x%X,0x%X,0x%X)\n",dim,dim2,wbuf,options,dim,dim2,wbuf,options);
	}
	if(dim>size) dim=size;
	if(dim%wbuf){			//grow to an integer number of rows
		dim+=wbuf-dim%wbuf;
		j=size;
		if(j<dim)memCODE.SetSize(dim);
		for(;j<dim;j++) memCODE[j]=0xFF;
	}
	if(dim2>sizeEE) dim2=sizeEE;
	if(dim<1){
		PrintMessage(strings[S_NoCode]);	//"Empty data area\r\n"
		return;
	}
	unsigned int start=GetTickCount();
	bufferU[0]=0;
	j=1;
	bufferU[j++]=SET_PARAMETER;
	bufferU[j++]=SET_T1T2;
	bufferU[j++]=1;						//T1=1u
	bufferU[j++]=100;					//T2=100u
	bufferU[j++]=EN_VPP_VCC;		//enter program mode
	bufferU[j++]=0x0;
	bufferU[j++]=SET_CK_D;
	bufferU[j++]=0x0;
	bufferU[j++]=EN_VPP_VCC;		//VDD
	bufferU[j++]=0x1;
	bufferU[j++]=EN_VPP_VCC;		//VDD+VPP
	bufferU[j++]=0x5;
	if(entry==2){					//LV entry with key
		bufferU[j++]=EN_VPP_VCC;		//VDD
		bufferU[j++]=0x1;
		bufferU[j++]=WAIT_T3;
		bufferU[j++]=WAIT_T3;
		bufferU[j++]=TX16;
		bufferU[j++]=2;
		bufferU[j++]=0x4D;
		bufferU[j++]=0x43;
		bufferU[j++]=0x48;
		bufferU[j++]=0x50;
		bufferU[j++]=EN_VPP_VCC;		//VDD+VPP
		bufferU[j++]=0x5;
		bufferU[j++]=WAIT_T3;
	}
	bufferU[j++]=WAIT_T3;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//3F
	bufferU[j++]=0x3F;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//-> TBLPTRU
	bufferU[j++]=0xF8;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//FF
	bufferU[j++]=0xFF;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//-> TBLPTRH
	bufferU[j++]=0xF7;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//FE
	bufferU[j++]=0xFE;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//-> TBLPTRL
	bufferU[j++]=0xF6;
	bufferU[j++]=TBLR_INC_N;		//DevID1-2	0x3FFFFE-F
	bufferU[j++]=2;
	bufferU[j++]=SET_PARAMETER;
	bufferU[j++]=SET_T3;
	bufferU[j++]=5100>>8;
	bufferU[j++]=5100&0xff;
	bufferU[j++]=FLUSH;
	for(;j<DIMBUF;j++) bufferU[j]=0x0;
	write();
	msDelay(3);
	if(entry==2) msDelay(7);
	read();
	if(saveLog)WriteLogIO();
	for(z=1;bufferI[z]!=TBLR_INC_N&&z<DIMBUF;z++);
	if(z<DIMBUF-3){
		PrintMessage2(strings[S_DevID2],bufferI[z+3],bufferI[z+2]);	//"DevID: 0x%02X%02X\r\n"
		PIC18_ID(bufferI[z+2]+(bufferI[z+3]<<8));
	}
	j=1;
//****************** erase memory ********************
	PrintMessage(strings[S_StartErase]);	//"Erase ... "
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x0E;			//3C
	bufferU[j++]=0x3C;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6E;			//-> TBLPTRU
	bufferU[j++]=0xF8;
	bufferU[j++]=CORE_INS;
	bufferU[j++]=0x6A;			//TBLPTRH=0
	bufferU[j++]=0xF7;
	if(eraseW1<0x10000){
		bufferU[j++]=CORE_INS;
		bufferU[j++]=0x0E;			//05
		bufferU[j++]=0x05;
		bufferU[j++]=CORE_INS;
		bufferU[j++]=0x6E;			//-> TBLPTRL
		bufferU[j++]=0xF6;
		bufferU[j++]=TABLE_WRITE;		// eraseW1@3C0005
		bufferU[j++]=(eraseW1>>8)&0xFF; 	//0x3F;
		bufferU[j++]=eraseW1&0xFF; 		//0x3F;
	}
Exemplo n.º 23
0
main()
{
	auto int i,x,y,z;
	auto char s[256];
	auto int NumPixel;
	auto int FontWidth, FontHeight;
	
	//------------------------------------------------------------------------
	// Initialize controller 
	//------------------------------------------------------------------------
	brdInit();			// Initialize Controller...Required for controllers!!! 

	glInit();			// Initialize the graphic driver
	glBackLight(1);
	glSetContrast(24);

	glXFontInit(&fi10x16, 10, 16, 32, 127, Font10x16);		//	Initialize basic font
	glXFontInit(&fi12x16, 12, 16, 32, 127, Font12x16);		//	Initialize basic font
	glXFontInit(&fi17x35, 17, 35, 32, 127, Font17x35);		//	Initialize basic font

	while(1)
	{	
		//------------------------------------------------------------------------
		// Text scroll-up example 
		//------------------------------------------------------------------------
		glPrintf(0, 0,&fi10x16,"Scroll-up Demo");
		msDelay(800);

		FontWidth  = 10;
		FontHeight = 16;
		glBuffLock();
		glBlankScreen();
		for (y = 0, z = 32; y < 240; y += FontHeight)
		{	
			for (x = 0; x < LCD_XS; x+=FontWidth)
			{
				glPrintf(x, y,&fi10x16,"%c",z++);
				if (z > 64) z = 32;
			}
		}
		glBuffUnlock();
		msDelay(750);

		for(y=0; y<3; y++)
		{
			glVScroll(0, 0, LCD_XS, LCD_YS, -FontHeight);
			for (x = 0; x < LCD_XS; x+=FontWidth)
			{
				glPrintf(x, LCD_YS-FontHeight, &fi10x16, "%c",z++);
				if (z > 126) z = 32;
					msDelay(5);
			}
			msDelay(600);
		} 
	
		//------------------------------------------------------------------------
		// Text scroll-down example 
		//------------------------------------------------------------------------
		glBlankScreen();
		glPrintf(0, 0,&fi10x16,"Scroll-Down Demo");
		msDelay(800);

		FontWidth  = 10;
		FontHeight = 16;
		glBuffLock();
		glBlankScreen();
		for (y = 0, z=32; y < LCD_XS; y += FontHeight)
		{
			for (x = 0; x < LCD_XS; x+=FontWidth)
			{
				glPrintf(x, y,&fi10x16,"%c",z++);
				if (z > 126) z = 32;
					msDelay(5);
			}
		}

		glBuffUnlock();
		msDelay(750);
		for(y=0; y<4; y++)
		{
			glVScroll(0, 0, LCD_XS, LCD_YS, FontHeight);
			for (x = 0; x < LCD_XS; x+=FontWidth)
			{
				glPrintf(x, 0,&fi10x16,"%c",z++);
				if (z > 64) z = 32;
					msDelay(5);
			}
			msDelay(600);
		}

		//------------------------------------------------------------------------
		// Text Scrolling left example 
		//------------------------------------------------------------------------
		glBlankScreen();
		glPrintf(0, 0,&fi10x16,"Scroll-Left Demo");
		msDelay(1500);

		NumPixel = 17;
		for(y = 0; y < 1; y++)
		{
			sprintf(s, "Hello from Z-World.....");
			i =0;
			while(s[i] != '\0')
			{
				glHScroll(0, 60, LCD_XS, 34, -NumPixel);
				glPrintf (LCD_XS-NumPixel, 60, &fi17x35, "%c", s[i++]);
				msDelay(300);
			}
		}
		glBlankScreen();
		
		//------------------------------------------------------------------------
		// Text Scrolling right and left example 
		//------------------------------------------------------------------------
		glPrintf(0, 0,&fi10x16,"Scroll Right&Left Demo");
		msDelay(1200);

		FontWidth  = 10;
		FontHeight = 16;
		sprintf(s, "Text to Scroll Right/Left");
		glPrintf (0, 40, &fi10x16, "%s", s);
		msDelay(1000);
		NumPixel = 4;
		for(y = 0; y < 3; y++)
		{		
			for(i=0; i<(LCD_XS -(strlen(s)*FontWidth)); i+=FontWidth)
			{
				glHScroll(0, 40, LCD_XS, FontHeight, FontWidth);	
			}
			msDelay(500);
			for(i=0; i<(LCD_XS-(strlen(s)*FontWidth)); i+=FontWidth)
			{
				glHScroll(0, 40, LCD_XS, FontHeight, -FontWidth);
			}
			msDelay(500);
		}
		glBlankScreen();
	}
}
/* Low level output of a packet. Never call this from an interrupt context,
   as it may block until TX descriptors become available */
static err_t lpc_low_level_output(struct netif *netif, struct pbuf *sendp)
{
	struct lpc_enetdata *lpc_netifdata = netif->state;
	u32_t idx, fidx, dn;
	struct pbuf *p = sendp;

#if LPC_CHECK_SLOWMEM == 1
	struct pbuf *q, *wp;

	u8_t *dst;
	int pcopy = 0;

	/* Check packet address to determine if it's in slow memory and
	   relocate if necessary */
	for (q = p; ((q != NULL) && (pcopy == 0)); q = q->next) {
		fidx = 0;
		for (idx = 0; idx < sizeof(slmem);
			 idx += sizeof(struct lpc_slowmem_array_t)) {
			if ((q->payload >= (void *) slmem[fidx].start) &&
				(q->payload <= (void *) slmem[fidx].end)) {
				/* Needs copy */
				pcopy = 1;
			}
		}
	}

	if (pcopy) {
		/* Create a new pbuf with the total pbuf size */
		wp = pbuf_alloc(PBUF_RAW, (u16_t) EMAC_ETH_MAX_FLEN, PBUF_RAM);
		if (!wp) {
			/* Exit with error */
			return ERR_MEM;
		}

		/* Copy pbuf */
		dst = (u8_t *) wp->payload;
		wp->tot_len = 0;
		for (q = p; q != NULL; q = q->next) {
			MEMCPY(dst, (u8_t *) q->payload, q->len);
			dst += q->len;
			wp->tot_len += q->len;
		}
		wp->len = wp->tot_len;

		/* LWIP will free original pbuf on exit of function */

		p = sendp = wp;
	}
#endif

	/* Zero-copy TX buffers may be fragmented across mutliple payload
	   chains. Determine the number of descriptors needed for the
	   transfer. The pbuf chaining can be a mess! */
	dn = (u32_t) pbuf_clen(p);

	/* Wait until enough descriptors are available for the transfer. */
	/* THIS WILL BLOCK UNTIL THERE ARE ENOUGH DESCRIPTORS AVAILABLE */
	while (dn > lpc_tx_ready(netif))
#if NO_SYS == 0
	{xSemaphoreTake(lpc_netifdata->xTXDCountSem, 0); }
#else
	{msDelay(1); }
#endif

	/* Get the next free descriptor index */
	fidx = idx = lpc_netifdata->tx_fill_idx;

#if NO_SYS == 0
	/* Get exclusive access */
	sys_mutex_lock(&lpc_netifdata->TXLockMutex);
#endif

	/* Fill in the next free descriptor(s) */
	while (dn > 0) {
		dn--;

		/* Setup packet address and length */
		lpc_netifdata->ptdesc[idx].B1ADD = (u32_t) p->payload;
		lpc_netifdata->ptdesc[idx].BSIZE = (u32_t) TDES_ENH_BS1(p->len);

		/* Save pointer to pbuf so we can reclain the memory for
		   the pbuf after the buffer has been sent. Only the first
		   pbuf in a chain is saved since the full chain doesn't
		   need to be freed. */
		/* For first packet only, first flag */
		lpc_netifdata->tx_free_descs--;
		if (idx == fidx) {
			lpc_netifdata->ptdesc[idx].CTRLSTAT |= TDES_ENH_FS;
#if LPC_CHECK_SLOWMEM == 1
			/* If this is a copied pbuf, then avoid getting the extra reference
			   or the TX reclaim will be off by 1 */
			if (!pcopy) {
				pbuf_ref(p);
			}
#else
			/* Increment reference count on this packet so LWIP doesn't
			   attempt to free it on return from this call */
			pbuf_ref(p);
#endif
		}
		else {
			lpc_netifdata->ptdesc[idx].CTRLSTAT |= TDES_OWN;
		}

		/* Save address of pbuf, but make sure it's associated with the
		   first chained pbuf so it gets freed once all pbuf chains are
		   transferred. */
		if (!dn) {
			lpc_netifdata->txpbufs[idx] = sendp;
		}
		else {
			lpc_netifdata->txpbufs[idx] = NULL;
		}

		/* For last packet only, interrupt and last flag */
		if (dn == 0) {
			lpc_netifdata->ptdesc[idx].CTRLSTAT |= TDES_ENH_LS |
												   TDES_ENH_IC;
		}

		/* IP checksumming requires full buffering in IP */
		lpc_netifdata->ptdesc[idx].CTRLSTAT |= TDES_ENH_CIC(3);

		LWIP_DEBUGF(EMAC_DEBUG | LWIP_DBG_TRACE,
					("lpc_low_level_output: pbuf packet %p sent, chain %d,"
					 " size %d, index %d, free %d\n", p, dn, p->len, idx,
					 lpc_netifdata->tx_free_descs));

		/* Update next available descriptor */
		idx++;
		if (idx >= LPC_NUM_BUFF_TXDESCS) {
			idx = 0;
		}

		/* Next packet fragment */
		p = p->next;
	}

	lpc_netifdata->tx_fill_idx = idx;

	LINK_STATS_INC(link.xmit);

	/* Give first descriptor to DMA to start transfer */
	lpc_netifdata->ptdesc[fidx].CTRLSTAT |= TDES_OWN;

	/* Tell DMA to poll descriptors to start transfer */
	LPC_ETHERNET->DMA_TRANS_POLL_DEMAND = 1;

#if NO_SYS == 0
	/* Restore access */
	sys_mutex_unlock(&lpc_netifdata->TXLockMutex);
#endif

	return ERR_OK;
}
Exemplo n.º 25
0
//----------------------------------------------------------------------
// Read the temperature of a DS1920/DS1820
//
// 'portnum'     - number 0 to MAX_PORTNUM-1.  This number was provided to
//                 OpenCOM to indicate the port number.
// 'SerialNum'   - Serial Number of DS1920/DS1820 to read temperature from
// 'Temp '       - pointer to variable where that temperature will be 
//                 returned
//
// Returns: TRUE(1)  temperature has been read and verified
//          FALSE(0) could not read the temperature, perhaps device is not
//                   in contact
//
int ReadTemperature(int portnum, uchar *SerialNum, float *Temp)
{
   int rt=FALSE;
   uchar send_block[30],lastcrc8;
   int send_cnt=0, tsht, i, loop=0;
   float tmp,cr,cpc;
   
   
   setcrc8(portnum,0);

   // set the device serial number to the counter device
   owSerialNum(portnum,SerialNum,FALSE);

   for (loop = 0; rt==FALSE && loop < 2; loop ++)
   {
      // access the device 
      if (owAccess(portnum))
      {
         // send the convert temperature command
         owTouchByte(portnum,0x44);

         // set the 1-Wire Net to strong pull-up
         if (owLevel(portnum,MODE_STRONG5) != MODE_STRONG5)
            return FALSE;
 
         // sleep for 1 second
         msDelay(1000);

         // turn off the 1-Wire Net strong pull-up
         if (owLevel(portnum,MODE_NORMAL) != MODE_NORMAL)
            return FALSE;

         // access the device 
         if (owAccess(portnum))
         {
            // create a block to send that reads the temperature
            // read scratchpad command
            send_block[send_cnt++] = 0xBE;
            // now add the read bytes for data bytes and crc8
            for (i = 0; i < 9; i++)
               send_block[send_cnt++] = 0xFF;

            // now send the block
            if (owBlock(portnum,FALSE,send_block,send_cnt))
            {
               // perform the CRC8 on the last 8 bytes of packet
               for (i = send_cnt - 9; i < send_cnt; i++)
                  lastcrc8 = docrc8(portnum,send_block[i]);

               // verify CRC8 is correct
               if (lastcrc8 == 0x00)
               {
                  // calculate the high-res temperature
                  tsht = send_block[1]/2;
                  if (send_block[2] & 0x01)
                     tsht |= -128;
                  tmp = (float)(tsht);
                  cr = send_block[7];
                  cpc = send_block[8];
                  if (((cpc - cr) == 1) && (loop == 0))
                     continue;
                  if (cpc == 0)
                     return FALSE;   
                  else
                     tmp = tmp - (float)0.25 + (cpc - cr)/cpc;
   
                  *Temp = tmp;
                  // success
                  rt = TRUE;
               }
            }
         }
      }
        
   }
   
 // return the result flag rt
      return rt;
      
}
Exemplo n.º 26
0
//--------------------------------------------------------------------------
// This is the begining of the program that tests the different Channels
int main() //short argc, char **argv)
{
   char return_msg[128];           //returned message from 1-wire operations
   int i,j,k,n;                    //loop counters
   short test=0;                   //info byte data
   short clear=0;                  //used to clear the button
   SwitchProps sw;                 //used to set Channel A and B
   uchar SwitchSN[MAXDEVICES][8];  //the serial numbers for the devices
   int num;                        //for the number of devices present
   int ch;                         //inputed character from user
   char out[140];                  //used for output of the info byte data
   int portnum=0;

   //----------------------------------------
   // Introduction header
   printf("\n/---------------------------------------------\n");
   printf("  swtest - V2.00\n"
          "  The following is a test to excersize the\n"
          "  different channels on the DS2406.\n");
   printf("  Press any CTRL-C to stop this program.\n\n");

   // check for required port name
   if (argc != 2)
   {
      printf("1-Wire Net name required on command line!\n"
             " (example: \"COM1\" (Win32 DS2480),\"/dev/cua0\" "
             "(Linux DS2480),\"1\" (Win32 TMEX)\n");
      exit(1);
   }

   // attempt to acquire the 1-Wire Net
   if (!owAcquire(portnum, argv[1], return_msg))
   {  
      printf("%s",return_msg);
      exit(1);
   }

   // success
   printf("%s",return_msg);
   
   // this is to get the number of the devices and the serial numbers
   num = FindDevices(portnum, &SwitchSN[0], SWITCH_FAMILY, MAXDEVICES);

   // setting up the first print out for the frist device
   owSerialNum(portnum, SwitchSN[0], FALSE);
   
   j=1;
   n=0;
   do
   {
      // This is for after the different combinations of channels
      // have been tested to reset to a different device to be tested.
      if( ((test & 0x40) && (j==5)) ||
         ((!(test & 0x40)) && (j==3)) )
      {
         printf("\n\n");
         for(k=0; k < num; k++)
         {
            printf("%d  ", k+1);
            for(i=7; i>=0; i--)
            {
               printf("%02X", SwitchSN[k][i]);
            }
            printf("\n");
         }
         printf("%d To quit or any other key.\n", k+1);

         printf("\n");
         printf("Pick a device\n");

         ch = getkeystroke();
         n = 0;
         n = (10*n + (ch - '0')) - 1;

         if( (n>num-1) || (n<0) )
         {
            n = 0;        //used to finish off the loop
            break;
         }

         owSerialNum(portnum, SwitchSN[n], FALSE);
         j = 1;
      }
      printf("\n");
      
      test = ReadSwitch12(portnum,clear);

      // This looks at the info byte to determine if it is a
      // two or one channel device.
      if(test & 0x40)
      {

         switch(j)
         {
            case 1: 
               sw.Chan_A = 0;
               sw.Chan_B = 0;
               break;
            case 2:
               sw.Chan_A = 0;
               sw.Chan_B = 1;
               break;
            case 3:
               sw.Chan_A = 1;
               sw.Chan_B = 0;
               break;
            case 4:
               sw.Chan_A = 1;
               sw.Chan_B = 1;
               break;
            default:
               sw.Chan_A = 1;
               sw.Chan_B = 1;
               j=0;
               break;
            }
      }
      else
      {
         switch(j)
         {
            case 1:
               sw.Chan_B = 0;
               sw.Chan_A = 0;
               break;
            case 2:
               sw.Chan_B = 0;
               sw.Chan_A = 1;
               break;
            default:
               sw.Chan_B = 0;
               sw.Chan_A = 1;
               j = 0;
               break;
         }
      }

      if(!SetSwitch12(portnum, SwitchSN[n], &sw))
      {
         msDelay(50);
         if(SetSwitch12(portnum, SwitchSN[n], &sw))
            msDelay(50);
         else
            printf("Switch not set\n");
      }

      test = ReadSwitch12(portnum,clear);

      printf("\n");

      for(i=7; i>=0; i--)
      {
         printf("%02X", SwitchSN[n][i]);
      }
      printf("\n");

      SwitchStateToString12(test, out);
      printf("%s", out);

      j++;

   }
   while(1);

   // release the 1-Wire Net
   owRelease(portnum,return_msg);
   printf("%s",return_msg);
   exit(0);

   return 0;
}
Exemplo n.º 27
0
//---------------------------------------------------------------------------
// The main program that performs the operations on switches
//
int main(int argc, char **argv)
{
   short test;                     //info byte data
   short clear=0;                  //used to clear the button
   short done;                     //to tell when the user is done
   SwitchProps sw;                 //used to set Channel A and B
   uchar SwitchSN[MAXDEVICES][8];  //the serial number for the devices
   int num;                        //for the number of devices present
   int i,j,n,count,result;         //loop counters and indexes
   char out[140];                  //used for output of the info byte data
   int portnum=0;
   long select;                    //inputed number from user

   //----------------------------------------
   // Introduction header
   printf("\n/---------------------------------------------\n");
   printf("  Switch - V3.00\n"
          "  The following is a test to excersize the \n"
          "  setting of the state in a DS2406.\n");

   printf("  Press any CTRL-C to stop this program.\n\n");

   // check for required port name
   if (argc != 2)
   {
      printf("1-Wire Net name required on command line!\n"
             " (example: \"COM1\" (Win32 DS2480),\"/dev/cua0\" "
             "(Linux DS2480),\"1\" (Win32 TMEX)\n");
      exit(1);
   }

   // attempt to acquire the 1-Wire Net
   if ((portnum = owAcquireEx(argv[1])) < 0)
   {
      OWERROR_DUMP(stdout);
      exit(1);
   }

   // success
   printf("Port opened: %s\n",argv[1]);

   // this is to get the number of the devices and the serial numbers
   num = FindDevices(portnum, &SwitchSN[0], SWITCH_FAMILY, MAXDEVICES);

   // setting up the first print out for the frist device
   owSerialNum(portnum, SwitchSN[0], FALSE);

   printf("\n");
   n=0;
   if(owAccess(portnum))
   {
      // loop while not done
      do
      {
         test = ReadSwitch12(portnum, clear);

         for(i=7; i>=0; i--)
            printf("%02X", SwitchSN[n][i]);

         printf("\n");

         count = SwitchStateToString12(test, out);
         printf("%s", out);

         // print menu
         select = 1;
         if (!EnterNum("\n\n(1) Display the switch Info\n"
              "(2) Clear activity Latches\n"
              "(3) Set Flip Flop(s) on switch\n"
              "(4) Select different device\n"
              "(5) Quit\n"
              "Select a Number", 1, &select, 1, 5))
              break;
         printf("\n\n");

         // do something from the menu selection
         clear = FALSE;
         switch(select)
         {
            case 1: // Display the switch Info
               done = FALSE;
               break;
            case 2: // Clear activity Latches
               clear = TRUE;
               done = FALSE;
               break;
            case 3: // Set Flip Flop(s) on switch
               select = 0;
               if (EnterNum("Channel A Flip Flop (1 set, 0 clear)",
                    1, &select, 0, 1))
               {
                  sw.Chan_A = (uchar)select;

                  if(test & 0x40)
                  {
                     if (EnterNum("Channel B Flip Flop (1 set, 0 clear)",
                          1, &select, 0, 1))
                     {
                        sw.Chan_B = (uchar)select;
                        done = FALSE;
                     }
                  }
                  else
                  {
                    sw.Chan_B = 0;
                    done = FALSE;
                  }
                  printf("\n");
               }

               // proceed to setting switch state if not done
               if (!done)
               {
                  // loop to attempt to set the switch (try up to 5 times)
                  count = 0;
                  do
                  {
                     result = SetSwitch12(portnum, SwitchSN[n], sw);

                     // if failed then delay to let things settle
                     if (!result)
                        msDelay(50);
                  }
                  while ((count++ < 5) && (result != TRUE));

                  // if could not set then show error
                  if (!result)
                     printf("Could not set Switch!\n");
               }
               break;
            case 4: // Switch Devices
               // print the device list
               for(j=0; j < num; j++)
               {
                  printf("%d  ", j+1);
                  for(i=7; i>=0; i--)
                  {
                     printf("%02X", SwitchSN[j][i]);
                  }
                  printf("\n");
               }
               printf("\n");

               // select the device
               select = 0;
               if (EnterNum("Select Device",1, &select, 1, num))
               {
                  n = (int)(select - 1);
                  owSerialNum(portnum, SwitchSN[n], FALSE);
                  done = FALSE;
               }
               break;

            case 5: // Done
               done = TRUE;
               break;
               default:
            break;
         }
      }
      while (!done);
   }
   //One Wire Access
   owRelease(portnum);
   printf("Closing port %s.\n", argv[1]);
   exit(0);

   return 0;
}
Exemplo n.º 28
0
Arquivo: owllu.c Projeto: bcl/digitemp
//--------------------------------------------------------------------------
// Set the 1-Wire Net line level.  The values for new_level are
// as follows:
//
// 'portnum'   - number 0 to MAX_PORTNUM-1.  This number was provided to
//               OpenCOM to indicate the port number.
// 'new_level' - new level defined as
//                MODE_NORMAL     0x00
//                MODE_STRONG5    0x02
//                MODE_PROGRAM    0x04
//                MODE_BREAK      0x08 (not supported)
//
// Returns:  current 1-Wire Net level
//
SMALLINT owLevel(int portnum, SMALLINT new_level)
{
   uchar sendpacket[10],readbuffer[10];
   uchar sendlen=0;
   uchar rt=FALSE;

   // check if need to change level
   if (new_level != ULevel[portnum])
   {
      // check if just putting back to normal
      if (new_level == MODE_NORMAL)
      {
         // check if correct mode
         if (UMode[portnum] != MODSEL_COMMAND)
         {
            UMode[portnum] = MODSEL_COMMAND;
            sendpacket[sendlen++] = MODE_COMMAND;
         }

         // stop pulse command
         sendpacket[sendlen++] = MODE_STOP_PULSE;

         // flush the buffers
         FlushCOM(portnum);

         // send the packet
         if (WriteCOM(portnum,sendlen,sendpacket))
         {
            msDelay(4);
            // read back the 1 byte response
            if (ReadCOM(portnum,1,readbuffer) == 1)
            {
               // check response byte
               if ((readbuffer[0] & 0xE0) == 0xE0)
               {
                  rt = TRUE;
                  ULevel[portnum] = MODE_NORMAL;
               }
            }
            else
               OWERROR(OWERROR_READCOM_FAILED);
         }
         else
            OWERROR(OWERROR_WRITECOM_FAILED);
      }
      // set new level
      else
      {
         // check if correct mode
         if (UMode[portnum] != MODSEL_COMMAND)
         {
            UMode[portnum] = MODSEL_COMMAND;
            sendpacket[sendlen++] = MODE_COMMAND;
         }

         // strong 5 volts
         if (new_level == MODE_STRONG5)
         {
            // set the SPUD time value
            sendpacket[sendlen++] = CMD_CONFIG | PARMSEL_5VPULSE | PARMSET_infinite;
            // add the command to begin the pulse
            sendpacket[sendlen++] = CMD_COMM | FUNCTSEL_CHMOD | SPEEDSEL_PULSE | BITPOL_5V;
         }
         // 12 volts
         else if (new_level == MODE_PROGRAM)
         {
            // check if programming voltage available
            if (!ProgramAvailable[portnum])
               return MODE_NORMAL;

            // set the PPD time value
            sendpacket[sendlen++] = CMD_CONFIG | PARMSEL_12VPULSE | PARMSET_infinite;
            // add the command to begin the pulse
            sendpacket[sendlen++] = CMD_COMM | FUNCTSEL_CHMOD | SPEEDSEL_PULSE | BITPOL_12V;
         }

         // flush the buffers
         FlushCOM(portnum);

         // send the packet
         if (WriteCOM(portnum,sendlen,sendpacket))
         {
            // read back the 1 byte response from setting time limit
            if (ReadCOM(portnum,1,readbuffer) == 1)
            {
               // check response byte
               if ((readbuffer[0] & 0x81) == 0)
               {
                  ULevel[portnum] = new_level;
                  rt = TRUE;
               }
            }
            else
               OWERROR(OWERROR_READCOM_FAILED);
         }
         else
            OWERROR(OWERROR_WRITECOM_FAILED);
      }

      // if lost communication with DS2480 then reset
      if (rt != TRUE)
         DS2480Detect(portnum);
   }

   // return the current level
   return ULevel[portnum];
}
Exemplo n.º 29
0
void io_toggle(long delayMs, GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
    HAL_GPIO_WritePin(GPIOx, GPIO_Pin, GPIO_PIN_SET);
    msDelay(delayMs);
    HAL_GPIO_WritePin(GPIOx, GPIO_Pin, GPIO_PIN_RESET);
}
Exemplo n.º 30
0
/* LWIP kickoff and PHY link monitor thread */
static void vSetupIFTask(void *pvParameters) {
	ip_addr_t ipaddr, netmask, gw;
	volatile s32_t tcpipdone = 0;
	uint32_t physts;
	static int prt_ip = 0;
	
	DEBUGSTR("LWIP HTTP Web Server FreeRTOS Demo...\r\n");
	
	/* Wait until the TCP/IP thread is finished before
	   continuing or wierd things may happen */
	DEBUGSTR("Waiting for TCPIP thread to initialize...\r\n");
	tcpip_init(tcpip_init_done_signal, (void *) &tcpipdone);
	while (!tcpipdone) {
		msDelay(1);
	}

	DEBUGSTR("Starting LWIP HTTP server...\r\n");

	/* Static IP assignment */
#if LWIP_DHCP
	IP4_ADDR(&gw, 0, 0, 0, 0);
	IP4_ADDR(&ipaddr, 0, 0, 0, 0);
	IP4_ADDR(&netmask, 0, 0, 0, 0);
#else
	IP4_ADDR(&gw, 10, 1, 10, 1);
	IP4_ADDR(&ipaddr, 10, 1, 10, 234);
	IP4_ADDR(&netmask, 255, 255, 255, 0);
#endif

	/* Add netif interface for lpc17xx_8x */
	memset(&lpc_netif, 0, sizeof(lpc_netif));
	if (!netif_add(&lpc_netif, &ipaddr, &netmask, &gw, NULL, lpc_enetif_init,
				   tcpip_input)) {
		DEBUGSTR("Net interface failed to initialize\r\n");
		while(1);			   
	}
	netif_set_default(&lpc_netif);
	netif_set_up(&lpc_netif);

	/* Enable MAC interrupts only after LWIP is ready */
	NVIC_SetPriority(ETHERNET_IRQn, config_ETHERNET_INTERRUPT_PRIORITY);
	NVIC_EnableIRQ(ETHERNET_IRQn);

#if LWIP_DHCP
	dhcp_start(&lpc_netif);
#endif
	
	/* Initialize and start application */
	http_server_netconn_init();
	
	/* This loop monitors the PHY link and will handle cable events
	   via the PHY driver. */
	while (1) {
		/* Call the PHY status update state machine once in a while
		   to keep the link status up-to-date */
		physts = lpcPHYStsPoll();

		/* Only check for connection state when the PHY status has changed */
		if (physts & PHY_LINK_CHANGED) {
			if (physts & PHY_LINK_CONNECTED) {
				Board_LED_Set(0, true);
				prt_ip = 0;

				/* Set interface speed and duplex */
				if (physts & PHY_LINK_SPEED100) {
					Chip_ENET_Set100Mbps(LPC_ETHERNET);
					NETIF_INIT_SNMP(&lpc_netif, snmp_ifType_ethernet_csmacd, 100000000);
				}
				else {
					Chip_ENET_Set10Mbps(LPC_ETHERNET);
					NETIF_INIT_SNMP(&lpc_netif, snmp_ifType_ethernet_csmacd, 10000000);
				}
				if (physts & PHY_LINK_FULLDUPLX) {
					Chip_ENET_SetFullDuplex(LPC_ETHERNET);
				}
				else {
					Chip_ENET_SetHalfDuplex(LPC_ETHERNET);
				}

				tcpip_callback_with_block((tcpip_callback_fn) netif_set_link_up,
										  (void *) &lpc_netif, 1);
			}
			else {
				Board_LED_Set(0, false);
				tcpip_callback_with_block((tcpip_callback_fn) netif_set_link_down,
										  (void *) &lpc_netif, 1);
			}

			/* Delay for link detection (250mS) */
			vTaskDelay(configTICK_RATE_HZ / 4);
		}

		/* Print IP address info */
		if (!prt_ip) {
			if (lpc_netif.ip_addr.addr) {
				static char tmp_buff[16];
				DEBUGOUT("IP_ADDR    : %s\r\n", ipaddr_ntoa_r((const ip_addr_t *) &lpc_netif.ip_addr, tmp_buff, 16));
				DEBUGOUT("NET_MASK   : %s\r\n", ipaddr_ntoa_r((const ip_addr_t *) &lpc_netif.netmask, tmp_buff, 16));
				DEBUGOUT("GATEWAY_IP : %s\r\n", ipaddr_ntoa_r((const ip_addr_t *) &lpc_netif.gw, tmp_buff, 16));
				prt_ip = 1;
			}
		}
	}
}