Exemple #1
0
inline void os_disable_interrupt() {
    cli();
}
Exemple #2
0
/*
 * Update the segment registers with new values from the pcb.
 *
 * We have to do this carefully, and in the following order,
 * in case any of the selectors points at a bogus descriptor.
 * If they do, we'll catch trap with on_trap and return 1.
 * returns 0 on success.
 *
 * This is particularly tricky for %gs.
 * This routine must be executed under a cli.
 */
int
update_sregs(struct regs *rp,  klwp_t *lwp)
{
	pcb_t *pcb = &lwp->lwp_pcb;
	ulong_t	kgsbase;
	on_trap_data_t	otd;
	int rc = 0;

	if (!on_trap(&otd, OT_SEGMENT_ACCESS)) {

#if defined(__xpv)
		/*
		 * On the hyervisor this is easy. The hypercall below will
		 * swapgs and load %gs with the user selector. If the user
		 * selector is bad the hypervisor will catch the fault and
		 * load %gs with the null selector instead. Either way the
		 * kernel's gsbase is not damaged.
		 */
		kgsbase = (ulong_t)CPU;
		if (HYPERVISOR_set_segment_base(SEGBASE_GS_USER_SEL,
		    pcb->pcb_gs) != 0) {
				no_trap();
				return (1);
		}

		rp->r_gs = pcb->pcb_gs;
		ASSERT((cpu_t *)kgsbase == CPU);

#else	/* __xpv */

		/*
		 * A little more complicated running native.
		 */
		kgsbase = (ulong_t)CPU;
		__set_gs(pcb->pcb_gs);

		/*
		 * If __set_gs fails it's because the new %gs is a bad %gs,
		 * we'll be taking a trap but with the original %gs and %gsbase
		 * undamaged (i.e. pointing at curcpu).
		 *
		 * We've just mucked up the kernel's gsbase.  Oops.  In
		 * particular we can't take any traps at all.  Make the newly
		 * computed gsbase be the hidden gs via __swapgs, and fix
		 * the kernel's gsbase back again. Later, when we return to
		 * userland we'll swapgs again restoring gsbase just loaded
		 * above.
		 */
		__swapgs();
		rp->r_gs = pcb->pcb_gs;

		/*
		 * restore kernel's gsbase
		 */
		wrmsr(MSR_AMD_GSBASE, kgsbase);

#endif	/* __xpv */

		/*
		 * Only override the descriptor base address if
		 * r_gs == LWPGS_SEL or if r_gs == NULL. A note on
		 * NULL descriptors -- 32-bit programs take faults
		 * if they deference NULL descriptors; however,
		 * when 64-bit programs load them into %fs or %gs,
		 * they DONT fault -- only the base address remains
		 * whatever it was from the last load.   Urk.
		 *
		 * XXX - note that lwp_setprivate now sets %fs/%gs to the
		 * null selector for 64 bit processes. Whereas before
		 * %fs/%gs were set to LWP(FS|GS)_SEL regardless of
		 * the process's data model. For now we check for both
		 * values so that the kernel can also support the older
		 * libc. This should be ripped out at some point in the
		 * future.
		 */
		if (pcb->pcb_gs == LWPGS_SEL || pcb->pcb_gs == 0) {
#if defined(__xpv)
			if (HYPERVISOR_set_segment_base(SEGBASE_GS_USER,
			    pcb->pcb_gsbase)) {
				no_trap();
				return (1);
			}
#else
			wrmsr(MSR_AMD_KGSBASE, pcb->pcb_gsbase);
#endif
		}

		__set_ds(pcb->pcb_ds);
		rp->r_ds = pcb->pcb_ds;

		__set_es(pcb->pcb_es);
		rp->r_es = pcb->pcb_es;

		__set_fs(pcb->pcb_fs);
		rp->r_fs = pcb->pcb_fs;

		/*
		 * Same as for %gs
		 */
		if (pcb->pcb_fs == LWPFS_SEL || pcb->pcb_fs == 0) {
#if defined(__xpv)
			if (HYPERVISOR_set_segment_base(SEGBASE_FS,
			    pcb->pcb_fsbase)) {
				no_trap();
				return (1);
			}
#else
			wrmsr(MSR_AMD_FSBASE, pcb->pcb_fsbase);
#endif
		}

	} else {
		cli();
		rc = 1;
	}
	no_trap();
	return (rc);
}
/** Discard all data in the ring buffer.
 *
 * @note This function must not be called with interrupts disabled.
 */
