카테고리 없음2015. 7. 23. 00:26

계속 libusb-0.1-4.so 가 없다고 불평을 늘어 놓더니...


sudo apt-get install lib32asound2 lib32gcc1 lib32ncurses5 lib32stdc++6 lib32z1 libc6-i386 ia32-libs

sudo apt-get install libstdc++6:i386 libxft2:i386 libxext6:i386 libusb-0.1-4:i386



Posted by 쿨한넘
카테고리 없음2015. 4. 16. 16:03

갑자기 mac에서 .DS_Store 화일이 보일 때, 터미널에서...


defaults write com.apple.finder AppleShowAllFiles FALSE

killall Finder


Posted by 쿨한넘
카테고리 없음2015. 3. 10. 01:16

csapp2e를 보다가 작성해서 테스트 해 본 코드.

math.h에 NAN은0x7fc00000 로 정의되어 있다. 그러나 이 floating point 밸류를 NAN과 비교해 판별하면 무조건 다르게 나온다는 점. NaN을 판별하려면 isnan() 함수를 사용하거나, exponent bits를 봐야 할 듯.




//
//  main.c
//  floatingpoint_bits
//
//  Created by Seong-Su Kim on 2015. 3. 9..
//  Copyright (c) 2015년 Seong-Su Kim. All rights reserved.
//

#include <stdio.h>
#include <math.h>


void printfpValue(float fvalue);
void printbitsValue(unsigned bits);
void isNaN(unsigned bits);


int main(void)
{
	unsigned long count;
	unsigned long start, end;

	
	printf("\n# predefined values\n\n");
	printfpValue(NAN);
	printfpValue(INFINITY);

	if (NAN == NAN)
		printf("NAN == NAN!\n");	// will be never executed
	
	printf("\n\n# user bits to floating point value\n\n");
	printbitsValue(0xff800000); isNaN(0xff800000);
	printbitsValue(0x7f800001); isNaN(0x7f800001);
	printbitsValue(0x7fc00000); isNaN(0x7fc00000);
	printbitsValue(0xff800001); isNaN(0xff800001);
	

	printf("enter start value : ");
	scanf("%lx", &start);
	printf("start value = %#lx\n", start);
	
	printf("enter end value : ");
	scanf("%lx", &end);
	printf("end value = %#lx\n", start);
	
	for (count = start; count <= end; count++)
		printbitsValue((unsigned)count);
	
	return 0;
}


void printfpValue(float fvalue)
{
	unsigned *bp;

	bp = (unsigned *)(&fvalue);

	printf("%0#10x = %12e\n", *bp, fvalue);
}


void printbitsValue(unsigned bits)
{
	float *fp;
	
	fp = (float *)(&bits);
	
	printf("%0#10x = %12e\n", bits, *fp);

}


void isNaN(unsigned bits)
{
	float *fp;
	
	fp = (float *)(&bits);
	
	if (*fp == NAN)
		printf("%e == NAN,\t", *fp);
	else
		printf("%e != NAN,\t", *fp);

	
	if (isnan(*fp))
		printf("isnan() says it is NaN.\n\n");
	else
		printf("isnan() says it is not NaN.\n\n");

}



Posted by 쿨한넘

ARM assembly를 좋아하지 않을 수 있을리가...



	// Get Greatest Common Divider (GCD)
	// using Euclid's algorithm
	//
	// while (a != b) {
	//	if (a > b)
	//		a = a - b;
	//	else
	//		b = b - a;
	// }

	.global	example8_5
	.global	gcd

example8_5:
gcd:
	cmp  	r0, r1
	subgt	r0, r1			// if r0 > r1, r0 -= r1
	sublt	r1, r0			// if r0 < r1, r1 -= r0
	bne	gcd

	bx  	lr			// if r0 == r1, return

	.end



Posted by 쿨한넘
카테고리 없음2014. 9. 1. 11:59


마땅히 새로운게 없어 살펴보고 있는 xmega.

쓰면서 느끼지만, 호화스러운 페리페럴들. 럭져리한 경차 같은 느낌이다. atmega와 유사하지만, 레지스터들이 상당히 많아서 효율좋은 코드가 가능할 것 같다.

