int main(void)
{
 char Received_From_device[500] = "";        // Maximum data from device of 500 bytes
 //char character[10] = "";
    char ETX_character;
 int i,a,lazy_timeout_counter,lazy_timeout_max,tmp,adc_value;
 char c;
  
  RCC_Configuration();
  
  GPIO_Configuration();
 
  SPI2_Configuration();   //SPI configure
  
  USART1_Configuration();
 
   GPIO_SetBits(GPIOB, GPIO_Pin_12);   //set Chip Select HIGH for SPI
  
 while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); // Wait for Empty
  
    USART_SendData(USART1, 0x49); // Send 'I'
 while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
 USART_SendData(USART1, 0x42); // Send 'B'
SPI_Loop:
 Delay(1000);    //1second delay
 
 //goto Jump2Here;
 
 //Select CH0 of LTC2492
 
 GPIO_ResetBits(GPIOB, GPIO_Pin_12); // Assert -CS
 Delay_us(10); // overkill
 
// You need semicolons after the whiles otherwise they repeat the next statement
 
 while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == 0); //wait for transmit buffer to be empty, should be
 
 SPI_I2S_ReceiveData(SPI2); // Clear RXNE
 SPI_I2S_SendData(SPI2, LTC_Internal_Temperature_select); //LTC_Internal_Temperature_select
 while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == 0); //wait for transmit buffer to not be empty (ie data loaded in)
 SPI_I2S_SendData(SPI2, 0); // Fill for 32-bits, remaining 16-bits in holding buffer
 
 while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == 0); // wait for last bit to be sent
 SPI_I2S_ReceiveData(SPI2); // Clear RXNE, first word
 while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == 0); // wait for last bit to be sent
 SPI_I2S_ReceiveData(SPI2); // Clear RXNE, second word
 
 Delay_us(10);
 GPIO_SetBits(GPIOB, GPIO_Pin_12); // Release -CS
 
 
 Delay(1000);    //1second delay
 
 
 //await result readable via SPI and read in result via SPI   two 16bit reads over SPI
 
 GPIO_ResetBits(GPIOB, GPIO_Pin_12); // Assert -CS
 Delay_us(10); // overkill
 
 while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == 0); // should be empty
 
 SPI_I2S_ReceiveData(SPI2);  // clear RXNE
 SPI_I2S_SendData(SPI2, LTC_Internal_Temperature_select); // send command word
 while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_TXE) == 0); //wait for transmit buffer to not be empty (ie data loaded in)
 SPI_I2S_SendData(SPI2, 0); // Fill for 32-bits, remaining 16-bits in holding buffer
 while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == 0);
 tmp = SPI_I2S_ReceiveData(SPI2);  // read word from receive buffer, high order 16-bits
 adc_value =  tmp * 65536;
 while(SPI_I2S_GetFlagStatus(SPI2, SPI_I2S_FLAG_RXNE) == 0);  // wait until receive buffer is not empty
 tmp = SPI_I2S_ReceiveData(SPI2);  // read word from receive buffer, low order 16-bits
 adc_value = adc_value + tmp;
 
 Delay_us(10);
 GPIO_SetBits(GPIOB, GPIO_Pin_12); // Release -CS
 
  
 
  
 
Jump2Here:
 //send result via RS232
 
 while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
 USART_SendData(USART1, 0x43); // Send 'C'
 while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
 USART_SendData(USART1, 0x48); // Send 'H'
 while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
 USART_SendData(USART1, 0x30); // Send '0'
 while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
 USART_SendData(USART1, 0x3A); // Send ':'
 
 // Sends as binary, not ascii
 //adc_value = 1234567890;
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
 USART_SendData(USART1, ((adc_value >> 24) & 0xFF));
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
 USART_SendData(USART1, ((adc_value >> 16) & 0xFF));
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
 USART_SendData(USART1, ((adc_value >>  8) & 0xFF));
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
 USART_SendData(USART1, ((adc_value >>  0) & 0xFF));
 
 //goto SPI_Loop;
 
 while (1);
}


'Embedded Lab > ARM' 카테고리의 다른 글

[STM32 : SPI, using chip select2]  (0) 2014.03.05
[SWI의 진실]  (0) 2013.03.22
[논리 스프트와 산술 시프트의 차이]  (0) 2013.03.20
Posted by cyj4369
,