void SerialRingBuffer::flush() {
  uint8_t s = SREG;
  cli();
  head_ = tail_ = 0;
  SREG = s;
}
Exemple #4
0
static void
sim710_soft_reset (struct Scsi_Host *host)
{
    unsigned long flags;
#ifdef CONFIG_TP34V_SCSI
    struct sim710_hostdata *hostdata = (struct sim710_hostdata *)
	host->hostdata[0];
#endif

    save_flags(flags);
    cli();
#ifdef CONFIG_TP34V_SCSI
    tpvic.loc_icr[irq_index[hostdata->chip]].icr = 0x80;
#endif
    /*
     * Do a soft reset of the chip so that everything is
     * reinitialized to the power-on state.
     *
     * Basically follow the procedure outlined in the NCR53c700
     * data manual under Chapter Six, How to Use, Steps Necessary to
     * Start SCRIPTS, with the exception of actually starting the
     * script and setting up the synchronous transfer gunk.
     */

    /* XXX Should we reset the scsi bus here? */

    NCR_write8(SCNTL1_REG, SCNTL1_RST);		/* Reset the bus */
    udelay(50);
    NCR_write8(SCNTL1_REG, 0);

    udelay(500);

    NCR_write8(ISTAT_REG, ISTAT_10_SRST);	/* Reset the chip */
    udelay(50);
    NCR_write8(ISTAT_REG, 0);

    mdelay(1000);				/* Let devices recover */

    NCR_write8(DCNTL_REG, DCNTL_10_COM | DCNTL_700_CF_3);
    NCR_write8(CTEST7_REG, CTEST7_10_CDIS|CTEST7_STD);
    NCR_write8(DMODE_REG, DMODE_10_BL_8 | DMODE_10_FC2);
    NCR_write8(SCID_REG, 1 << host->this_id);
    NCR_write8(SBCL_REG, 0);
    NCR_write8(SXFER_REG, 0);
    NCR_write8(SCNTL1_REG, SCNTL1_ESR_700);
    NCR_write8(SCNTL0_REG, SCNTL0_EPC | SCNTL0_EPG_700 | SCNTL0_ARB1 |
		SCNTL0_ARB2);

    NCR_write8(DIEN_REG, DIEN_700_BF |
		DIEN_ABRT | DIEN_SSI | DIEN_SIR | DIEN_700_OPC);

    NCR_write8(SIEN_REG_700,
	    SIEN_PAR | SIEN_700_STO | SIEN_RST | SIEN_UDC | SIEN_SGE | SIEN_MA);


#ifdef CONFIG_TP34V_SCSI
    tpvic.loc_icr[irq_index[hostdata->chip]].icr = 0x30 | TP34V_SCSI0n1_IPL;
#endif

    restore_flags(flags);
}
void unregister_netdev(struct device *dev)
{
	struct device *d = dev_base;
	unsigned long flags;
	int i;

	save_flags(flags);
	cli();

	if (dev == NULL) 
	{
		printk("was NULL\n");
		restore_flags(flags);
		return;
	}
	/* else */
	if (dev->start)
		printk("ERROR '%s' busy and not MOD_IN_USE.\n", dev->name);

	/*
	 * 	must jump over main_device+aliases
	 * 	avoid alias devices unregistration so that only
	 * 	net_alias module manages them
	 */
#ifdef CONFIG_NET_ALIAS		
	if (dev_base == dev)
		dev_base = net_alias_nextdev(dev);
	else
	{
		while(d && (net_alias_nextdev(d) != dev)) /* skip aliases */
			d = net_alias_nextdev(d);
	  
		if (d && (net_alias_nextdev(d) == dev))
		{
			/*
			 * 	Critical: Bypass by consider devices as blocks (maindev+aliases)
			 */
			net_alias_nextdev_set(d, net_alias_nextdev(dev)); 
		}
#else
	if (dev_base == dev)
		dev_base = dev->next;
	else 
	{
		while (d && (d->next != dev))
			d = d->next;
		
		if (d && (d->next == dev)) 
		{
			d->next = dev->next;
		}
#endif
		else 
		{
			printk("unregister_netdev: '%s' not found\n", dev->name);
			restore_flags(flags);
			return;
		}
	}
	for (i = 0; i < MAX_ETH_CARDS; ++i) 
	{
		if (ethdev_index[i] == dev) 
		{
			ethdev_index[i] = NULL;
			break;
		}
	}

	restore_flags(flags);

	/*
	 *	You can i.e use a interfaces in a route though it is not up.
	 *	We call close_dev (which is changed: it will down a device even if
	 *	dev->flags==0 (but it will not call dev->stop if IFF_UP
	 *	is not set).
	 *	This will call notifier_call_chain(&netdev_chain, NETDEV_DOWN, dev),
	 *	dev_mc_discard(dev), ....
	 */
	 
	dev_close(dev);
}
Exemple #6
0
void set_date(){
	clear_pixelMatrix();
	print_date(POS_DATE_SET);
	print_year();
	print_symbol(16,17, hakenSymb,108,46);
	print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_dateXPos() + get_dayWidth() / 2 - 4, POS_DATE_SET - 10);
	update_LCD();
	int old_selectedItem = 0;
	int item = 0;
	
	while (item != 3){
		cli();
		btn_drehenc_pushed = false;
		sei();
		while(!btn_drehenc_pushed){
			if(rotary != 0){
				item += rotary;
				cli();
				rotary = 0;
				sei();
				item = item % 4;
				if(item<0){
					item += 4;
				}
			
				switch (old_selectedItem){
					case 0: for(int x = 0; x<128; x++){
						for(int y = 0; y<10; y++)
						reset_pixel(x,y);
					} break;
					case 1: for(int x = 0; x<128; x++){
						for(int y = 0; y<10; y++)
						reset_pixel(x,y);
					}break;
					case 2: for(int x = 0; x<128; x++){
						for(int y = 30; y<40; y++)
						reset_pixel(x,y);
					}break;
					case 3: for(int x = 94; x<104; x++){
						for(int y = 2+3*15+5; y<2+3*15+5+8; y++)
						reset_pixel(x,y);
					}break;
				}
				switch (item) {
					case 0: print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_dateXPos() + get_dayWidth() / 2 - 4, POS_DATE_SET - 10); break; //-4 = halbe Länge Herz
					case 1: print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_dateXPos() + get_dayWidth() + get_monthWidth() / 2 - 4, POS_DATE_SET - 10); break;
					case 2: print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_yearXPos() + get_yearWidth() / 2 - 4, YPOS_YEAR - 10);break;
					case 3: print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, 94, 2+3*15+5);break;
				}
				old_selectedItem = item;
				update_LCD();
			}
			goodNight();
			check_light();
		}
		cli();
		btn_drehenc_pushed = false;
		sei();
		switch (item) {
			case 0: {
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinOffenSymb, get_dateXPos() + get_dayWidth() / 2 - 4, POS_DATE_SET - 10);
				update_LCD();
				set_day();
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_dateXPos() + get_dayWidth() / 2 - 4, POS_DATE_SET - 10);
				break;
			}
			case 1:{
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinOffenSymb, get_dateXPos() + get_dayWidth() + get_monthWidth() / 2 - 4, POS_DATE_SET - 10);
				update_LCD();
				set_month();
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_dateXPos() + get_dayWidth() + get_monthWidth() / 2 - 4, POS_DATE_SET - 10);
				break;
			}
			case 2: {
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinOffenSymb,  get_yearXPos() + get_yearWidth() / 2 - 4, YPOS_YEAR - 10);
				update_LCD();
				set_year();
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb,  get_yearXPos() + get_yearWidth() / 2 - 4, YPOS_YEAR - 10);
				break;
			}
			default: break;
		}
		update_LCD();
	}
}
Exemple #7
0
void WarGServer::start(){
	clients_ptr=&clients;
	serv=socket(AF_INET,SOCK_STREAM,0);
	if(serv<0){ cout<<"sock error\n"; return;}

	memset(&serv_addr,sizeof serv_addr,0);	

	port=9898;
	serv_addr.sin_family=AF_INET;
	serv_addr.sin_addr.s_addr=INADDR_ANY;
	serv_addr.sin_port =htons(port);
		

	if(bind(serv,(struct sockaddr*)&serv_addr,sizeof serv_addr)<0){
		cout<<"error binding\n"; return;
		}

	listen(serv,5);
	FD_SET(serv,&master);
	fdmax=serv;
	clilen=sizeof cli_addr;
	int newsock;
	while(true){
	read_fds=master;
		if(select(fdmax+1,&read_fds,NULL,NULL,NULL)==-1){
			cout<<"select error\n";
			return;		
		}
		for(int i=0;i<=fdmax;i++){
		 if(FD_ISSET(i,&read_fds)){//data to be red
			if(i==serv){//new connection
			if((newsock=accept(serv,(struct sockaddr*)&cli_addr,&clilen))!=-1){
			      char ip[INET_ADDRSTRLEN];
			      inet_ntop(AF_INET,&cli_addr.sin_addr.s_addr,ip,INET_ADDRSTRLEN);
			      stringstream ss;
			      ss<<"Connection from "<<ip<<" accepted.";

			      writeLog(ss.str());


			      Client cli(newsock);
			      cli.setIp((string)ip);
			       clients.push_back(cli);
 	                	FD_SET(newsock,&master);
				if(newsock >fdmax){
				fdmax=newsock;
				}
				cout<<"new connection, "<<newsock<<endl;
			//	send_welcome(newsock);
				send_data(newsock,"LOGON: ");
			}else{
		              cout<<"error accepting\n";
			  //close(newsock);
		         }		
			}else{ //handle data from client
			  if(handle_client(i)==0){ //connection lost?
			  	  close_connection(i);
			   }
			}

		
		}
	}//for
	}//while
}
void HardwareSerial::flush()
{
  cli();
  _rxfifo->idx_r = _rxfifo->idx_w = 0;
  sei();
}
Exemple #9
0
/*-----------------------------------------------------------------------------
*  process received bus telegrams
*/
static void ProcessBus(void) {

    uint8_t       ret;
    TClient       *pClient;
    TBusMsgType   msgType;
    uint8_t       i;
    uint8_t       *p;
    bool          msgForMe = false;
   
    ret = BusCheck();

    if (ret == BUS_MSG_OK) {
        msgType = spRxBusMsg->type; 
        switch (msgType) {  
        case eBusDevReqReboot:
        case eBusDevRespSwitchState:
        case eBusDevReqActualValue:
        case eBusDevReqSetClientAddr:
        case eBusDevReqGetClientAddr:
        case eBusDevReqInfo:
        case eBusDevReqSetAddr:
        case eBusDevReqEepromRead:
        case eBusDevReqEepromWrite:
            if (spRxBusMsg->msg.devBus.receiverAddr == MY_ADDR) {
                msgForMe = true;
            }
            break;
        default:
            break;
        }
    }

    if (msgForMe == false) {
        return;
    }

    switch (msgType) {
    case eBusDevReqReboot:
        /* reset controller with watchdog */    
        /* set watchdog timeout to shortest value (14 ms) */                     
        cli();
        wdt_enable(WDTO_15MS);
        /* wait for reset */
        while (1);
        break;   
    case eBusDevRespSwitchState:
        pClient = sClient;
        for (i = 0; i < sNumClients; i++) {
            if ((pClient->address == spRxBusMsg->senderAddr) &&
                (pClient->state == eWaitForConfirmation)) {
                if (spRxBusMsg->msg.devBus.x.devResp.switchState.switchState == sWindSwitch) {
                    pClient->state = eConfirmationOK;
                }
                break;
            }
            pClient++;
        }
        break;
    case eBusDevReqActualValue:
        sTxBusMsg.senderAddr = MY_ADDR; 
        sTxBusMsg.type = eBusDevRespActualValue;
        sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr;
        sTxBusMsg.msg.devBus.x.devResp.actualValue.devType = eBusDevTypeWind;
        sTxBusMsg.msg.devBus.x.devResp.actualValue.actualValue.wind.state = sWindSwitch;
        sTxBusMsg.msg.devBus.x.devResp.actualValue.actualValue.wind.wind = sMaxWind; //sWind;
        BusSend(&sTxBusMsg);           
        break;
    case eBusDevReqSetClientAddr:
        sTxBusMsg.senderAddr = MY_ADDR; 
        sTxBusMsg.type = eBusDevRespSetClientAddr;  
        sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr;
        for (i = 0; i < BUS_MAX_CLIENT_NUM; i++) {
            p = &(spRxBusMsg->msg.devBus.x.devReq.setClientAddr.clientAddr[i]);
            eeprom_write_byte((uint8_t *)(CLIENT_ADDRESS_BASE + i), *p);
        }
        BusSend(&sTxBusMsg);
        GetClientListFromEeprom();
        break;
    case eBusDevReqGetClientAddr:
        sTxBusMsg.senderAddr = MY_ADDR; 
        sTxBusMsg.type = eBusDevRespGetClientAddr;  
        sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr;
        for (i = 0; i < BUS_MAX_CLIENT_NUM; i++) {
            p = &(sTxBusMsg.msg.devBus.x.devResp.getClientAddr.clientAddr[i]);
            *p = eeprom_read_byte((const uint8_t *)(CLIENT_ADDRESS_BASE + i));
        }
        BusSend(&sTxBusMsg);  
        break;
    case eBusDevReqInfo:
        sTxBusMsg.type = eBusDevRespInfo;  
        sTxBusMsg.senderAddr = MY_ADDR; 
        sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr;
        sTxBusMsg.msg.devBus.x.devResp.info.devType = eBusDevTypeWind;
        strncpy((char *)(sTxBusMsg.msg.devBus.x.devResp.info.version),
                version, BUS_DEV_INFO_VERSION_LEN); 
        sTxBusMsg.msg.devBus.x.devResp.info.version[BUS_DEV_INFO_VERSION_LEN - 1] = '\0';
        BusSend(&sTxBusMsg);  
        break;
    case eBusDevReqSetAddr:
        sTxBusMsg.senderAddr = MY_ADDR; 
        sTxBusMsg.type = eBusDevRespSetAddr;  
        sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr;
        p = &(spRxBusMsg->msg.devBus.x.devReq.setAddr.addr);
        eeprom_write_byte((uint8_t *)MODUL_ADDRESS, *p);
        BusSend(&sTxBusMsg);  
        break;
    case eBusDevReqEepromRead:
        sTxBusMsg.senderAddr = MY_ADDR; 
        sTxBusMsg.type = eBusDevRespEepromRead;
        sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr;
        sTxBusMsg.msg.devBus.x.devResp.readEeprom.data = 
        eeprom_read_byte((const uint8_t *)spRxBusMsg->msg.devBus.x.devReq.readEeprom.addr);
        BusSend(&sTxBusMsg);  
        break;
    case eBusDevReqEepromWrite:
        sTxBusMsg.senderAddr = MY_ADDR; 
        sTxBusMsg.type = eBusDevRespEepromWrite;
        sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr;
        p = &(spRxBusMsg->msg.devBus.x.devReq.writeEeprom.data);
        eeprom_write_byte((uint8_t *)spRxBusMsg->msg.devBus.x.devReq.readEeprom.addr, *p);
        BusSend(&sTxBusMsg);  
        break;
    default:
        break;
    }   
}
Exemple #10
0
int main( void )
{
	int32_t tmp = 0x0;
//	uint8_t tmp8;

	cli();

	SetupInterruptPins();

	y_pos = 0;
	x_pos = 0;

//	DDRC = _BV(PC6); //output pin
	SetupDriverPins();

	setup_clock();
	setup_timers();
	SetupPrintf();

	USB_ZeroPrescaler();
	USB_Init();

	sei();

	printf("hello world");

//	motorflags |= 0x01;
//	set_motor_pwm(PWM_MAX);
//	forward();
//	while(1);

//AutoSlop();

/*
AutoSlop();
while(1);
*/

//		dec_backward();
//		set_dec_pwm(0x1fff);
//		ra_forward();
//		set_ra_pwm(0x3fff);

	while(1)
	{
		cli();
//		tmp8 = usbHasEvent;
		//add accumulated radial encoder output
		y_pos += y_tmp;
		y_tmp = 0;

		x_pos += x_tmp;
		x_tmp = 0;
		sei();

		if (usbHasEvent) ProcessUSB();

		if (jog_value_dec == 0) {
			tmp = ComputeOffset(&y_pos,&y_dest); //pid error value
			slew_dec(&tmp);
		}

		if (jog_value_ra == 0) {
			tmp = ComputeOffset(&x_pos,&x_dest); //pid error value
			slew_ra(&tmp);
		}

	}
	return 0;
}
Exemple #11
0
/** 
 * @brief emulate instruction 
 * @return returns false if something goes wrong (e.g. illegal instruction)
 *
 * Current limitations:
 * 
 * - Illegal instructions are not implemented
 * - Excess cycles due to page boundary crossing are not calculated
 * - Some known architectural bugs are not emulated
 */