프로세서는 역시 클럭 셋팅부터. application note avr1003을 참조...라기보다는 걍 거의 그대로 가져다 써서 테스트. 아래 코드로 네가지의 클럭셋팅을 순서대로 돌아가며 사용하였다. 조금 신경을 써야 할 부분은, 페리페럴 클럭들이다. CLKper2와 CLKper4는 고클럭세팅전에 반드시 낮춰놓고 나중에 다시 맞게 세팅해야한다.




/*
 * avr1003_dons.c
 *
 * Created: 2014-08-28 오후 11:23:31
 *  Author: Don Quixote
 */
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

/* The LED to use for visual feedback. */
#define LEDPORT		PORTE
#define LEDMASK		0xFF

/* Which switches to listen to */
#define SWITCHPORT	PORTD
#define SWITCHMASK	0xFF

/*! \brief Define the delay_us macro for GCC. */
#define delay_us(us)	(_delay_us(us))

/* Definitions of macros. */

/*! \brief This macro enables the selected oscillator.
 *
 *  \note Note that the oscillator cannot be used as a main system clock
 *        source without being enabled and stable first. Check the ready flag
 *        before using the clock. The function CLKSYS_IsReady( _oscSel )
 *        can be used to check this.
 *
 *  \param  _oscSel Bitmask of selected clock. Can be one of the following
 *                  OSC_RC2MEN_bm, OSC_RC32MEN_bm, OSC_RC32KEN_bm, OSC_XOSCEN_bm,
 *                  OSC_PLLEN_bm.
 */
#define	CLKSYS_Enable(_oscSel)		(OSC.CTRL |= (_oscSel))

/*! \brief This macro check if selected oscillator is ready.
 *
 *  This macro will return non-zero if is is running, regardless if it is
 *  used as a main clock source or not.
 *
 *  \param _oscSel Bitmask of selected clock. Can be one of the following
 *                 OSC_RC2MEN_bm, OSC_RC32MEN_bm, OSC_RC32KEN_bm, OSC_XOSCEN_bm,
 *                 OSC_PLLEN_bm.
 *
 *  \return  Non-zero if oscillator is ready and running.
 */
#define	CLKSYS_IsReady(_oscSel)		(OSC.STATUS & (_oscSel))

/*! \brief This macro will protect the following code from interrupts. */
#define	AVR_ENTER_CRITICAL_REGION()	uint8_t volatile saved_sreg = SREG; \
									cli();
/*! \brief This macro must always be used in conjunction with AVR_ENTER_CRITICAL_REGION
 *        so the interrupts are enabled again.
 */
#define	AVR_LEAVE_CRITICAL_REGION()	SREG = saved_sreg;


void clk32m_setup(void);
void timer_setup(void);
void Port_setup(void);
void WaitForSwitches(void);

void CLKSYS_Prescalers_Config(CLK_PSADIV_t PSAfactor,
				CLK_PSBCDIV_t PSBCfactor);
uint8_t CLKSYS_Main_ClockSource_Select(CLK_SCLKSEL_t clockSource);
uint8_t CLKSYS_Disable(uint8_t oscSel);
void CLKSYS_PLL_Config(OSC_PLLSRC_t clockSource, uint8_t factor);
void CCPWrite(volatile uint8_t* address, uint8_t value);

void clk_32m(void);
void clk_pll30m(void);
void clk_2m(void);
void clk_32k(void);
void clk_pll32m(void);


int main(void)
{
	Port_setup();
	timer_setup();

	/* Enable low interrupt level in PMIC and enable global interrupts. */
	PMIC.CTRL |= PMIC_MEDLVLEN_bm;
	sei();

	while (1) {
		WaitForSwitches();
		LEDPORT.OUT = ~0x01 & 0x0f;
		clk_pll30m();


		WaitForSwitches();
		LEDPORT.OUT = ~0x02 & 0x0f;
		clk_32m();


		WaitForSwitches( );
		LEDPORT.OUT = ~0x04 & 0x0f;
		clk_pll32m();


		WaitForSwitches();
		LEDPORT.OUT = ~0x08 & 0x0f;
		clk_2m();
	}
}


/*! Just toggle LED(s) when interrupt occurs. */
ISR(TCC0_OVF_vect)
{
	LEDPORT.OUTTGL = 0xf0;
}