atoi


uint16_t Atoi(unsigned char* str)

{

  uint16_t nSign = 0, nSum = 0;

  

  if(*str == '-' || *str >= '0' && *str <= '9')

  {

    if(*str == '-')

    {

      nSign = 1;

      str++;

    }

    while(*str >= '0' && *str <= '9')

    {

      nSum = (nSum * 10) + (*str - '0');

      str++;

    }

    if(nSign)

      return -nSum;

    else

      return nSum;

  }

  else

    return 0;

}





itoa

unsigned char * Itoa(uint16_t s_value, uint16_t s_radix)

{

    static const char c_base_ascii[] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 'A', 'B', 'C', 'D', 'E', 'F'};

    static unsigned char s_buffer[ 64 ] = {0, };

    uint16_t s_offset = sizeof(s_buffer) - 1;


    do {

        s_buffer[--s_offset] = c_base_ascii[ s_value % s_radix ];

        s_value /= s_radix; 

    }while(s_value != 0u);


    return((unsigned char *)(&s_buffer[s_offset]));

}

'Development > C/C++' 카테고리의 다른 글

[고급 매크로 표현식]  (0) 2014.04.22
[Static Assert]  (0) 2014.04.16
[scanf에서 공백을 포함한 문자열을 받는 방법]  (0) 2014.02.09
[objdump in linux]  (0) 2014.01.15
[vim에서 hexedit하기, hex비교하기]  (0) 2014.01.15
Posted by cyj4369
,

scanf를 통하여 공백이 있는 문제열을 입력 받지 못하여 애를 먹였는데, 아래와 같은 방법이 있네요.

- 방법은 문자열 입력 조건을 통하여 처리하는 것입니다.

- 문자열 조건은 []을 통하여 넣을 수 있습니다. 

 

[[[예제]]] 

ㆍchar str[80];

   scanf("%[12345]s", str);

// 입력이 "4567" 이면 str에 "45" 가 기억

 

ㆍchar str[80];

   scanf("%[^12345]s", str);

// 입력이 "6745" 이면 str에 "67"dl rldjr

// ^ 는 [ ] 안 이외의 문자만 입력 허용

 

ㆍchar str[80];

   scanf("%[0-9]s", str);

// 입력이 "45ab" 이면 str에 "45" 가 기억

// 0-9 는 0123456789 와 동일

  

[[[ 공백을 포함한 문자열 입력 방법]]]

 

char str[80];

   scanf("%[^\n]s", str);

// '\n'(new line) 문자를 만나기 전까지 입력을 받습니다.

 

ㆍchar str[80];

   scanf("%79[^\n]s", str);

// '\n'(new line) 문자를 만나기 전까지 입력을 받되, 79자 까지만 입력을 받습니다.

 

ㆍchar str[80];
   scanf("%[a-zA-Z]s", str);

// 영문자만 입력을 받습니다.

 

 ps. gets()는 입력받을 글자수의 제한할 수 없음.

      제한을 두고 싶을땐 sacnf() 함수 사용.

 

 

----------------------------------------------------

c언어에서 가끔 발생하는 문제가 scanf로 입력받다가
입력버퍼가 다 비워지지 않아서 문자입력받는게 씹히는 경우가 생긴다.
c언어 공부하다보면 꼭 한번쯤은 겪어보는 문제
예를 들면

#include <stdio.h>

int main()
{
        char string[20];
        char c;

        scanf("%s", string);
        scanf("%c", &c);

        printf("%s\n", string);
        printf("!!%c!!\n", c);

        return 0;
}

실행 결과는?

문자열만 입력받아버리고 프로그램이 끝나버린다.

원인은
scanf("%s", string);
가 실행되고 나서 입력버퍼에는 개행문자가 그대로 남아있는 거다.

그래서 
scanf("%c", &c);
를 실행하려고 보니 버퍼에 개행문자가 있어서 그걸 c에다 넣어버린거다.
정작 표준입력으로는 아무것도 입력안했는데
예전에 이걸 몰라서 개고생한거 생각하면..

해결방법은
입력버퍼를 비우면 된다.

어떻게?
        scanf("%s", string);

       scanf("%c", &c);