bool Cpu::emulate()
{
  /* fetch instruction */
  uint8_t insn = fetch_op();
  bool retval = true;
  /* emulate instruction */
  switch(insn)
  {
  /* BRK */
  case 0x0: brk(); break;
  /* ORA (nn,X) */
  case 0x1: ora(load_byte(addr_indx()),6); break;
  /* ORA nn */
  case 0x5: ora(load_byte(addr_zero()),3); break;
  /* ASL nn */
  case 0x6: asl_mem(addr_zero(),5); break;
  /* PHP */
  case 0x8: php(); break;
  /* ORA #nn */
  case 0x9: ora(fetch_op(),2); break;
  /* ASL A */
  case 0xA: asl_a(); break;
  /* ORA nnnn */
  case 0xD: ora(load_byte(addr_abs()),4); break;
  /* ASL nnnn */
  case 0xE: asl_mem(addr_abs(),6); break; 
  /* BPL nn */
  case 0x10: bpl(); break;
  /* ORA (nn,Y) */
  case 0x11: ora(load_byte(addr_indy()),5); break;
  /* ORA nn,X */
  case 0x15: ora(load_byte(addr_zerox()),4); break;
  /* ASL nn,X */
  case 0x16: asl_mem(addr_zerox(),6); break;
  /* CLC */
  case 0x18: clc(); break;
  /* ORA nnnn,Y */
  case 0x19: ora(load_byte(addr_absy()),4); break;
  /* ORA nnnn,X */
  case 0x1D: ora(load_byte(addr_absx()),4); break;
  /* ASL nnnn,X */
  case 0x1E: asl_mem(addr_absx(),7); break;
  /* JSR */
  case 0x20: jsr(); break;
  /* AND (nn,X) */
  case 0x21: _and(load_byte(addr_indx()),6); break;
  /* BIT nn */
  case 0x24: bit(addr_zero(),3); break;
  /* AND nn */
  case 0x25: _and(load_byte(addr_zero()),3); break;
  /* ROL nn */
  case 0x26: rol_mem(addr_zero(),5); break;
  /* PLP */
  case 0x28: plp(); break;
  /* AND #nn */
  case 0x29: _and(fetch_op(),2); break;
  /* ROL A */
  case 0x2A: rol_a(); break;
  /* BIT nnnn */
  case 0x2C: bit(addr_abs(),4); break;
  /* AND nnnn */
  case 0x2D: _and(load_byte(addr_abs()),4); break;
  /* ROL nnnn */
  case 0x2E: rol_mem(addr_abs(),6); break;
  /* BMI nn */
  case 0x30: bmi(); break;
  /* AND (nn,Y) */
  case 0x31: _and(load_byte(addr_indy()),5); break;               
  /* AND nn,X */
  case 0x35: _and(load_byte(addr_zerox()),4); break;
  /* ROL nn,X */
  case 0x36: rol_mem(addr_zerox(),6); break;
  /* SEC */
  case 0x38: sec(); break;
  /* AND nnnn,Y */
  case 0x39: _and(load_byte(addr_absy()),4); break;
  /* AND nnnn,X */
  case 0x3D: _and(load_byte(addr_absx()),4); break;
  /* ROL nnnn,X */
  case 0x3E: rol_mem(addr_absx(),7); break;
  /* RTI */
  case 0x40: rti(); break;
  /* EOR (nn,X) */
  case 0x41: eor(load_byte(addr_indx()),6); break;
  /* EOR nn */
  case 0x45: eor(load_byte(addr_zero()),3); break;
  /* LSR nn */
  case 0x46: lsr_mem(addr_zero(),5); break;
  /* PHA */
  case 0x48: pha(); break;
  /* EOR #nn */
  case 0x49: eor(fetch_op(),2); break;
  /* BVC */
  case 0x50: bvc(); break;
  /* JMP nnnn */
  case 0x4C: jmp(); break;
  /* EOR nnnn */
  case 0x4D: eor(load_byte(addr_abs()),4); break;
  /* LSR A */
  case 0x4A: lsr_a(); break;
  /* LSR nnnn */
  case 0x4E: lsr_mem(addr_abs(),6); break;
  /* EOR (nn,Y) */
  case 0x51: eor(load_byte(addr_indy()),5); break;
  /* EOR nn,X */
  case 0x55: eor(load_byte(addr_zerox()),4); break;
  /* LSR nn,X */
  case 0x56: lsr_mem(addr_zerox(),6); break;
  /* CLI */
  case 0x58: cli(); break;
  /* EOR nnnn,Y */
  case 0x59: eor(load_byte(addr_absy()),4); break;
  /* EOR nnnn,X */
  case 0x5D: eor(load_byte(addr_absx()),4); break;
  /* LSR nnnn,X */
  case 0x5E: lsr_mem(addr_absx(),7); break;
  /* RTS */
  case 0x60: rts(); break;
  /* ADC (nn,X) */
  case 0x61: adc(load_byte(addr_indx()),6); break;
  /* ADC nn */
  case 0x65: adc(load_byte(addr_zero()),3); break;
  /* ROR nn */
  case 0x66: ror_mem(addr_zero(),5); break;
  /* PLA */
  case 0x68: pla(); break;
  /* ADC #nn */
  case 0x69: adc(fetch_op(),2); break;
  /* ROR A */
  case 0x6A: ror_a(); break;
  /* JMP (nnnn) */
  case 0x6C: jmp_ind(); break;
  /* ADC nnnn */
  case 0x6D: adc(load_byte(addr_abs()),4); break;
  /* ROR nnnn */
  case 0x6E: ror_mem(addr_abs(),6); break;
  /* BVS */
  case 0x70: bvs(); break;
  /* ADC (nn,Y) */
  case 0x71: adc(load_byte(addr_indy()),5); break;
  /* ADC nn,X */
  case 0x75: adc(load_byte(addr_zerox()),4); break;
  /* ROR nn,X */
  case 0x76: ror_mem(addr_zerox(),6); break;
  /* SEI */
  case 0x78: sei(); break;
  /* ADC nnnn,Y */
  case 0x79: adc(load_byte(addr_absy()),4); break;
  /* ADC nnnn,X */
  case 0x7D: adc(load_byte(addr_absx()),4); break;
  /* ROR nnnn,X */
  case 0x7E: ror_mem(addr_absx(),7); break;
  /* STA (nn,X) */
  case 0x81: sta(addr_indx(),6); break;
  /* STY nn */
  case 0x84: sty(addr_zero(),3); break;
  /* STA nn */
  case 0x85: sta(addr_zero(),3); break;
  /* STX nn */
  case 0x86: stx(addr_zero(),3); break;
  /* DEY */
  case 0x88: dey(); break;
  /* TXA */
  case 0x8A: txa(); break;
  /* STY nnnn */
  case 0x8C: sty(addr_abs(),4); break;
  /* STA nnnn */
  case 0x8D: sta(addr_abs(),4); break;
  /* STX nnnn */
  case 0x8E: stx(addr_abs(),4); break;
  /* BCC nn */
  case 0x90: bcc(); break;
  /* STA (nn,Y) */
  case 0x91: sta(addr_indy(),6); break;
  /* STY nn,X */
  case 0x94: sty(addr_zerox(),4); break;
  /* STA nn,X */
  case 0x95: sta(addr_zerox(),4); break;
  /* STX nn,Y */
  case 0x96: stx(addr_zeroy(),4); break;
  /* TYA */
  case 0x98: tya(); break;
  /* STA nnnn,Y */
  case 0x99: sta(addr_absy(),5); break;
  /* TXS */
  case 0x9A: txs(); break;
  /* STA nnnn,X */
  case 0x9D: sta(addr_absx(),5); break;
  /* LDY #nn */
  case 0xA0: ldy(fetch_op(),2); break; 
  /* LDA (nn,X) */
  case 0xA1: lda(load_byte(addr_indx()),6); break;
  /* LDX #nn */
  case 0xA2: ldx(fetch_op(),2); break;
  /* LDY nn */
  case 0xA4: ldy(load_byte(addr_zero()),3); break;
  /* LDA nn */
  case 0xA5: lda(load_byte(addr_zero()),3); break;
  /* LDX nn */
  case 0xA6: ldx(load_byte(addr_zero()),3); break;
  /* TAY */
  case 0xA8: tay(); break;
  /* LDA #nn */
  case 0xA9: lda(fetch_op(),2); break;
  /* TAX */
  case 0xAA: tax(); break;
  /* LDY nnnn */
  case 0xAC: ldy(load_byte(addr_abs()),4); break;
  /* LDA nnnn */
  case 0xAD: lda(load_byte(addr_abs()),4); break;
  /* LDX nnnn */
  case 0xAE: ldx(load_byte(addr_abs()),4); break;
  /* BCS nn */
  case 0xB0: bcs(); break;
  /* LDA (nn,Y) */
  case 0xB1: lda(load_byte(addr_indy()),5); break;
  /* LDY nn,X */
  case 0xB4: ldy(load_byte(addr_zerox()),3); break;
  /* LDA nn,X */
  case 0xB5: lda(load_byte(addr_zerox()),3); break;
  /* LDX nn,Y */
  case 0xB6: ldx(load_byte(addr_zeroy()),3); break;
  /* CLV */
  case 0xB8: clv(); break;
  /* LDA nnnn,Y */
  case 0xB9: lda(load_byte(addr_absy()),4); break;
  /* TSX */
  case 0xBA: tsx(); break;
  /* LDY nnnn,X */
  case 0xBC: ldy(load_byte(addr_absx()),4); break;
  /* LDA nnnn,X */
  case 0xBD: lda(load_byte(addr_absx()),4); break;
  /* LDX nnnn,Y */
  case 0xBE: ldx(load_byte(addr_absy()),4); break;
  /* CPY #nn */
  case 0xC0: cpy(fetch_op(),2); break;
  /* CMP (nn,X) */
  case 0xC1: cmp(load_byte(addr_indx()),6); break;
  /* CPY nn */
  case 0xC4: cpy(load_byte(addr_zero()),3); break;
  /* CMP nn */
  case 0xC5: cmp(load_byte(addr_zero()),3); break;
  /* DEC nn */
  case 0xC6: dec(addr_zero(),5); break;
  /* INY */
  case 0xC8: iny(); break;
  /* CMP #nn */
  case 0xC9: cmp(fetch_op(),2); break;
  /* DEX */
  case 0xCA: dex(); break;
  /* CPY nnnn */
  case 0xCC: cpy(load_byte(addr_abs()),4); break;
  /* CMP nnnn */
  case 0xCD: cmp(load_byte(addr_abs()),4); break;
  /* DEC nnnn */
  case 0xCE: dec(addr_abs(),6); break;
  /* BNE nn */
  case 0xD0: bne(); break;
  /* CMP (nn,Y) */
  case 0xD1: cmp(load_byte(addr_indy()),5); break;
  /* CMP nn,X */
  case 0xD5: cmp(load_byte(addr_zerox()),4); break;
  /* DEC nn,X */
  case 0xD6: dec(addr_zerox(),6); break;
  /* CLD */
  case 0xD8: cld(); break;
  /* CMP nnnn,Y */
  case 0xD9: cmp(load_byte(addr_absy()),4); break;
  /* CMP nnnn,X */
  case 0xDD: cmp(load_byte(addr_absx()),4); break;
  /* DEC nnnn,X */
  case 0xDE: dec(addr_absx(),7); break;
  /* CPX #nn */
  case 0xE0: cpx(fetch_op(),2); break;
  /* SBC (nn,X) */
  case 0xE1: sbc(load_byte(addr_indx()),6); break;
  /* CPX nn */
  case 0xE4: cpx(load_byte(addr_zero()),3); break;
  /* SBC nn */
  case 0xE5: sbc(load_byte(addr_zero()),3); break;
  /* INC nn */
  case 0xE6: inc(addr_zero(),5); break;
  /* INX */
  case 0xE8: inx(); break;
  /* SBC #nn */
  case 0xE9: sbc(fetch_op(),2); break;
  /* NOP */
  case 0xEA: nop(); break;
  /* CPX nnnn */
  case 0xEC: cpx(load_byte(addr_abs()),4); break;
  /* SBC nnnn */
  case 0xED: sbc(load_byte(addr_abs()),4); break;
  /* INC nnnn */
  case 0xEE: inc(addr_abs(),6); break;
  /* BEQ nn */
  case 0xF0: beq(); break;
  /* SBC (nn,Y) */
  case 0xF1: sbc(load_byte(addr_indy()),5); break;
  /* SBC nn,X */
  case 0xF5: sbc(load_byte(addr_zerox()),4); break;
  /* INC nn,X */
  case 0xF6: inc(addr_zerox(),6); break;
  /* SED */
  case 0xF8: sed(); break;
  /* SBC nnnn,Y */
  case 0xF9: sbc(load_byte(addr_absy()),4); break;
  /* SBC nnnn,X */
  case 0xFD: sbc(load_byte(addr_absx()),4); break;
  /* INC nnnn,X */
  case 0xFE: inc(addr_absx(),7); break;
  /* Unknown or illegal instruction */
  default:
    D("Unknown instruction: %X at %04x\n", insn,pc());
    retval = false;
  }
  return retval;
}
Exemple #12
0
void main(void)
{
	int receiveInt = 0;
	setInt = 0;
	setFlag = 0; //false
	unsigned long sClk, pClk;
	
	cli(); //
	
	SetSystemClock(CLK_SCLKSEL_RC32M_gc, CLK_PSADIV_1_gc,
	CLK_PSBCDIV_1_1_gc);
	GetSystemClocks(&sClk, &pClk);
	
	/*
	* Programmable interrupt controller configuration
	*/
	PMIC_CTRL = PMIC_HILVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_LOLVLEN_bm; //enable all levels of interrupts
	
	PORTH_DIR = 0xFF;
	PORTQ_DIR = 0x0F; //port q lower 3 bits control access to usb and other stuff so get access with these two lines
	PORTQ_OUT = 0x07; //if using port F make this hex 5.
	/*
	* Serial set up
	*/
	//initialize the usart d0 for 57600 baud with 8 data bits, no parity, and 1 stop bit, interrupts on low (porth set to this for debugging purposes)
	USART_init(&serialStruct, 0xD0, pClk, (_USART_RXCIL_LO | _USART_TXCIL_LO), 576, -4, _USART_CHSZ_8BIT, _USART_PM_DISABLED, _USART_SM_1BIT);
	USART_buffer_init(&serialStruct, 100, 100); //initialize the circular buffers
	USART_enable(&serialStruct, USART_TXEN_bm | USART_RXEN_bm); //enable the USART
	serialStruct.fOutMode = _OUTPUT_CRLF; //append a carriage return and a line feed to every output.
	serialStruct.fInMode = _INPUT_CR | _INPUT_TTY | _INPUT_ECHO; //echo input back to the terminal and set up for keyboard input.
	
	/*
	* Timer E0 setup for servo PWM
	*/
	TCE0_CTRLA = TC_CLKSEL_DIV64_gc; //set timer to div/64
	TCE0_CTRLB = 0x10 | TC_WGMODE_SS_gc; //turn on capture(CCAEN) and set waveform generation mode to PWM
	TCE0_CTRLC = 0x00; //turn off compares
	TCE0_CTRLD = 0x00; //turn off events
	TCE0_CTRLE = 0x00; //turn off byte mode
	TCE0_PER = 10000; //set the top of the period to 20ms
	TCE0_CCA = 350; //lower bound, datasheet says 600 microseconds(which should be 300) but that is to low so set it to this
	TCE0_INTCTRLA = 0x01; //turn on Overflow interrupt at low priority.
	
	/*
	* Port J configuration for pushbutton incrementing
	*/
	PORTJ_DIR = 0x00; //all pins as input
	PORTJ_INTCTRL = 0x05; //turn on both interrupts to low
	PORTJ_PIN0CTRL = 0x01; //set pin 0 so only rising edges trigger
	PORTJ_PIN1CTRL = 0x01; //set pin 1 so only rising edges trigger
	PORTJ_INT0MASK = 0x01; //mask interrupt 0 to only be fired by pin 0
	PORTJ_INT1MASK = 0x02; //mask interrupt 1 to only be fired by pin 1
	
	/*
	* PORT E configuration
	*/
	PORTE_DIR = 0xFF;	
	
	
	PORTH_OUT = TCE0_CCA/10;
	
	sei();
	
	while(1)
	{
		 if(serialStruct.serStatus & _USART_RX_DONE)
		 {
			 USART_read(&serialStruct, receiveString);
			 receiveInt = atoi(receiveString);
			 if(receiveInt < 350 || receiveInt > 1150)
				USART_send(&serialStruct, "These are not the values you are looking for");
			 else
				TCE0_CCA = receiveInt;
		 }
		 
		 if(setFlag)
		 {
			 setFlag = 0; //false
			 itoa(setInt, sendString, 10);
			 while(1)
				USART_send(&serialStruct, sendString);
		 }
	}
}
Exemple #13
0
void init(void)
{
	uint8_t i;
	bool	updated;
	
	//***********************************************************
	// I/O setup
	//***********************************************************
	// Set port directions
	DDRA		= 0x30;		// Port A
	DDRB		= 0x0A;		// Port B
	DDRC		= 0xFC;		// Port C
	DDRD		= 0xF2;		// Port D

	// Hold all PWM outputs low to stop glitches
	// M5 and M6 are on PortA for KK2.1
	MOTORS		= 0;
	M5			= 0;
	M6			= 0;

	// Preset I/O pins
	LED1 		= 0;		// LED1 off
	LVA 		= 0; 		// LVA alarm OFF
	LCD_SCL		= 1;		// GLCD clock high

	// Set/clear pull-ups (1 = set, 0 = clear)
	PINB		= 0xF5;		// Set PB pull-ups
	PIND		= 0x0C;		// Set PD pull-ups (Don't pull up RX yet)

	//***********************************************************
	// Spektrum receiver binding. Must be done immediately on power-up
	// 
	// 3 low pulses: DSM2 1024/22ms
	// 5 low pulses: DSM2 2048/11ms
	// 7 low pulses: DSMX 1024/22ms
	// 9 low pulses: DSMX 2048/11ms
	//***********************************************************

	PIND	= 0x0C;			// Release RX pull up on PD0
	_delay_ms(63);			// Pause while satellite wakes up
							// and pull-ups have time to rise.
							// Tweak until bind pulses about 68ms after power-up		
		
	// Bind as master if any single button pressed.
	// NB: Have to wait until the button pull-ups rise before testing for a button press.
	// Button 1
	if ((PINB & 0xf0) == 0x70)
	{
		DDRD	= 0xF3;		// Switch PD0 to output
		bind_master(3);
		
	}
	// Button 2	
	if ((PINB & 0xf0) == 0xb0)
	{
		DDRD	= 0xF3;		// Switch PD0 to output
		bind_master(5);
	}
	// Button 3	
	if ((PINB & 0xf0) == 0xd0)
	{
		DDRD	= 0xF3;		// Switch PD0 to output
		bind_master(7);
	}
	
	// Button 4
	if ((PINB & 0xf0) == 0xE0)
	{
		DDRD	= 0xF3;		// Switch PD0 to output
		bind_master(9);
	}
	
	DDRD	= 0xF2;			// Reset Port D directions
	PIND	= 0x0D;			// Set PD pull-ups (now pull up RX as well)

	//***********************************************************
	// Timers
	//***********************************************************

	// Timer0 (8bit) - run @ 20MHz / 1024 = 19.531kHz or 51.2us - max 13.1ms
	// Slow timer to extend Timer 1
	TCCR0A = 0;								// Normal operation
	TCCR0B = 0x05;							// Clk / 1024 = 19.531kHz or 51.2us - max 13.1ms
	TIMSK0 |= (1 << TOIE0);					// Enable interrupts
	TCNT0 = 0;								// Reset counter
	
	// Timer1 (16bit) - run @ 2.5MHz (400ns) - max 26.2ms
	// Used to measure Rx Signals & control ESC/servo output rate
	TCCR1A = 0;
	TCCR1B |= (1 << CS11);					// Clk/8 = 2.5MHz

	// Timer2 8bit - run @ 20MHz / 1024 = 19.531kHz or 51.2us - max 13.1ms
	// Used to time arm/disarm intervals
	TCCR2A = 0;	
	TCCR2B = 0x07;							// Clk/1024 = 19.531kHz
	TIMSK2 = 0;
	TIFR2 = 0;
	TCNT2 = 0;								// Reset counter

	//***********************************************************
	// Interrupts and pin function setup
	//***********************************************************

	// Pin change interrupt enables PCINT1, PCINT2 and PCINT3 (Throttle, AUX and CPPM input)
	PCICR  = 0x0A;							// PCINT8  to PCINT15 (PCINT1 group - AUX)
											// PCINT24 to PCINT31 (PCINT3 group - THR)
	PCIFR  = 0x0F;							// Clear PCIF0 interrupt flag 
											// Clear PCIF1 interrupt flag 
											// Clear PCIF2 interrupt flag 
											// Clear PCIF3 interrupt flag 

	// External interrupts INT0 (Elevator) and INT1 (Aileron) and INT2 (Rudder)
	EICRA = 0x15;							// Any change INT0
											// Any change INT1
											// Any change INT2
	EIFR  = 0x07; 							// Clear INT0 interrupt flag (Elevator)
											// Clear INT1 interrupt flag (Aileron)
											// Clear INT2 interrupt flag (Rudder/CPPM)

	//***********************************************************
	// Start up
	//***********************************************************

	// Preset important flags
	Interrupted = false;						

	// Load EEPROM settings
	updated = Initial_EEPROM_Config_Load(); // Config now contains valid values

	//***********************************************************
	// RX channel defaults for when no RC connected
	// Not doing this can result in the FC trying (unsuccessfully) to arm
	// and makes entry into the menus very hard
	//***********************************************************

	for (i = 0; i < MAX_RC_CHANNELS; i++)
	{
		RxChannel[i] = 3750;
	}
	
	RxChannel[THROTTLE] = 2500; // Min throttle
	
	//***********************************************************
	// GLCD initialisation
	//***********************************************************

	// Initialise the GLCD
	st7565_init();

	// Make sure the LCD is blank without clearing buffer (and so no logo)
	clear_screen();

	//***********************************************************
	// ESC calibration
	//***********************************************************
	
	// Calibrate ESCs if ONLY buttons 1 and 4 pressed
	if ((PINB & 0xf0) == 0x60)
	{
		// Display calibrating message
		st7565_command(CMD_SET_COM_NORMAL); 	// For text (not for logo)
		clear_buffer(buffer);
		LCD_Display_Text(59,(const unsigned char*)Verdana14,10,25);
		write_buffer(buffer);
		clear_buffer(buffer);
				
		// For each output
		for (i = 0; i < MAX_OUTPUTS; i++)
		{
			// Check for motor marker
			if (Config.Channel[i].Motor_marker == MOTOR)
			{
				// Set output to maximum pulse width
				ServoOut[i] = MOTOR_100;
			}
			else
			{
				ServoOut[i] = SERVO_CENTER;
			}
		}
					
		// Output HIGH pulse (1.9ms) until buttons released
		while ((PINB & 0xf0) == 0x60)
		{
			// Pass address of ServoOut array and select all outputs
			output_servo_ppm_asm(&ServoOut[0], 0xFF);

			// Loop rate = 20ms (50Hz)
			_delay_ms(20);			
		}

		// Output LOW pulse (1.1ms) after buttons released
		// For each output
		for (i = 0; i < MAX_OUTPUTS; i++)
		{
			// Check for motor marker
			if (Config.Channel[i].Motor_marker == MOTOR)
			{
				// Set output to maximum pulse width
				ServoOut[i] = MOTOR_0;
			}
		}		

		// Loop forever here
		while(1)
		{
			// Pass address of ServoOut array and select all outputs
			output_servo_ppm_asm(&ServoOut[0], 0xFF);

			// Loop rate = 20ms (50Hz)
			_delay_ms(20);			
		}
	}

	//***********************************************************
	// Reset EEPROM settings
	//***********************************************************

	// This delay prevents the GLCD flashing up a ghost image of old data
	_delay_ms(300);

	// Reload default eeprom settings if middle two buttons are pressed
	if ((PINB & 0xf0) == 0x90)
	{
		// Display reset message
		st7565_command(CMD_SET_COM_NORMAL); 	// For text (not for logo)
		clear_buffer(buffer);
		LCD_Display_Text(262,(const unsigned char*)Verdana14,40,25); // "Reset"
		write_buffer(buffer);
		clear_buffer(buffer);
		
		// Reset EEPROM settings
		Set_EEPROM_Default_Config();
		Save_Config_to_EEPROM();

		// Set contrast to the default value
		st7565_set_brightness(Config.Contrast);

		_delay_ms(500);		// Save is now too fast to show the "Reset" text long enough
	}

	// Display message in place of logo when updating eeprom structure
	if (updated)
	{
		st7565_command(CMD_SET_COM_NORMAL); 	// For text (not for logo)
		clear_buffer(buffer);
		LCD_Display_Text(259,(const unsigned char*)Verdana14,30,13); // "Updating"
		LCD_Display_Text(260,(const unsigned char*)Verdana14,33,37); // "settings"
		write_buffer(buffer);
		clear_buffer(buffer);		
		_delay_ms(1000);	
	}
	else
	{
		// Write logo from buffer
		write_buffer(buffer);
		_delay_ms(1000);
	}

	clear_buffer(buffer);
	write_buffer(buffer);
	
	st7565_init(); // Seems necessary for KK2 mini
	
	//***********************************************************
	// i2c init
	//***********************************************************	

	i2c_init();
	init_i2c_gyros();
	init_i2c_accs();

	//***********************************************************
	// Remaining init tasks
	//***********************************************************

	// Display "Hold steady" message
	clear_buffer(buffer);
	st7565_command(CMD_SET_COM_NORMAL); 	// For text (not for logo)
	LCD_Display_Text(263,(const unsigned char*)Verdana14,18,25);	// "Hold steady"
	write_buffer(buffer);	
	clear_buffer(buffer);
		
	// Do startup tasks
	Init_ADC();
	init_int();								// Initialise interrupts based on RC input mode
	init_uart();							// Initialise UART

	// Initial gyro calibration
	if (!CalibrateGyrosSlow())
	{
		clear_buffer(buffer);
		LCD_Display_Text(61,(const unsigned char*)Verdana14,25,25); // "Cal. failed"
		write_buffer(buffer);
		_delay_ms(1000);
		
		// Reset
		cli();
		wdt_enable(WDTO_15MS);				// Watchdog on, 15ms
		while(1);							// Wait for reboot
	}

	// Update voltage detection
	SystemVoltage = GetVbat();				// Check power-up battery voltage
	UpdateLimits();							// Update travel and trigger limits

	// Disarm on start-up if Armed setting is ARMABLE
	if (Config.ArmMode == ARMABLE)
	{
		General_error |= (1 << DISARMED); 	// Set disarmed bit
	}

	// Check to see that throttle is low if RC detected
	if (Interrupted)
	{
		RxGetChannels();
		if (MonopolarThrottle > THROTTLEIDLE) // THROTTLEIDLE = 50
		{
			General_error |= (1 << THROTTLE_HIGH); 	// Set throttle high error bit
		}
	}

	// Reset IMU
	reset_IMU();

	// Beep that init is complete
	LVA = 1;
	_delay_ms(25);
	LVA = 0;

#ifdef ERROR_LOG	
	// Log reboot
	add_log(REBOOT);
#endif
} // init()
Exemple #14
0
unsigned short USART_TXUsed(USART * serial) {
	unsigned short ret;
	cli();
	ret = RingBufferBytesUsed(&serial->tx_buffer);
	sei();
}
Exemple #15
0
static int
ergo_waitpofready(struct HYSDN_CARD *card)
{
	tErgDpram *dpr = card->dpram;	/* pointer to DPRAM structure */
	int timecnt = 10000 / 50;	/* timeout is 10 secs max. */
	ulong flags;
	int msg_size;
	int i;

	if (card->debug_flags & LOG_POF_CARD)
		hysdn_addlog(card, "ERGO: waiting for pof ready");
	while (timecnt--) {
		/* wait until timeout  */

		if (dpr->ToPcFlag) {
			/* data has arrived */

			if ((dpr->ToPcChannel != CHAN_SYSTEM) ||
			    (dpr->ToPcSize < MIN_RDY_MSG_SIZE) ||
			    (dpr->ToPcSize > MAX_RDY_MSG_SIZE) ||
			    ((*(ulong *) dpr->ToPcBuf) != RDY_MAGIC))
				break;	/* an error occurred */

			/* Check for additional data delivered during SysReady */
			msg_size = dpr->ToPcSize - RDY_MAGIC_SIZE;
			if (msg_size > 0)
				if (EvalSysrTokData(card, dpr->ToPcBuf + RDY_MAGIC_SIZE, msg_size))
					break;

			if (card->debug_flags & LOG_POF_RECORD)
				hysdn_addlog(card, "ERGO: pof boot success");
			save_flags(flags);
			cli();

			card->state = CARD_STATE_RUN;	/* now card is running */
			/* enable the cards interrupt */
			byteout(card->iobase + PCI9050_INTR_REG,
				bytein(card->iobase + PCI9050_INTR_REG) |
			(PCI9050_INTR_REG_ENPCI | PCI9050_INTR_REG_EN1));
			card->irq_enabled = 1;	/* we are ready to receive interrupts */

			dpr->ToPcFlag = 0;	/* reset data indicator */
			dpr->ToHyInt = 1;
			dpr->ToPcInt = 1;	/* interrupt to E1 for all cards */

			restore_flags(flags);
			if ((hynet_enable & (1 << card->myid)) 
			    && (i = hysdn_net_create(card))) 
			{
				ergo_stopcard(card);
				card->state = CARD_STATE_BOOTERR;
				return (i);
			}
#ifdef CONFIG_HYSDN_CAPI
			if((i = hycapi_capi_create(card))) {
				printk(KERN_WARNING "HYSDN: failed to create capi-interface.\n");
			}
#endif /* CONFIG_HYSDN_CAPI */
			return (0);	/* success */
		}		/* data has arrived */
		sti();
		msleep_interruptible(50);		/* Timeout 50ms */
	}			/* wait until timeout */

	if (card->debug_flags & LOG_POF_CARD)
		hysdn_addlog(card, "ERGO: pof boot ready timeout");
	return (-ERR_POF_TIMEOUT);
}				/* ergo_waitpofready */
Exemple #16
0
/**
 * Entry point 
 */