void timer_setup(void)
{
	/* Set up Timer/Counter 0 to work from CPUCLK/64, with period 10000 and
	 * enable overflow interrupt.
	 */
	TCC0.PER = 20000;
	TCC0.CTRLA = ( TCC0.CTRLA & ~TC0_CLKSEL_gm ) | TC_CLKSEL_DIV64_gc;
	TCC0.INTCTRLA = ( TCC0.INTCTRLA & ~TC0_OVFINTLVL_gm )
			| TC_OVFINTLVL_MED_gc;

}


void clk32m_setup(void)
{
	// enable 32Mhz internal osc.
	OSC.CTRL |= OSC_RC32MEN_bm;

	// check whether the 32Mhz internal clock
	while ((OSC.STATUS & OSC_RC32MRDY_bm) == 0);


}


/*
 *	setup LED port and switch port
 */
void Port_setup(void)
{

	/* Set up user interface. */
	LEDPORT.DIRSET = LEDMASK;
	LEDPORT.OUTSET = 0xf7;

	/* PORTC pin7 set to output */
	PORTC.DIRSET = 0x80;
	
	/* clkout on portc */
	PORTCFG.CLKEVOUT |= 0x01;
	
	SWITCHPORT.DIRCLR = SWITCHMASK;		// set input
	SWITCHPORT.PIN0CTRL = (SWITCHPORT.PIN0CTRL & ~PORT_OPC_gm)
				| PORT_OPC_PULLUP_gc;

}


void waitBtnPressed(void)
{
	while (1) {
		if ((SWITCHPORT.IN & 0x01) == 0x00) {
			_delay_ms(10);
			if ((SWITCHPORT.IN & 0x01) == 0x00)
				return;
		}
	}
}


void waitBtnRelesed(void)
{
	while (1) {

		if ((SWITCHPORT.IN & 0x01) == 0x01) {
			_delay_ms(10);
			if ((SWITCHPORT.IN & 0x01) == 0x01)
				return;
		}	
	}
}


/*! \brief This function waits for a button push and release before proceeding.
 */
void WaitForSwitches(void)
{
	waitBtnPressed();
	waitBtnRelesed();
	/*
	while ((SWITCHPORT.IN & 0x01) == 0x01);
	_delay_ms(10);
	while ((SWITCHPORT.IN & 0x01) == 0x00);
	_delay_ms(10);
	*/
}


/*! \brief This function changes the prescaler configuration.
 *
 *  Change the configuration of the three system clock
 *  prescaler is one single operation. The user must make sure that
 *  the main CPU clock does not exceed recommended limits.
 *
 *  \param  PSAfactor   Prescaler A division factor, OFF or 2 to 512 in
 *                      powers of two.
 *  \param  PSBCfactor  Prescaler B and C division factor, in the combination
 *                      of (1,1), (1,2), (4,1) or (2,2).
 */
void CLKSYS_Prescalers_Config(CLK_PSADIV_t PSAfactor,
                               CLK_PSBCDIV_t PSBCfactor)
{
	uint8_t PSconfig = (uint8_t) PSAfactor | PSBCfactor;
	CCPWrite(&CLK.PSCTRL, PSconfig);
}


/*! \brief This function selects the main system clock source.
 *
 *  Hardware will disregard any attempts to select a clock source that is not
 *  enabled or not stable. If the change fails, make sure the source is ready
 *  and running and try again.
 *
 *  \param  clockSource  Clock source to use as input for the system clock
 *                       prescaler block.
 *
 *  \return  Non-zero if change was successful.
 */
uint8_t CLKSYS_Main_ClockSource_Select(CLK_SCLKSEL_t clockSource)
{
	uint8_t clkCtrl = (CLK.CTRL & ~CLK_SCLKSEL_gm) | clockSource;

	CCPWrite(&CLK.CTRL, clkCtrl);
	clkCtrl = (CLK.CTRL & clockSource);

	return clkCtrl;
}


/*! \brief This function disables the selected oscillator.
 *
 *  This function will disable the selected oscillator if possible.
 *  If it is currently used as a main system clock source, hardware will
 *  disregard the disable attempt, and this function will return zero.
 *  If it fails, change to another main system clock source and try again.
 *
 *  \param oscSel  Bitmask of selected clock. Can be one of the following
 *                 OSC_RC2MEN_bm, OSC_RC32MEN_bm, OSC_RC32KEN_bm,
 *                 OSC_XOSCEN_bm, OSC_PLLEN_bm.
 *
 *  \return  Non-zero if oscillator was disabled successfully.
 */
