AVR's SD card basic reading and writing procedures (Part 2)

Publisher:捡漏来了Latest update time:2016-08-15 Source: eefocusKeywords:avr Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere
SD card read and write subroutine

Hardware platform: atmega8L minimum system
                    hard SPI (the SD card initialization uses the IO port simulation timing, because it is found in the experiment that a lower rate is required for stable initialization)
Software development platform: ICC-AVR version 6.31a
Hardware configuration: atmega8L internal 8m clock
                    Sandisk 128m SD card
 
Several basic subroutines and their introductions:
 
1. The IO port simulates SPI to realize data transmission, and is used during initialization
void iodatatransfer(unsigned char iodata)
 {
 unsigned char num,b;
 num=0x80;
 for (b=0;b<0x08;b++)  
     {  
    WDR();//feed the dog
  //SD_Write|=(1<        SD_Write&=~(1<     if(iodata&num)
    SD_Write|=(1<     else
    SD_Write&=~(1<     delay_4ms();//4ms
    WDR();//feed the dog
    //SD_Write&=~(1<     SD_Write|=(1<     delay_4ms();//4ms
    if(num>0x01)
    num=num>>1;
     }  
 }  
 
2. The io port simulates spi to realize data reading. During initialization, use
 unsigned char iodataread(void)
 {
   unsigned char data,temp,b;
   data=0;
   temp=0;
   for (b=0;b<0x08;b++)
   {
    WDR();//feed the dog  
    SD_Write&=~(1<  delay_4ms();//4ms
    WDR();//feed the dog
  
    SD_Write|=(1<  temp=SD_READ;
 temp&=0x10;//to maintain the pb.4 bit(data_in)
  WDR();//feed the dog
 if(temp)
  {
  data|=0x01;  
     }
 if(b<7)
  { 
  data=data<<1;//
     }
 delay_4ms();//4ms
  WDR();//feed the dog
   }   
   return data ;
 }


3. The io port simulates spi to implement command sending and read response. During initialization, use 
  unsigned char iocmd(unsigned char *cmd)
 {
 unsigned temp,a,timeout;
 temp=0xff;
 timeout=0;
 // Raise chip select -- ---/ss=1 
 SD_Disable();  
 WDR();//feed the dog
  
 // Send an 8 bit pulse  
 iodatatransfer(0xff);
 WDR();//feed the dog
 // Lower chip select  
 SD_Enable();
  for(a=0;a<6;a++)
  {
  iodatatransfer(*cmd++);
  WDR();
  //transfer cmd in io_mode 
  }
  while(temp==0xff)//
      {  
    WDR();//feed the dog
       temp =iodataread();  
       if(timeout++>100)  
         {  
          break;  
         }  
      } 
  WDR();//feed the dog
 return(temp);//the respone of the byte_write_operation      
 }
 
4. Hard spi read data
 unsigned char Read_Byte_SD(void)  
{  
 char Byte;
   //SD_Enable();
 SPDR=0xff;  
 while(!(SPSR&(1<  Byte=SPDR; 
 return(Byte) ;  

 
5. Hard spi write data
void Write_Byte_SD(char Byte)  
{  
//SD_Enable();
 SPDR=Byte;  
 while(!(SPSR&(1< }  
 
6. Hard spi write command and read response
unsigned char Write_Command_SD(char *CMD)  
{  
 unsigned char a;  
 unsigned char tmp=0xff;  
 unsigned char Timeout=0;  
 // Raise chip select -----/ss=1 
 SD_Disable();  
 // Send an 8 bit pulse  
 Write_Byte_SD (0xFF);  
  
 // Lower chip select  
 SD_Enable();  
 //Send the 6 byte command  
 for(a=0;a<0x06;a++)  
    {  
     Write_Byte_SD(*CMD++);  
    }  
 //Wait for the response  
 while(tmp==0xff)//
      {  
       tmp=Read_Byte_SD();  
       if(Timeout++>100)  
         {  
          break ;  
         }  
      }  
 //for some reason we need to delay here  
//delay_1ms(); 
 return(tmp);//the respone of the byte_write_operation  

 
7. Initialize
unsigned char SDInit(void)  
{  
 unsigned char a,b,retry, erroetoken;  
 unsigned char CMD[]={0x40,0x00,0x00,0x00,0x00,0x95};//cmd0
 // Set certain pins to inputs and others to outputs  
 // Only SPI_DI (data in) is an input  
 //SD_Direction_REG ==ddrb
 SD_Direction_REG&=~(1<  SD_Direction_REG|=(1<  SD_Direction_REG|=(1<  SD_Direction_REG|=(1<  //SD_Direction_REG|=(1<  SD_Disable();
 //We need to wait for the SD_Direction_REG to be ready  
 for(a=0;a<200;a++)  
    {  
  WDR();//feed the dog
     nop(); 
  nop();
    };  
 delay_1ms();
 
 SD_Disable();//   
 iodatatransfer(0xff);
 WDR();//feed the dog
 //return 0;/////////// 
  
 retry=0;
 SD_Enable();
 while((erroetoken=iocmd(CMD))!=0x01)//
 { 
 WDR();
 //serial(erroetoken); 
 if(retry++>200)  
 { //fail and return
 return 1;  
 }  
 }  
  //return 0;///////////
  
//Send the 2nd command  
 retry=0;  
 CMD[0]=0x41;  
 CMD[5]=0xFF;  
while(erroetoken=iocmd(CMD)!=0x00)  
      {  
    WDR();
       if (retry++>200)  
          { 
          return 2;  
          }  
       }      
    
 //Set the SPI bus to full speed 
 SPCR=0x50; 
  SPSR|=0x01;
 //Raise Chip Select  
 SD_Disable();  
 return 0;  
}  
 
8.设置每次读的字节数
char SD_set_length(unsigned int length) 
{
 unsigned char retry; 
 //Command to set the block length; 
 char CMD[]={0x50,0x00,0x00,0x00,0x00,0xFF}; //cmd16 
  
 CMD[3]=((length&0xFF00)>>8);// 
 CMD[4]= (length&0x00FF);  
 while(Write_Command_SD(CMD)!=0)//  
      {  
    WDR(); 
       if (retry++>200)  
          {  
          return 1;  
          }  
       } 
 SD_Disable(); 
 return 0; 
}

9.write 512 bytes to a given sector from a  Byte_byte_long  Buffer
unsigned char SD_write_sector(unsigned long addr,unsigned char *Buffer,unsigned int Bytes) 

 unsigned int a; 
 unsigned char retry,temp; 
 //Command to read a block; 
 char CMD[]={0x58,0x00,0x00,0x00,0x00,0xFF};//cmd24
 CMD[1]=((addr&0xFF000000)>>24);  
 CMD[2]=((addr&0x00FF0000)>>16);  
 CMD[3]=((addr&0x0000FF00)>>8); 
 CMD[4]=(addr&0x000000FF); 
  //Send the write command  
   
 while(Write_Command_SD(CMD)!=0)  
      {  
       if (retry++>50)  
          {  
          return 1;  
          }  
       }  
 //Send the start byte  
 Write_Byte_SD(0xfe);                                                                           
 //Read off all the bytes in the block  
 for(a=0;a  {  
 Write_Byte_SD(*Buffer++);
 }   
 while((temp=Read_Byte_SD())&0x10);
 //serial(temp);//according to p101 of datasheet
 if((temp&0x0f)!=0x05)
 return 2;
 //Read CRC byte  
 while(SD_READ&0x10);//detect if data_in pb.4 is still busy(high) 
   
 // Set SD_Chip_Select to high  
 SD_Disable();  
 //SEI(); //re-enable interrupts  
 return 0;  
 
}

unsigned char SD_read_sector(unsigned long addr,unsigned char *Buffer,unsigned int Bytes)  
{  
 
 unsigned int a; 
 unsigned char retry; 
 //Command to read a block; 
 char CMD[]={0x51,0x00,0x00,0x00,0x00,0xFF};//cmd17
 //CLI(); //disable all interrupts
 //addr = addr << 9; //addr = addr * 512  
 CMD[1]=((addr&0xFF000000)>>24);  
 CMD[2]=((addr&0x00FF0000)>>16);  
 CMD[3]=((addr&0x0000FF00)>>8); 
 CMD[4]=(addr&0x000000FF); 
  //Send the read command  
   
 while(Write_Command_SD(CMD)!=0)  
      {  
    WDR();//feed the dog
       if (retry++>200)  
          {  
          return 1;  
          }  
       }  
 //Send the start byte  
  while(Read_Byte_SD()!=0xfe)  
  {
  WDR();//feed the dog
  }                                                                             
 //Read off all the bytes in the block  
 for(a=0;a  {  
  WDR();//feed the dog
 *Buffer=Read_Byte_SD();  
 //serial(*Buffer); 
 Buffer++; 
 }   
 //Read CRC byte  
 Read_Byte_SD();  
 Read_Byte_SD();  
   
 // Set SD_Chip_Select to high  
 SD_Disable();  
 //SEI(); //re-enable interrupts  
 return 0;  
}  
/*
//read xx bytes no matter of misalignment!!
*/
unsigned char read_antimisaliment(unsigned long addr_temp,unsigned char *p_buffer, unsigned int length)
{
  unsigned int _length=0x0000;
  SD_Enable(); 
  while(SD_read_sector(addr_temp,p_buffer,length))
  {
  SD_Enable();//
  length-=0x0001;//to find a suuitable length to avoid misalignment
  _length+=0x0001;// _length+length==xx
  SD_set_length(length);
  }  
  ///
  if(_length==0x0000)
  {
  return 0;
  }
  ///
  addr_temp+=length;
  SD_Enable();//
  SD_set_length(_length); 
  SD_Enable();//
  while(SD_read_sector(addr_temp,p_buffer,_length))
  {
  SD_Enable();
  }
  SD_Enable();//
  SD_set_length(length+_length);//to read the rest bytes of the xx bytes
  return 0;
  /////////////////
 }

Keywords:avr Reference address:AVR's SD card basic reading and writing procedures (Part 2)

Previous article:Fuse configuration of avr microcontroller
Next article:AVR's SD card basic reading and writing procedures (I)

Recommended ReadingLatest update time:2024-11-16 13:29

How to make program debugging easier with AVR microprocessors
  introduction   With the development of technology, the design and application of embedded systems have had a great impact on people's lives and will gradually change people's future lifestyles. Developing applications on a specific operating system allows developers to ignore many underlying hardware details, maki
[Microcontroller]
AVR microcontroller controlled relay
#include "macros.h" #define uchar unsigned char #define uint  unsigned int void delay_ms(uchar i) { uchar a,b; for(a=1;a i;a++)    for(b=1;b 141;b++)    {;} } void main(void) { DDRA=0X80; PORTA=0X80; DDRB=0XFF; PORTB=0XFF; DDRC=0X01; PORTC=0X01; DDRD=0X00; PORTD=0XFF; while(1)   {    PORTA  ^=  BIT(7);     delay_ms
[Microcontroller]
AVR microcontroller controlled relay
AVR MCU Timer/Counter Study Notes (Part 3)
    Timer/Counter 1 (16-bit) has normal mode, CTC mode, fast PWM mode, phase correction PWM mode and other operating modes. 3. Fast PWM mode (needs to use two pins OC1A and OC1B) Prerequisite: Set the waveform generation mode to mode 15 (fast PWM) by combining bit 4 and bit 3 of TCCR1B and bit 1 and bit 0 of TCCR1A ).
[Microcontroller]
AVR MCU Timer/Counter Study Notes (Part 3)
AVR microcontroller (learning) - (II), ATMEGA16 interrupt system - 01
2. ATMEGA16 interrupt system 2- (01) Two-way anti-theft system test As mentioned in the previous article, this microcontroller controls the so-called registers to control the related functions of the microcontroller (the reason why it is more powerful than 51 is that it combines these and several other buses, which wi
[Microcontroller]
AVR microcontroller (learning) - (II), ATMEGA16 interrupt system - 01
AVR MCU Learning ATmega16 ADC
Conversion rate: The number of samples taken per second. Common units: SPS (times per second) KSPS (kilosamples per second) MSPS (millionsamples per second). The faster, the better. Conversion precision: The number of significant digits (in binary) of the conversion result. Unit: bit AVR's on-chip ADC: Maxim
[Microcontroller]
AVR MCU Learning ATmega16 ADC
AVR high-end microcontroller internal EEPROM method! Can be used!
/************************************************************** ;eeprom.c can be used in AVR microcontrollers, ATMEGA16 and ATMEGA8, under GCC ;Compiled. November 1, 2009! Chen Yongfei has tested it! ; Example of reading/writing atmega8515 internal EEPROM ;Write data 0....9 into eeprom, then read it out and display i
[Microcontroller]
AVR memory organization and internal EEPROM read and write examples
There are three types of independently addressed memories inside the AVR series microcontrollers: Flash program memory, internal SRAM data memory and EEPROM data memory. Flash memory is 1K~128K bytes, supports parallel programming and serial download, and the download life is usually up to 10,000 times. Since AVR in
[Microcontroller]
Design of intelligent treadmill controller based on AVR microcontroller
1 Introduction The electric treadmill is the mainstream product among fitness equipment at present. It uses a motor to drive the running belt to make people run or walk passively at different speeds. In terms of human strength, it saves a stretching action compared to running and walking on the ground, which ca
[Microcontroller]
Design of intelligent treadmill controller based on AVR microcontroller
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号