int main(void) {

  /* Misc variables */
  DCPU_registers reg; // CPU registers states (at boot)

  /* Hardware initialisation */
  cli();
  led_setup();
  spi_setup(SPI_PRESCALER, SPI_MODE, SPI_BITS_ORDER);
  uart_setup(UART_BAUDRATE);
  DEBUG_STR("Main init", "UART ready");
  button_setup();
  buzzer_setup(BUZZER_FREQUENCY, BUZZER_DURATION);
  ram_setup();
  rom_setup();
  microvga_setup();
  microvga_enable();
  dcpu_register_init(&reg);
  DEBUG_STR("Main init", "done");
  sei();
  
  /* MicroVGA initialisation */
  _delay_ms(1000);         // MicroVGA boot time
  microvga_clear_screen(); // Clear screen and goto (0, 0)
  microvga_goto_cursor(0, 0);
  uart_puts_PSTR(PSTR("SkyWodd DCPU-16 hardware emulator")); // Screen test
  buzzer_beep();
  DEBUG_STR("Main init", "MicroVGA ready");
  
  /* Hardware self-test */
  DEBUG_STR("Main init", "self-test run");
  led_run_write(1); // Led test
  _delay_ms(250);
  led_run_write(0);
  led_cpu_write(1);
  _delay_ms(250);
  led_cpu_write(0);
  led_rom_write(1);
  _delay_ms(250);
  led_rom_write(0);
  led_ram_write(1);
  _delay_ms(250);
  led_ram_write(0);
  DEBUG_STR("Main init", "self-test done");
  
  /* Keyboard & MicroVGA api test */
  DEBUG_STR("Main init", "waiting for keypress");
  microvga_goto_cursor(0, 1);
  uart_puts_PSTR(PSTR("Press any key to boot ..."));
  keyboard_wait();
  uart_puts_PSTR(PSTR("Loading please wait ..."));
  dcpu_setup(reg);
  buzzer_beep();
  microvga_clear_screen();
  microvga_goto_cursor(0, 0);
  DEBUG_STR("Main init", "ready to run");
  
  /* Infinite loop */
  for(;;) {
  
    /* Handle pause */
    while(!button_get_state()); 
	
#ifdef SERIAL_DEBUG_SUPPORT
	/* Debug */
	dcpu_registers_dump();
#endif
	
	/* Fetch opcode from ROM */
    dcpu_step(); 
  }
  
}
Exemple #17
0
void set_time(bool timeType){
	int *hou = &hour;
	int *min = &minute;
	update_timeXPos(hour, minute);
	if (timeType == ALARM_TYPE){
		hou = &alarm_hour;
		min = &alarm_minute;
		update_timeXPos(alarm_hour, alarm_minute);
	}
	int item = 0;
	int old_selectedItem = 1;
	cli();
	btn_drehenc_pushed = false;
	sei();
	clear_pixelMatrix();
	print_time(timeType);
	
	print_symbol(16,17, hakenSymb,108,46);
	print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb,timeXPos+get_timeWidth(alarm_hour)/2-4, 2);
	update_LCD();
	while(item != 2){
		while(!btn_drehenc_pushed){
			if(rotary != 0){
				item += rotary;
				cli();
				rotary = 0;
				sei();
				item = item % 3;
				if(item<0){
					item += 3;
				}
				
				switch (old_selectedItem){
					case 0: for(int x = 0; x<128; x++){
								for(int y = 2; y<10; y++)
									reset_pixel(x,y);
							} break;
					case 1: for(int x = 0; x<128; x++){
								for(int y = 2; y<10; y++)
								reset_pixel(x,y);
							}break;
					case 2: for(int x = 92; x<102; x++){
								for(int y = 2+3*15+5; y<2+3*15+8+5; y++)
									reset_pixel(x,y);
							}break;
				}
				switch (item) {
					case 0: print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb,timeXPos+hourWidth/2-4, 2); break;
					case 1: print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb,timeXPos+hourWidth+2*SPACE_TO_DOTS+ TIMEDOT_WIDTH + minuteWidth/2-4, 2); break;
					case 2: print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb, 92, 2+3*15+5);break;
				}
				old_selectedItem = item;
				update_LCD();
			}
			goodNight();
			check_light();
		}
		cli();
		btn_drehenc_pushed = false;
		sei();
		switch (item) {
			case 0: {
				print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinOffenSymb,timeXPos+hourWidth/2-4, 2); 
				update_LCD(); 
				set_timeParameter(hou, 24, timeType); 
				print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb,timeXPos+hourWidth/2-4, 2);
				break;
			}
			
			case 1: {
				print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinOffenSymb,timeXPos+hourWidth+2*SPACE_TO_DOTS+ TIMEDOT_WIDTH + minuteWidth/2-4, 2); 
				update_LCD(); 
				set_timeParameter(min, 60, timeType); 
				print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb,timeXPos+hourWidth+2*SPACE_TO_DOTS+ TIMEDOT_WIDTH + minuteWidth/2-4, 2);
				break;
			}
			case 2: {	seconds = 0;
						cli();
						TCNT2 = 0;
						timeAdvance = 0;
						timeUpdate = 0;
						sei();
						break;
			}
		}
		update_LCD();
	}
}
Exemple #18
0
/*!
 * Stop the counter.
 *
 * Disable the interrupt and remove the link
 * to the interrupt routine.
 *
 * \bug The interrupt can be required enable by
 * other part of the program.
 * It shouldn't be totally disabled here.
 */