uint8_t CLKSYS_Disable(uint8_t oscSel)
{
	OSC.CTRL &= ~oscSel;
	uint8_t clkEnabled = OSC.CTRL & oscSel;

	return clkEnabled;
}


/*! \brief This function configures the internal high-frequency PLL.
 *
 *  Configuration of the internal high-frequency PLL to the correct
 *  values. It is used to define the input of the PLL and the factor of
 *  multiplication of the input clock source.
 *
 *  \note Note that the oscillator cannot be used as a main system clock
 *        source without being enabled and stable first. Check the ready flag
 *        before using the clock. The macro CLKSYS_IsReady( _oscSel )
 *        can be used to check this.
 *
 *  \param  clockSource Reference clock source for the PLL,
 *                      must be above 0.4MHz.
 *  \param  factor      PLL multiplication factor, must be
 *                      from 1 to 31, inclusive.
 */
void CLKSYS_PLL_Config(OSC_PLLSRC_t clockSource, uint8_t factor)
{
	factor &= OSC_PLLFAC_gm;
	OSC.PLLCTRL = (uint8_t)clockSource | (factor << OSC_PLLFAC_gp);
}


/*! \brief CCP write helper function written in assembly.
 *
 *  This function is written in assembly because of the timecritial
 *  operation of writing to the registers.
 *
 *  \param address A pointer to the address to write to.
 *  \param value   The value to put in to the register.
 */
void CCPWrite(volatile uint8_t* address, uint8_t value)
{
	AVR_ENTER_CRITICAL_REGION( );
	volatile uint8_t* tmpAddr = address;
#ifdef RAMPZ
	RAMPZ = 0;
#endif
	asm volatile(
		"movw	r30, %0"	"\n\t"
		"ldi	r16, %2"	"\n\t"
		"out	%3, r16"	"\n\t"
		"st	Z, %1"		"\n\t"
		:
		: "r" (tmpAddr), "r" (value), "M" (CCP_IOREG_gc), "i" (&CCP)
		: "r16", "r30", "r31"
	);

	AVR_LEAVE_CRITICAL_REGION( );
}


void clk_32m(void)
{
	/*  Enable internal 32 MHz ring oscillator and wait until it's
	 *  stable. Divide clock by two with the prescaler C and set the
	 *  32 MHz ring oscillator as the main clock source. Wait for
	 *  user input while the LEDs toggle.
	 */
	CLKSYS_Enable(OSC_RC32MEN_bm);
	while (CLKSYS_IsReady(OSC_RC32MRDY_bm) == 0);
	CLKSYS_Main_ClockSource_Select(CLK_SCLKSEL_RC32M_gc);
	CLKSYS_Prescalers_Config(CLK_PSADIV_1_gc, CLK_PSBCDIV_1_1_gc);
	CLKSYS_Disable(OSC_PLLEN_bm | OSC_XOSCEN_bm | OSC_RC32KEN_bm | OSC_RC2MEN_bm);
}


void clk_pll30m(void)
{
	/*  Configure PLL with the 2 MHz RC oscillator as source and
	 *  multiply by 30 to get 60 MHz PLL clock and enable it. Wait
	 *  for it to be stable and set prescaler C to divide by two
	 *  to set the CPU clock to 30 MHz. Disable unused clock and
	 *  wait for user input.
	 */
	CLKSYS_PLL_Config(OSC_PLLSRC_RC2M_gc, 30);
	CLKSYS_Enable(OSC_PLLEN_bm);
	while (CLKSYS_IsReady(OSC_PLLRDY_bm) == 0);
	CLKSYS_Prescalers_Config(CLK_PSADIV_2_gc, CLK_PSBCDIV_2_2_gc);
	CLKSYS_Main_ClockSource_Select(CLK_SCLKSEL_PLL_gc);
	CLKSYS_Prescalers_Config(CLK_PSADIV_1_gc, CLK_PSBCDIV_1_2_gc);
	CLKSYS_Disable(OSC_XOSCEN_bm | OSC_RC32KEN_bm | OSC_RC32MEN_bm);
}