이 두 사이에 입력버퍼를 비워주는 뭔가를 해주면 된다.

1. 간단하게는 getchar(); 를 추가하는 걸로도 가능

2. fflush(stdin); 추가
그런데 이건 gcc에서 안돌아간다. 왜? 당연히 안된다. 표준 fflush함수는 출력버퍼를 비우는 녀석이다.
VC에서는 확장해서 사용하므로 동작하지만 gcc는 안된다.

3. tcflush(0, TCIFLUSH); 추가
0번 디스크립터를 비워라. 그런데 이는 유닉스 계열에서 터미널과 관련된 함수인 듯

4. rewind(stdio); 추가
rewind함수는 매개변수로 들어온 스트림을 초기화하는데 사용

5. 
__fpurge(stdin);
이놈도 리눅스에서만 동작하고 표준은 아니다. stdio_ext.h 추가.

6. 
fgets(string, sizeof(string), stdin);
문자열 입력을 scanf가 아니라 fgets로 받는다.
그러나 입력시 사이즈를 오버하면 똑같은 문제가 발생한다.
그리고 사이즈를 오버하지 않더라도 문자열 끝에 개행문자가 추가된다.

그래서 다음 줄에
string[strlen(string)-1] = '\0'; 로 강제로 널문자를 넣어준다.
개인적으로 제일 많이 사용하는 방식

7. scanf("%*c", c);
%*c는 입력은 받지만 저장은 안한다. 즉 비어있는 \n를 날려버린다.

8. scanf("%c", &c);를 scanf(" %c", &c); 로
%c 앞에 공백을 추가하면 white space를 구분자로 인식한다.


입력들이 간단하게 위와 같이 나온다면 위의 방법들 아무거나 사용해도 되지만
복잡한 입력에 입력버퍼에 뭔가 많이 남는다면
버퍼를 비우는 것이 근본적인 해결방법인듯 하다.


출처 : http://blog.daum.net/jjiyong/18230445

'Development > C/C++' 카테고리의 다른 글

[Static Assert]  (0) 2014.04.16
[itoa, atoi 구현]  (0) 2014.03.04
[objdump in linux]  (0) 2014.01.15
[vim에서 hexedit하기, hex비교하기]  (0) 2014.01.15
[코드에서 endian을 파악하는 방법]  (0) 2014.01.06
Posted by cyj4369
,

ln 명령은 파일을 링크할 때 사용하는 명령입니다.

리눅스 시스템 상에는 심볼릭링크와 하드링크 두가지의 링크가 있습니다.

 

심볼릭링크는 원본파일을 가리키도록 링크만 시켜둔 것으로 윈도우의 바로가기와 같다고 보시면 됩니다. 심볼릭링크는 원본파일이 삭제되면 링크파일은 작동하지 않게 됩니다.

 

하드링크는 원본파일과 이름은 다르지만 동일한 파일입니다. 하드링크에서는 원본파일이나 링크파일 둘중의 하나가 삭제되더라도 나머지 하나는 그대로 남아 정상 동작 합니다. 또한 하드링크는 원본파일의 내용이 변경될 경우에 링크파일의 내용도 자동으로 변경됩니다.

 

명령어 위비: /bin/ln

사용형식 : ln [옵션] 원본파일 대상파일

             ln [옵션] 원본파일 대상디렉토리

옵션

-b, --backup : 대상파일이 이미 존재할 경우 백업파일을 만든 후에 링크파일을 생성

-d, -F, --directory : 디렉토리에 대한 하드링크파일 생성을 가능하게함

-f : 대상파일이 존재할 경우 대상파일을 지우고 링크파일을 생성

-i : 대상파일이 존재할 경우 대상파일을 지울 것인가 확인하게함

-s : 심볼릭링크파일을 생성

-S : 만약에 대상이 이미 있어서 백업을 해야 할 경우에 그 백업파일에서 사용 할 파일이름의

      접미사(suffix)를 지정할 수 있음

-t, --target-directory=DIRECTORY : 링크파일을 생성할 디렉토리를 지정

 

예1) ln 명령어를 사용하여 하드링크 생성하기

우선 hard_source 파일을 hard_link 파일로 하드링크 시킨 후 두 파일의 내용을 확인해 보도록 하겠습니다.

 

#ln hard_source hard_link

#

#ls -l