void rtc_stop(void)
{
	cli();
	TCCR0B = 0;
}
Exemple #19
0
int
door_main(void)
{
	serial_init(9600, 8e2);

	pin13_mode_output();

	pin_mode_input(PIN_CLK);         /* clk             */
	pin_mode_input(PIN_DATA);        /* data            */
	pin_mode_output(PIN_GREEN_LED);  /* green led lock  */
	pin_mode_output(PIN_YELLOW_LED); /* yellow led lock */
	pin_mode_output(PIN_OPEN_LOCK);  /* open            */
	pin_mode_output(PIN_DAYMODE);    /* stay open       */
	pin_mode_output(PIN_STATUS_LED); /* yellow status   */

	pin_high(PIN_OPEN_LOCK);
	pin_high(PIN_DAYMODE);
	pin_high(PIN_GREEN_LED);
	pin_high(PIN_YELLOW_LED);

	/* trigger pin2 interrupt when the clock
	 * signal goes high */
	pin2_interrupt_mode_rising();
	pin2_interrupt_enable();

	data_reset();

	/* setup timer1 to trigger interrupt a 4 times a second */
	timer1_mode_ctc();
	timer1_compare_a_set(62499);
	timer1_clock_d64();
	timer1_interrupt_a_enable();

        softserial_init();
	pin_mode_output(PIN_RFID_ENABLE);
	pin_low(PIN_RFID_ENABLE);

	sleep_mode_idle();

	while (1) {
		/*
		 * sleep if no new events need to be handled
		 * while avoiding race conditions. see
		 * http://www.nongnu.org/avr-libc/user-manual/group__avr__sleep.html
		 */
		cli();
		if (events == EV_NONE && !ev_softserial) {
			sleep_enable();
			sei();
			sleep_cpu();
			sleep_disable();
			continue;
		}
		sei();

		if (events & EV_SERIAL) {
			handle_serial_input();
			continue;
		}

		if (ev_softserial) {
			handle_rfid_input();
		}

		events &= ~EV_DATA;
		if (cnt > 0 && data[cnt - 1] == 0xB4) {
			if (cnt >= 10) {
				struct sha1_context ctx;
				char digest[SHA1_DIGEST_LENGTH];

				sha1_init(&ctx);
				sha1_update(&ctx, (char *)data, 256);
				sha1_final(&ctx, digest);
				serial_print("HASH+");
				serial_hexdump(digest, SHA1_DIGEST_LENGTH);
				serial_print("\n");
			}
			data_reset();
			continue;
		}

		events &= ~EV_TIME;
		if (second > 10*4) {
			serial_print("ALIVE\n");
			second = 0;
			data_reset();
			continue;
		}
	}
}
Exemple #20
0
/*---------------------------------------------------------------------------*/
int main(void)
{
    uint8_t rv;
    uint8_t i = 0;
    uint8_t mcp3421_addr;
    uint8_t mcp9800_addr;
    uint8_t tmpReadout[4];

    /* Variables for cold junction moving average filter */
    int16_t movAvg_read;
    int8_t movAvg_ind = 0;
    int32_t movAvg_sum = 0;
    uint8_t movAvg_stabil = 0;
    int16_t movAvg_mem[8] = {0,0,0,0,0,0,0,0};    

    gainSetting = 0;
    timer0_counter = 0;

    initSerialNumber();
    usb_init();  
    I2C_Init();  
    timer_init();

    pinMode(B,1,OUTPUT);

    /*-----------------------------------------------------------------------*/
    /* Search for viable MCP3421 address options */
    /*-----------------------------------------------------------------------*/
    for(i=0x68;i<0x70;i++)
    {
        I2C_Start();
        rv = I2C_Write(write_address(i));
        I2C_Stop();

        if(rv == 0)
        {
            mcp3421_addr = i;
        }
    }

    /*-----------------------------------------------------------------------*/
    /* Search for viable MCP9800 address options */
    /*-----------------------------------------------------------------------*/
    I2C_Start();
    rv = I2C_Write(write_address(0x48));
    I2C_Stop();

    if(rv == 0)
    {
        mcp9800_addr = 0x48;
    }
    else
    {
        mcp9800_addr = 0x4D;
    }

    /*-----------------------------------------------------------------------*/
    /* Set MCP9800 to 12 bit resolution */
    /*-----------------------------------------------------------------------*/
    I2C_Start();
    I2C_Write(write_address(mcp9800_addr));    
    I2C_Write(0x01);
    I2C_Write((1<<7)|(1<<6)|(1<<5));
    I2C_Stop();

    /*-----------------------------------------------------------------------*/
    /* Set MCP9800 Register Pointer to Ambient Temperature */
    /*-----------------------------------------------------------------------*/
    I2C_Start();
    I2C_Write(write_address(mcp9800_addr));
    I2C_Write(0x00);
    I2C_Stop();
    
    while(1)
    {                
        /*-------------------------------------------------------------------*/
        /* MCP9800: Cold junction channel */
        /*-------------------------------------------------------------------*/
        usbPoll();
        I2C_Start();
        debug[0] = I2C_Write(read_address(mcp9800_addr));
        tmpReadout[0] = I2C_Read(ACK);
        tmpReadout[1] = I2C_Read(NO_ACK);        
        I2C_Stop();

        movAvg_read = ((int16_t)tmpReadout[0] << 8) + ((int16_t)tmpReadout[1]);                
        movAvg_sum -= movAvg_mem[movAvg_ind];
        movAvg_sum += movAvg_read;        
        movAvg_mem[movAvg_ind] = movAvg_read;
        
        if(movAvg_ind == 7)
        {
            movAvg_ind = 0;
            movAvg_stabil = 1;
        }
        else
        {
            movAvg_ind++;
        }

        if(movAvg_stabil == 1)
        {
            movAvg_read = movAvg_sum >> 3;    
        }        

        usbPoll();
        cli();                                
            coldJunctionReadout[0] = movAvg_read >> 8;            
            coldJunctionReadout[1] = movAvg_read & 0xFF;          
        sei();

        /*-------------------------------------------------------------------*/
        /* MCP3421: 3.75 SPS + 18 Bits + Initiate new conversion
        /*-------------------------------------------------------------------*/
        usbPoll();
        I2C_Start();
        I2C_Write(write_address(mcp3421_addr));
        I2C_Write((1<<7)|(1<<3)|(1<<2)|gainSetting);
        I2C_Stop();

        /*-------------------------------------------------------------------*/
        /* Small delay ...
        /*-------------------------------------------------------------------*/
        timer0_counter = 250;
        while(timer0_counter)
        {
            usbPoll();            
        }

        /*-------------------------------------------------------------------*/
        /* MCP3421
        /*-------------------------------------------------------------------*/
        usbPoll();
        I2C_Start();
        I2C_Write(read_address(mcp3421_addr));
        tmpReadout[0] = I2C_Read(ACK);
        tmpReadout[1] = I2C_Read(ACK);
        tmpReadout[2] = I2C_Read(ACK);
        tmpReadout[3] = I2C_Read(NO_ACK);
        I2C_Stop();

        usbPoll();
        cli();
            thermocoupleReadout[0] = tmpReadout[0];
            thermocoupleReadout[1] = tmpReadout[1];
            thermocoupleReadout[2] = tmpReadout[2];
            thermocoupleReadout[3] = tmpReadout[3];
        sei();
    }
/* Put data into the tx_buffer and schedule write_tasklet */
static ssize_t fsl_write(struct file *f, const char *buf, 
				size_t count, loff_t *pos)
{
	struct fsl_fifo_t *fsl_fifo;
	int do_sched_tasklet=0;
	unsigned flags;
	int total=0;

	fsl_fifo = (struct fsl_fifo_t *)f->private_data;
	if(!fsl_fifo->exists)
		return -ENODEV;

	save_flags_cli(flags);

	/* Is the tx buffer full, and we block */
	while(fsl_fifo->tx_cnt==FSLFIFO_BUF_SIZE)
	{
		restore_flags(flags);
		tasklet_schedule(&fsl_write_tasklet);
		interruptible_sleep_on(&fsl_write_queue);
		if(current->sigpending)
			return -EINTR;
		save_flags_cli(flags);
	}

	/* The following logic stolen from mcfserial.c */
	save_flags(flags);
	while(1)
	{
		int c;

		cli();

		/* How much can we write into the buffer? */
		c=MIN(count, MIN(FSLFIFO_BUF_SIZE - fsl_fifo->tx_cnt-1,
				 FSLFIFO_BUF_SIZE - fsl_fifo->tx_head));
		if(c<=0)
		{
			restore_flags(flags);
			break;
		}

		copy_from_user(fsl_fifo->tx_buf+fsl_fifo->tx_head, 
				buf, c);

		fsl_fifo->tx_head=(fsl_fifo->tx_head+c) & (FSLFIFO_BUF_SIZE-1);
		fsl_fifo->tx_cnt += c;

		restore_flags(flags);

		do_sched_tasklet++;

		buf+=c;
		count-=c;
		total+=c;
	}

	if(do_sched_tasklet)
		tasklet_schedule(&fsl_write_tasklet);

	return total;
}
Exemple #22
0
int main(void)
{
    { // Set up timers, sleep and such
        cli();
        set_sleep_mode(SLEEP_MODE_IDLE);
        PRR = ((1 << PRTIM1) | (1 << PRUSI) | (1 << PRADC));
        // TIMER0
        TCCR0A = (1 << WGM01);
        TCCR0B = ((1 << CS01) | (1 << CS00));
        OCR0A = 61;
        OCR0B = 0;
        TIMSK = (1 << OCIE0A);
        // INT0
        MCUCR |= (1 << ISC01);
        GIMSK = (1 << INT0);
        PORTB = PORTB_NULL;
        counter = leds = 0;
        counter_max = MAXIMUM;
        piezo = 0;
        stopped = 1;
        sei();
    }
    { // Set up the counter and start
        while (stopped < 3)
        {
            leds = counter_max;
            sleep_mode();
        }
        leds = LED_ON;
    }
    { // Prepare for the timer
        cli();
        GIMSK = 0; // Stop INT0
        stopped = 0;
        TCNT0 = 0; // Clear TIMER0
        sei();
    }
    { // Display the timer while it's running
        while (counter < counter_max)
        {
            leds = counter | LED_ON;
            sleep_mode();
        }
        stopped = 4;
        leds = counter;
    }
    { // Yell!
        cli();
        GIMSK = (1 << INT0); // Start INT0
        sei();
        while (stopped == 4) // Sleep!
            sleep_mode();
        GIMSK = 0; // Stop INT0
        TCCR0A &= ~((1 << COM0B1) | (1 << COM0B0)); // Stop yelling!
    }
    { // Timer finished, sleep forever!
        cli();
        TIMSK = 0;
        PORTB = 0; // Everything off
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_mode();
    }
    return 0;
}
Exemple #23
0
void INT0_vect ( void )
{
  cli ();
  printf ("I am in an interrupt----------->\n");
  sei ();
}
Exemple #24
0
	LockEP(u8 ep) : _sreg(SREG)
	{
		cli();
		SetEP(ep & 7);
	}
pmd_t *get_pointer_table (void)
{
	pmd_t *pmdp = NULL;
	unsigned long flags;
	struct ptable_desc *dp = ptable_list.next;
	int i;

	/*
	 * For a pointer table for a user process address space, a
	 * table is taken from a page allocated for the purpose.  Each
	 * page can hold 8 pointer tables.  The page is remapped in
	 * virtual address space to be noncacheable.
	 */
	if (PD_NONEFREE (dp)) {

		if (!(dp = kmalloc (sizeof(struct ptable_desc),GFP_KERNEL))) {
			return 0;
		}

		if (!(dp->page = __get_free_page (GFP_KERNEL))) {
			kfree (dp);
			return 0;
		}

		nocache_page (dp->page);

		dp->alloced = 0;
		/* put at head of list */
		save_flags(flags);
		cli();
		dp->next = ptable_list.next;
		dp->prev = ptable_list.next->prev;
		ptable_list.next->prev = dp;
		ptable_list.next = dp;
		restore_flags(flags);
	}

	for (i = 0; i < 8; i++)
		if (PD_TABLEFREE (dp, i)) {
			PD_MARKUSED (dp, i);
			pmdp = (pmd_t *)(dp->page + PTABLE_SIZE*i);
			break;
		}

	if (PD_NONEFREE (dp)) {
		/* move to end of list */
		save_flags(flags);
		cli();
		dp->prev->next = dp->next;
		dp->next->prev = dp->prev;

		dp->next = ptable_list.next->prev;
		dp->prev = ptable_list.prev;
		ptable_list.prev->next = dp;
		ptable_list.prev = dp;
		restore_flags(flags);
	}

	memset (pmdp, 0, PTABLE_SIZE);

	return pmdp;
}
Exemple #26
0
int
main (void)
{
#ifdef BOOTLOADER_SUPPORT
  _IVREG = _BV (IVCE);    /* prepare ivec change */
  _IVREG = _BV (IVSEL);   /* change ivec to bootloader */
#endif

  /* Default DDR Config */
#if IO_HARD_PORTS >= 4 && DDR_MASK_A != 0
  DDRA = DDR_MASK_A;
#endif
#if DDR_MASK_B != 0
  DDRB = DDR_MASK_B;
#endif
#if DDR_MASK_C != 0
  DDRC = DDR_MASK_C;
#endif
#if DDR_MASK_D != 0
  DDRD = DDR_MASK_D;
#endif
#if IO_HARD_PORTS >= 6
#if DDR_MASK_E != 0
  DDRE = DDR_MASK_E;
#endif
#if DDR_MASK_F != 0
  DDRF = DDR_MASK_F;
#endif
#endif
#if IO_HARD_PORTS >= 7
#if DDR_MASK_G != 0
  DDRG = DDR_MASK_G;
#endif
#endif


#ifdef STATUSLED_POWER_SUPPORT
  PIN_SET(STATUSLED_POWER);
#endif

  //FIXME: zum ethersex meta system hinzufügen, aber vor allem anderem initalisieren
  debug_init();
  debug_printf("ethersex " VERSION_STRING_LONG " (Debug mode)\n");

#ifdef DEBUG_RESET_REASON
  if (bit_is_set (mcusr_mirror, BORF))
    debug_printf("reset: Brown-out\n");
  else if (bit_is_set (mcusr_mirror, PORF))
    debug_printf("reset: Power on\n");
  else if (bit_is_set (mcusr_mirror, WDRF))
    debug_printf("reset: Watchdog\n");
  else if (bit_is_set (mcusr_mirror, EXTRF))
    debug_printf("reset: Extern\n");
  else
    debug_printf("reset: Unknown\n");
#endif

#ifdef BOOTLOADER_SUPPORT
  /* disable interrupts */
  cli ();
  wdt_disable();
#endif //BOOTLOADER_SUPPORT
  /* enable interrupts */
  sei ();

#ifdef USE_WATCHDOG
  debug_printf("enabling watchdog\n");
#ifdef DEBUG
  /* for debugging, test reset cause and jump to bootloader */
  if (MCU_STATUS_REGISTER & _BV (WDRF))
  {
    debug_printf("bootloader...\n");
    jump_to_bootloader();
  }
#endif
  /* set watchdog to 2 seconds */
  wdt_enable(WDTO_2S);
  wdt_kick();
#else //USE_WATCHDOG
  debug_printf("disabling watchdog\n");
  wdt_disable();
#endif //USE_WATCHDOG

#if defined(RFM12_SUPPORT) || defined(ENC28J60_SUPPORT) \
	|| defined(DATAFLASH_SUPPORT)
  spi_init();
#endif

  ethersex_meta_init();

  /* must be called AFTER all other initialization */
#ifdef PORTIO_SUPPORT
  portio_init();
#elif defined(NAMED_PIN_SUPPORT)
  np_simple_init();
#endif

#ifdef ENC28J60_SUPPORT
  debug_printf ("enc28j60 revision 0x%x\n",
  read_control_register (REG_EREVID));
  debug_printf ("mac: %02x:%02x:%02x:%02x:%02x:%02x\n",
	  uip_ethaddr.addr[0], uip_ethaddr.addr[1], uip_ethaddr.addr[2],
	  uip_ethaddr.addr[3], uip_ethaddr.addr[4], uip_ethaddr.addr[5]);
#endif

#ifdef STATUSLED_BOOTED_SUPPORT
  PIN_SET(STATUSLED_BOOTED);
#endif

  ethersex_meta_startup();
  /* main loop */
  while (1)
  {
    wdt_kick();
    ethersex_meta_mainloop();

#ifdef SD_READER_SUPPORT
    if (sd_active_partition == NULL)
    {
      if (!sd_try_init())
      {
#ifdef VFS_SD_SUPPORT
        vfs_sd_try_open_rootnode();
#endif
      }
      wdt_kick();
    }
#endif

#ifdef BOOTLOADER_JUMP
    if (status.request_bootloader)
    {
#ifdef MBR_SUPPORT
      mbr_config.bootloader = 1;
      write_mbr();
#endif
#ifdef CLOCK_CRYSTAL_SUPPORT
      TC2_INT_OVERFLOW_OFF;
#endif
#ifdef DCF77_SUPPORT
      ACSR &= ~_BV (ACIE);
#endif
      cli();
      jump_to_bootloader();
    }
#endif

#ifndef TEENSY_SUPPORT
    if (status.request_wdreset)
    {
      cli();
      wdt_enable(WDTO_15MS);
      for (;;);
    }
#endif

    if (status.request_reset)
    {
      cli();
      void (*reset) (void) = NULL;
      reset();
    }
  }
}
Exemple #27
0
static int
cpm_enet_start_xmit(struct sk_buff *skb, struct device *dev)
{
	struct cpm_enet_private *cep = (struct cpm_enet_private *)dev->priv;
	volatile cbd_t	*bdp;
	unsigned long flags;

	/* Transmitter timeout, serious problems. */
	if (dev->tbusy) {
		int tickssofar = jiffies - dev->trans_start;
		if (tickssofar < 200)
			return 1;
		printk("%s: transmit timed out.\n", dev->name);
		cep->stats.tx_errors++;
#ifndef final_version
		{
			int	i;
			cbd_t	*bdp;
			printk(" Ring data dump: cur_tx %p%s cur_rx %p.\n",
				   cep->cur_tx, cep->tx_full ? " (full)" : "",
				   cep->cur_rx);
			bdp = cep->tx_bd_base;
			for (i = 0 ; i < TX_RING_SIZE; i++, bdp++)
				printk("%04x %04x %08x\n",
					bdp->cbd_sc,
					bdp->cbd_datlen,
					bdp->cbd_bufaddr);
			bdp = cep->rx_bd_base;
			for (i = 0 ; i < RX_RING_SIZE; i++, bdp++)
				printk("%04x %04x %08x\n",
					bdp->cbd_sc,
					bdp->cbd_datlen,
					bdp->cbd_bufaddr);
		}
#endif

		dev->tbusy=0;
		dev->trans_start = jiffies;

		return 0;
	}

	/* Block a timer-based transmit from overlapping.  This could better be
	   done with atomic_swap(1, dev->tbusy), but set_bit() works as well. */
	if (test_and_set_bit(0, (void*)&dev->tbusy) != 0) {
		printk("%s: Transmitter access conflict.\n", dev->name);
		return 1;
	}

	if (test_and_set_bit(0, (void*)&cep->lock) != 0) {
		printk("%s: tx queue lock!.\n", dev->name);
		/* don't clear dev->tbusy flag. */
		return 1;
	}

	/* Fill in a Tx ring entry */
	bdp = cep->cur_tx;

#ifndef final_version
	if (bdp->cbd_sc & BD_ENET_TX_READY) {
		/* Ooops.  All transmit buffers are full.  Bail out.
		 * This should not happen, since dev->tbusy should be set.
		 */
		printk("%s: tx queue full!.\n", dev->name);
		cep->lock = 0;
		return 1;
	}
#endif

	/* Clear all of the status flags.
	 */
	bdp->cbd_sc &= ~BD_ENET_TX_STATS;

	/* If the frame is short, tell CPM to pad it.
	*/
	if (skb->len <= ETH_ZLEN)
		bdp->cbd_sc |= BD_ENET_TX_PAD;
	else
		bdp->cbd_sc &= ~BD_ENET_TX_PAD;

	/* Set buffer length and buffer pointer.
	*/
	bdp->cbd_datlen = skb->len;
	bdp->cbd_bufaddr = __pa(skb->data);

	/* Save skb pointer.
	*/
	cep->tx_skbuff[cep->skb_cur] = skb;

	cep->stats.tx_bytes += skb->len;
	cep->skb_cur = (cep->skb_cur+1) & TX_RING_MOD_MASK;
	
	/* Push the data cache so the CPM does not get stale memory
	 * data.
	 */
	flush_dcache_range(skb->data, skb->data + skb->len);

	/* Send it on its way.  Tell CPM its ready, interrupt when done,
	 * its the last BD of the frame, and to put the CRC on the end.
	 */
	bdp->cbd_sc |= (BD_ENET_TX_READY | BD_ENET_TX_INTR | BD_ENET_TX_LAST | BD_ENET_TX_TC);

	dev->trans_start = jiffies;

	/* If this was the last BD in the ring, start at the beginning again.
	*/
	if (bdp->cbd_sc & BD_ENET_TX_WRAP)
		bdp = cep->tx_bd_base;
	else
		bdp++;

	save_flags(flags);
	cli();
	cep->lock = 0;
	if (bdp->cbd_sc & BD_ENET_TX_READY)
		cep->tx_full = 1;
	else
		dev->tbusy=0;
	restore_flags(flags);

	cep->cur_tx = (cbd_t *)bdp;

	return 0;
}
Exemple #28
0
int main( )
{
	uint8_t frame;
	static uint8_t i;
	static uint16_t adcT = 0;  //ADC Temp
	static uint16_t adcP = 0;  //ADC Pin
	static uint8_t last_timercycle = 0;
	cli();

	setup_clock();

	//1st let's see how fast we can clock the pin.
	et_init( MyMAC );

	i = 0;


	//Assumed setup:
	//
	// PB2: Disconnect this (I don't know if you can use it at all)
	// PB1: TX (From this device, out) Put a 47nF capcaitor in series.

	//Enable ADC.  (For reading in pin ADC2)
	PORTB &= ~_BV(4);
	PORTB |= _BV(4);
	ADCSRA = _BV(ADEN) | _BV(ADPS1) | _BV(ADPS0) | _BV(ADSC) | _BV(ADATE);

	//Enable port B for the WS2812B.
	WSDDR |= WSPIN;
	WSPORT &= ~WSPIN;

	//The burden of configuring the tick timer is on you, the user.
	//#188 Creates a clock with period ~4ms. ~3.2ms at 31MHz, ~4.8ms at 20 MHz.
	//Making it lower seems to help.
	TCCR1 = _BV(CTC1) | _BV(CS13) | _BV(CS12); //HS Clock/2048
	OCR1C = 255; 
	OCR1A = 1;
	TIMSK = _BV(OCIE1A);

	//Enable Pin Change Interrupt.
	//(For if we have some RX data)
	PCMSK |= _BV(PCINT0);
	GIMSK |= _BV(PCIE);

	sei();

	OSCCAL = OSCHIGH;
	PORTB |= _BV(0);

	while(1)
	{
		if( last_timercycle != timercycle )
		{
			last_timercycle = timercycle;
			//i++;
			i = timercycle & 0x0f;

			if( i == 0 )
			{
				ADMUX = 2;
			}

			if( i == 1 )
			{
				adcP = ADC;
				ADMUX = _BV(REFS1) | 0x0f;
			}

			if( i == 2 )
			{
				adcT = ADC;
			}

			if( i == 14 )
			{

				frame++;
				//How to send a UDP Packet.
				cli();
				OSCCAL = OSC20;
				et_stopop();
				et_startsend( 0 );
				memset( macfrom, 0xff, 6 );
				send_etherlink_header( 0x0800 );
				send_ip_header( 0, (unsigned char*)"\xff\xff\xff\xff", 17 ); //UDP Packet to 255.255.255.255
				et_push16( 13313  ); //to port
				et_push16( 13312 ); //from port
				et_push16( 0 ); //length for later
				et_push16( 0 ); //csum for later
				et_pushpgmstr( PSTR( "TPIN" ) ); //csum for later
				et_push16( adcT ); 
				et_push16( adcP ); 
				et_push16( icmp_out ); 
				et_push16( hict ); 
				et_push16( lowct );
				util_finish_udp_packet();
				OSCCAL = OSCHIGH;
				sei();
				i = 0;

			}

		}
	}



	return 0;
} 
void BootLoader( int mode )
{
    uint8_t beats;
    uint8_t bootDelay;
    uint8_t beatRate;

#if BOOT_LOG_ENABLED
    FILE   *logFs;
#endif

    uint8_t beatCounter = 0;

#if defined( CFG_FORCE_MASK )

    // We configure the pullup as early as we can, to give the pin a chance
    // to respond.

    CFG_FORCE_DDR  &= ~CFG_FORCE_MASK;  // Configure pin for input
    CFG_FORCE_PORT |= CFG_FORCE_MASK;   // Enable Pullup
#endif

    cli();

#if ( !STANDALONE )

    // For the BootLoader, we want the interrupts to goto the BootLoader
    // interrupt vector. Do the special dance.

#if defined( GICR )
    GICR = ( 1 << IVCE );
    GICR = ( 1 << IVSEL );
#else
    MCUCR = ( 1 << IVCE );
    MCUCR = ( 1 << IVSEL );
#endif
#endif // STANDALONE

#if CFG_USE_UART && 0
    InitHardware();
#else
    InitTimer();
#endif

#if BOOT_LOG_ENABLED
    logFs = fdevopen( UART0_PutCharStdio, NULL );

    LogInit( logFs );
#endif

#if defined( CFG_I2C_LED_MASK )
    CFG_I2C_LED_DDR         |= CFG_I2C_LED_MASK;
#endif
#if defined( CFG_BOOTLOADER_BEAT_MASK )
    CFG_BOOTLOADER_BEAT_DDR |= CFG_BOOTLOADER_BEAT_MASK;
#endif

    // Read our i2c address from the EEPROM

    eeprom_read_block( &gEeprom, (void *)( E2END + 1 - sizeof( gEeprom )), sizeof( gEeprom ));

    // Check to see if the FORCE strap has been installed

    if (( gEeprom.structSize == 0xff ) || ( gEeprom.i2cAddr > 0x7f ))
    {
        // EEPROM is uninitialized. Use default data

        gEeprom.i2cAddr = BL_DEFAULT_I2C_ADDR;
    }
    if (( gEeprom.structSize == 0xff ) || ( gEeprom.bootDelay == 0xff ))
    {
        gEeprom.bootDelay = BL_DEFAULT_BOOT_DELAY;
    }

    I2C_SlaveInit( &gI2cGlobals, gEeprom.i2cAddr, ProcessCommand );

    memset( &gBootLoaderGlobals, 0, sizeof( gBootLoaderGlobals ));
    gBootLoaderGlobals.m_pageAddress = ~0uL;

    // Set gStayInBootLoader to zero before we enable interripts. We do this
    // since the interrupt handler will set it to 1 if an Info command is received.

    gStayInBootloader = 0;
    if (( pgm_read_byte_near( 0x0000 ) == 0xFF ) || ( mode == BOOT_MODE_APP ))
    {
        // No user mode program has been downloaded. We really have no choice but to stay in
        // the bootloader.

        gStayInBootloader = 1;
    }

    sei();

    BOOT_LOG0( "\n" );
    BOOT_LOG0( "*****\n" );
    BOOT_LOG2( "***** I2C BootLoader i2cAddr: 0x%02x bootDelay:%d\n", gEeprom.i2cAddr, gEeprom.bootDelay );
    BOOT_LOG0( "*****\n" );

    bootDelay = gEeprom.bootDelay;
    beats = 0;

    // gStayInBootloader is set if the BL_CMD_GET_INFO packet is received or 
    // no user program is found in flash.

    beatRate = 100; // Toggle every 100 msec

// By default, we pick Port E1 (TXD) as the override pin. For the normal bootloader
// we don't use the UART, so this is fine.

#if ( defined( CFG_FORCE_MASK ) && !CFG_USE_UART )

    // We split the test away from the configuration of the pin to give
    // things a chance to settle.   

    gStayInBootloader |= (( CFG_FORCE_PIN & CFG_FORCE_MASK ) == 0 );

#endif

    while ( gStayInBootloader || ( bootDelay > 0 ))
    {
        tick_t prevCount;

        if ( gStayInBootloader  )
        {
            beatRate = 250;
        }

        if ( ++beatCounter >= beatRate )
        {
            beatCounter = 0;

            CFG_BOOTLOADER_BEAT_PORT ^= CFG_BOOTLOADER_BEAT_MASK;

            if ( ++beats >= 10 )
            {
                // This branch taken once per second

                beats = 0;
                if ( bootDelay > 0 )
                {
                    bootDelay--;
                }
            }
        }

        prevCount = gTickCount;
        while ( gTickCount == prevCount )
        {
#if BOOT_LOG_ENABLED
            LogBufDump();
#endif
        }
    }

    RunUserProgram();

} // BootLoader
Exemple #30
0
// atomic statement runtime support
inline os_atomic_t os_atomic_begin(void)
{
    os_atomic_t result = inp(SREG);
    cli();
    return result;
}