void clk_pll32m(void)
{
	CLKSYS_Enable(OSC_RC32MEN_bm);
	while (CLKSYS_IsReady(OSC_RC32MRDY_bm) == 0);
	CLKSYS_Prescalers_Config(CLK_PSADIV_2_gc, CLK_PSBCDIV_2_2_gc);

	CLKSYS_PLL_Config(OSC_PLLSRC_RC32M_gc, 16);
	CLKSYS_Enable(OSC_PLLEN_bm);
	while (CLKSYS_IsReady(OSC_PLLRDY_bm) == 0);
	CLKSYS_Main_ClockSource_Select(CLK_SCLKSEL_PLL_gc);
	CLKSYS_Prescalers_Config(CLK_PSADIV_1_gc, CLK_PSBCDIV_2_2_gc);	
	CLKSYS_Disable(OSC_XOSCEN_bm | OSC_RC32KEN_bm | OSC_RC2MEN_bm);

}


void clk_2m(void)
{
	/*  Select 2 MHz RC oscillator as main clock source and diable
	 *  unused clock.
	 */
	CLKSYS_Enable(OSC_RC2MEN_bm);
	while (CLKSYS_IsReady(OSC_RC2MRDY_bm) == 0);

	CLKSYS_Main_ClockSource_Select(CLK_SCLKSEL_RC2M_gc);
	CLKSYS_Prescalers_Config(CLK_PSADIV_1_gc, CLK_PSBCDIV_1_1_gc);	
	CLKSYS_Disable(OSC_PLLEN_bm | OSC_XOSCEN_bm | OSC_RC32KEN_bm | OSC_RC32MEN_bm);
}


void clk_32k(void)
{
	/*  Enable internal 32 kHz calibrated oscillator and check for
	 *  it to be stable and set prescaler A, B and C to none. Set
	 *  the 32 kHz oscillator as the main clock source. Wait for
	 *  user input while the LEDs toggle.
	 */
	CLKSYS_Enable(OSC_RC32KEN_bm);
	while (CLKSYS_IsReady(OSC_RC32KRDY_bm) == 0);
	CLKSYS_Main_ClockSource_Select(CLK_SCLKSEL_RC32K_gc);
	CLKSYS_Disable(OSC_XOSCEN_bm | OSC_PLLEN_bm);
	CLKSYS_Prescalers_Config(CLK_PSADIV_1_gc, CLK_PSBCDIV_1_1_gc);
}



Posted by 쿨한넘
book/Make: AVR Programming2014. 7. 29. 01:48

책에서 구현한 방법의 원리를 짚고 넘어가자.

은박지로 capacitive sensor를 만들었다. 책에서는 그라운드에 연결되는 면은 크게, mcu의 입력이 되는 면은 작게 만들라해서 일단 그렇게. 중간엔 종이를 넣었다. 이면지 활용인데, 2009년도 영수증이네.



아래 도면과 같이 atmega328p에 연결. 100K ohm 대신 20K 사용.



코드는,



/*
   Capacitive touch sensor demo
*/

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <avr/power.h>
#include "pinDefines.h"
#include "USART.h"


#define SENSE_TIME   25
#define THRESHOLD    8000


// -------  Global Variables ---------- //

volatile uint16_t chargeCycleCount;


// ------- Functions -------- //

void initPinChangeInterrupt(void)
{
	PCICR |= (1 << PCIE1);	/* enable Pin-change interrupts 1 (bank C) */
	PCMSK1 |= (1 << PC1);	/* enable specific interrupt for our pin PC1 */
}


ISR (PCINT1_vect)
{
	chargeCycleCount++;	/* count this change */

	CAP_SENSOR_DDR |= (1 << CAP_SENSOR);	/* output mode */
	_delay_us(1);				/* charging delay */

	CAP_SENSOR_DDR &= ~(1 << CAP_SENSOR);	/* set as input */
	PCIFR |= (1 << PCIF1);			/* clear the pin-change interrupt */
}