합계 12
-rw-r--r-- 2 root root 15  7월 19 21:54 hard_link

-rw-r--r-- 2 root root 15  7월 19 21:54 hard_source

 

#cat hard_source

linux

network

windows

 

#cat hard_link

linux

network

windows

 

위에서 보시는 것과 같이 두파일의 내용이 동일하다는 것을 알 수 있습니다.

이번에는 원본파일 내용의 첫행을 지운뒤 링크파일과 비교해 보도록 하겠습니다.

 

#cat hard_source

network

windows

 

#cat hard_link

network

windows

 

위와 같이 원본파일만 수정했는데도 링크된 파일의 내용도 같이 수정됨을 확인 할 수 있습니다.

 

 

예2)심볼릭링크 사용하기

심볼릭링크를 사용하기 위해서는 -s 옵션을 사용해야 합니다.

sym_source 파일을 만든뒤 sym_link 파일로 심볼릭링크 시키도록 하겠습니다.

 

#ln -s sym_source sym_link

#ls -l

lrwxrwxrwx 1 root root 14  7월 19 22:09 sym_link -> sym_source

-rw-r--r-- 1 root root 22  7월 19 22:09 sym_source

 

여기서 확인하고 넘어가야 할 부분은 심볼릭링크된 파일의 퍼미션이 하드링크일때와는 다르게

lrwxrwxrwx 이라는 것과 -> 로 원본을 가리켜 심볼릭링크된 파일이라는 것을 확인 할 수있게 해줍니다.

 

[출처] ln 명령어|작성자 김동훈



출처 : http://blog.naver.com/PostView.nhn?blogId=ehdgns621&logNo=130056448055

'Embedded Lab > linux, x86' 카테고리의 다른 글

[우분투 10.10 maveric apt-get update 에러]  (0) 2014.05.04
[우분투에서 monaco 폰트 설정]  (0) 2014.04.27
[특수문자표]  (0) 2013.11.04
[GFS(Google File System)]  (0) 2013.10.28
[top 명령어]  (0) 2013.10.23
Posted by cyj4369
,

다음은 objdump의 man내용이다


OBJDUMP(1)                   GNU Development Tools                  OBJDUMP(1)

NAME
       objdump - display information from object files.

SYNOPSIS
       objdump [-a│--archive-headers]
               [-b bfdname│--target=bfdname]
               [-C│--demangle[=style] ]
               [-d│--disassemble]
               [-D│--disassemble-all]
               [-z│--disassemble-zeroes]
               [-EB│-EL│--endian={big │ little }]
               [-f│--file-headers]
               [--file-start-context]
               [-g│--debugging]
               [-e│--debugging-tags]
               [-h│--section-headers│--headers]
               [-i│--info]
               [-j section│--section=section]
               [-l│--line-numbers]
               [-S│--source]
               [-m machine│--architecture=machine]
               [-M options│--disassembler-options=options]
               [-p│--private-headers]
               [-r│--reloc]
               [-R│--dynamic-reloc]
               [-s│--full-contents]
               [-W│--dwarf]
               [-G│--stabs]
               [-t│--syms]
               [-T│--dynamic-syms]
               [-x│--all-headers]
               [-w│--wide]
               [--start-address=address]
               [--stop-address=address]
               [--prefix-addresses]
               [--[no-]show-raw-insn]
               [--adjust-vma=offset]
               [--special-syms]
               [-V│--version]
               [-H│--help]
               objfile...

DESCRIPTION
       objdump displays information about one or more object files.  The options control what particular information to display.  This information is mostly use-
       ful to programmers who are working on the compilation tools, as opposed to programmers who just want their program to compile and work.

       objfile... are the object files to be examined.  When you specify archives, objdump shows information on each of the member object files.

OPTIONS
       The   long   and   short   forms   of   options,   shown   here   as   alternatives,   are   equivalent.    At   least   one   option   from   the    list
       -a,-d,-D,-e,-f,-g,-G,-h,-H,-p,-r,-R,-s,-S,-t,-T,-V,-x must be given.

       -a
       --archive-header
           If  any  of  the objfile files are archives, display the archive header information (in a format similar to ls -l).  Besides the information you could
           list with ar tv, objdump -a shows the object file format of each archive member.

Posted by cyj4369
,