int main(void)
{
	// -------- Inits --------- //
	clock_prescale_set(clock_div_1);	/* full speed */
	initUSART();
	printString("==[ Cap Sensor ]==\r\n\r\n");


	LED_DDR = 0xff;
	MCUCR |= (1 << PUD);			/* disable all pull-ups */
	CAP_SENSOR_PORT |= (1 << CAP_SENSOR);	/* we can leave output high */

	initPinChangeInterrupt();


	// ------ Event loop ------ //
	while (1) {

		chargeCycleCount = 0;		/* reset counter */
		CAP_SENSOR_DDR |= (1 << CAP_SENSOR);	/* start with cap charged */

		sei();				/* start up interrupts, counting */
		_delay_ms(SENSE_TIME);
		cli();				/* done */

		if (chargeCycleCount < THRESHOLD) {
			LED_PORT = 0xff;
		} else {
			LED_PORT = 0;
		}

		printWord(chargeCycleCount);	/* for fine tuning */
		printString("\r\n");

	}	/* End event loop */

	return (0);				/* This line is never reached */
}


한마디로 요약하자면, SENSE_TIME 동안 센서의 캐패시터에 충전하고 방전시켜 그 사이클 수를 측정하여 터치를 인식. 터치가 되면 캐패시턴스가 증가하여, 방전시간이 길어져, 사이클 수가 줄어든다.

책에선 SENSE_TIME 은 50을, THRESHOLD 는 12000 을 지정했고, 운 좋게도 이 값으로 동작을 했다. 센서의 캐패시턴스 값, 연결하는 저항의 값에 따라서 THRESHOLD 값은 조정해야 한다. 빠른 인식을 원해서 나는 SENSE_TIME을 25ms 로 줄였고, 이에 맞춰 THRESHOLD 값도 변경하였다.




PC1 핀을 스코프로 들여다 봤다. 위 사진은 터치가 되지 않았을 경우, 아래 사진은 터치를 했을 경우다. 이 센서의 경우 무엇으로도 터치가 되었고, 터치되는 면적이 넓을수록 캐패시턴스가 증가하는 것 같다.

Posted by 쿨한넘




--
--	VHDL을 이용한 FPGA 설계
--
--	3장. Section08. '1' 개수 카운터
--
library ieee;
use ieee.std_logic_1164.all;


entity OneCounter is

	port (
		d		:	in		std_logic_vector (7 downto 0);
		seg		:	out		std_logic_vector (6 downto 0)
	);
	
end OneCounter;


architecture arc of OneCounter is

    -- convert integer value to drive 7-segment
    --
    function toSeg(
        in_value    :   in  integer range 0 to 15
    ) return std_logic_vector is
    begin
     
        case in_value is
         
            when 0      =>   return "1000000";
            when 1      =>   return "1111001";
            when 2      =>   return "0100100";
            when 3      =>   return "0110000";
            when 4      =>   return "0011001";
            when 5      =>   return "0010010";
            when 6      =>   return "0000010";
            when 7      =>   return "1011000";
            when 8      =>   return "0000000";
            when 9      =>   return "0011000";
            when 10     =>   return "0001000";
            when 11     =>   return "0000011";
            when 12     =>   return "0100111";
            when 13     =>   return "0100001";
            when 14     =>   return "0000110";
            when 15     =>   return "0001110";
            when others =>   return "1111111";
 
        end case;
             
    end toSeg;

begin


	process (d)

		variable oneCount	:	integer;
		
	begin
	
	
		oneCount	:=	0;
		
		for i in d'range loop
		
			if d(i) = '1' then
				oneCount	:=	oneCount + 1;
			end if;
			
		end loop;
		
		seg		<=	toSeg(oneCount);


	end process;


end arc;



Posted by 쿨한넘

de2-115 의 I/O 에 맞게 구현.




--
--	VHDL을 이용한 FPGA 설계
--	3장. section07. n비트 가산 / 감산기
--		DE2-117 구현
--
library ieee;
use ieee.std_logic_1164.all;

package my_package is

	constant	adder_width		:	integer := 4;
	constant	result_width	:	integer := 5;
	constant	max_result		:	integer := 2**result_width - 1;
	constant	min_result		:	integer := -2**result_width;
	
	subtype		adder_value		is	integer range 0 to 2**adder_width - 1;
	subtype		result_value	is	integer range min_result to max_result;
	
end my_package;


library ieee;
use ieee.std_logic_1164.all;
use work.my_package.all;

entity nbitAddSub is

	port (
		a, b		:	in		adder_value;
		mode		:	in		std_logic;
		sega		:	out		std_logic_vector (6 downto 0);	-- hex6 of de2-117
		segb		:	out		std_logic_vector (6 downto 0);	-- hex4 of de2-117
		segmode		:	out		std_logic_vector (6 downto 0);	-- hex3 of de2-117
		segsign		:	out		std_logic;						-- hex2 of de2-117
		seg1		:	out		std_logic_vector (6 downto 0);	-- hex0 of de2-117
		seg2		:	out		std_logic_vector (6 downto 0);	-- hex1 of de2-117
		underflow	:	out		std_logic;
		overflow	:	out		std_logic
	);
	
end nbitAddSub;


architecture arc of nbitAddSub is

	signal	over, under	:	std_logic;
	signal	seg1Reg, seg2Reg	:	integer range 0 to 15;


	-- convert integer value to drive 7-segment
	--
	function toSeg(
		in_value	:	in	integer range 0 to 15
	) return std_logic_vector is
	begin
	
		case in_value is
		
			when 0	 	=>	return "1000000";
			when 1		=>	return "1111001";
			when 2		=>	return "0100100";
			when 3		=>	return "0110000";
			when 4		=>	return "0011001";
			when 5		=>	return "0010010";
			when 6		=>	return "0000010";
			when 7		=>	return "1011000";
			when 8		=>	return "0000000";
			when 9		=>	return "0011000";
			when 10		=>	return "0001000";
			when 11		=>	return "0000011";
			when 12		=>	return "0100111";
			when 13		=>	return "0100001";
			when 14		=>	return "0000110";
			when 15		=>	return "0001110";
			when others	=>	return "1111111";

		end case;
			
	end toSeg;

begin


	process (mode, a, b, over, under)
		variable res	:	result_value;
	begin

		if (mode = '1') then		-- if key0 is not pressed
			res		:=	a + b;
			segmode	<=	toSeg(10);	-- display 'A' for mode add
		else
			res		:=	a - b;
			segmode	<=	toSeg(5);	--	display 'S' for mode subtraction
		end if;

	
		if (res > max_result) then
			over	<=	'1';
		else
			over	<=	'0';
		end if;


		if (res < min_result) then
			under	<=	'1';
		else
			under	<=	'0';
		end if;


		if (res < 0) then
			segsign	<=	'0';		-- turn on minus sign
			seg2Reg	<=	-res / 16;
			seg1Reg	<=	-res mod 16;
		else
			segsign	<=	'1';		-- turn off minus sign
			seg2Reg	<=	res / 16;
			seg1Reg	<=	res mod 16;
		end if;

		overflow	<=	over;
		underflow	<=	under;

	end process;


	sega	<=	toSeg(a);
	segb	<=	toSeg(b);
	seg1	<=	toSeg(seg1Reg);
	seg2	<=	toSeg(seg2Reg);

	
end arc;



'book > VHDL을 이용한 FPGA 디지털 설계' 카테고리의 다른 글

'1' 개수 카운터  (0) 2014.06.25
lab06. 수의 정렬회로 설계  (0) 2014.06.25
7-segment decoder  (0) 2014.06.05
xor을 이용한 전감산기 설계  (0) 2014.06.04
xor을 이용한 전가산기 설계  (0) 2014.06.04
Posted by 쿨한넘

...




--
-- VDHL을 이용한 FPGA 설계
--
-- 3장 Lab06. 수의 정렬 회로 설계
--
--	de2-115 로 구현.
--		input a 	=>	SW17~SW14
--		input b 	=>	SW3~SW0
--		value a		=>	HEX6
--		value b 	=>	HEX4
--		value max 	=>	HEX3
--		value min 	=>	HEX0
--		input ena	=>	KEY0
--
package my_package is

	constant input_width	:	integer := 4;
	constant output_width	:	integer := 4;
	
	subtype input_value		is integer range 0 to 2**input_width - 1;
	subtype output_value	is integer range 0 to 2**output_width - 1;
	
end my_package;


library ieee;
use ieee.std_logic_1164.all;
use work.my_package.all;


entity lab06 is

	port (
		a		:	in		input_value;
		b		:	in		input_value;
		ena		:	in		std_logic;

		led_a	:	out		std_logic_vector (6 downto 0);
		led_b	:	out		std_logic_vector (6 downto 0);
		
		led_max	:	out		std_logic_vector (6 downto 0);
		led_min	:	out		std_logic_vector (6 downto 0)

	);
	
end lab06;


architecture arc of lab06 is

	signal	max		:	output_value;
	signal	min		:	output_value;

	-- convert integer value to drive 7-segment
	--
	function to_hex(
		in_value	:	in	input_value
	) return std_logic_vector is
	begin
	
		case in_value is
		
			when 0	 	=>	return "1000000";
			when 1		=>	return "1111001";
			when 2		=>	return "0100100";
			when 3		=>	return "0110000";
			when 4		=>	return "0011001";
			when 5		=>	return "0010010";
			when 6		=>	return "0000010";
			when 7		=>	return "1011000";
			when 8		=>	return "0000000";
			when 9		=>	return "0011000";
			when 10		=>	return "0001000";
			when 11		=>	return "0000011";
			when 12		=>	return "0100111";
			when 13		=>	return "0100001";
			when 14		=>	return "0000110";
			when 15		=>	return "0001110";
			when others	=>	return "1111111";

		end case;
			
	end to_hex;
		
begin


	led_a	<=	to_hex(a);
	led_b	<=	to_hex(b);
	led_max	<=	to_hex(max);
	led_min	<=	to_hex(min);


	process (a, b, ena)
	begin
	
		if (ena = '0') then
		
			if (a > b) then
			
				max	<=	a;
				min	<=	b;
			
			else
			
				max	<=	b;
				min	<=	a;

			end if;
			
		end if;

	end process;
		
	
end arc;


'book > VHDL을 이용한 FPGA 디지털 설계' 카테고리의 다른 글

'1' 개수 카운터  (0) 2014.06.25
n비트 가산/감산기 vhdl 설계  (0) 2014.06.25
7-segment decoder  (0) 2014.06.05
xor을 이용한 전감산기 설계  (0) 2014.06.04
xor을 이용한 전가산기 설계  (0) 2014.06.04
Posted by 쿨한넘

4bit 스위치 입력을 받아 7 세그먼트에 표시한다.

DE2-115에 맞게 바꿔었다.

numeric_std 을 사용하기 위해서는 std_logic_arith 을 인클루드 하지 말아야.

http://www.lothar-miller.de/s9y/uploads/Bilder/Usage_of_numeric_std.pdf 참조.


--
-- VHDL을 이용한 FPGA 디지털 설계
-- section_03 Lab4 7-segment decoder
--

library ieee;
use ieee.std_logic_1164.all;
--use ieee.std_logic_arith.all;
use ieee.numeric_std.all;


entity Lab4_7seg is

	port (
		CLOCK_50		:	in		std_logic;
		SW				:	in		std_logic_vector (17 downto 0);
		HEX0			:	out		std_logic_vector (6 downto 0)
	);
	
end Lab4_7seg;


architecture arc of Lab4_7seg is

	signal	keyVal		:	integer range 0 to 15;

begin


	keyVal <= to_integer(unsigned(SW (3 downto 0)) );


	process (CLOCK_50)
	begin
	
		if rising_edge(CLOCK_50) then
		
			case keyVal is
										--	"gfedcba"
				when 0		=>	HEX0	<=	"1000000";
				when 1		=>	HEX0	<=	"1111001";
				when 2		=>	HEX0	<=	"0100100";
				when 3		=>	HEX0	<=	"0110000";
				when 4		=>	HEX0	<=	"0011001";
				when 5		=>	HEX0	<=	"0010010";
				when 6		=>	HEX0	<=	"0000010";
				when 7		=>	HEX0	<=	"1011000";
				when 8		=>	HEX0	<=	"0000000";
				when 9		=>	HEX0	<=	"0011000";
				when 10		=>	HEX0	<=	"0001000";
				when 11		=>	HEX0	<=	"0000011";
				when 12		=>	HEX0	<=	"0100111";
				when 13		=>	HEX0	<=	"0100001";
				when 14		=>	HEX0	<=	"0000110";
				when 15		=>	HEX0	<=	"0001110";
				when others	=>	null;

			end case;
	
		end if;
		
	end process;

end arc;



Posted by 쿨한넘