⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 common.c

📁 AVRmega28L的串口发送数据程序
💻 C
字号:

#include <iom128v.h>
#include <macros.h>
#include "config.h"

void port_init(void)
{
 PORTA = 0x00;
 DDRA  = 0x00;
 PORTB = 0x80;
 DDRB  = 0x80;
 PORTC = 0x00; //m103 output only
 DDRC  = 0x00;
 PORTD = 0x00;
 DDRD  = 0x00;
 PORTE = 0x00;
 DDRE  = 0x00;
 PORTF = 0x00;
 DDRF  = 0x00;
 PORTG = 0x00;
 DDRG  = 0x00;
}

//SPI initialize
// clock rate: 1000000hz
void spi_init(void)
{
 SPCR = 0x50; //setup SPI
 SPSR = 0x00; //setup SPI
}
//1200  4M
void uart0_init(void)
{
 UCSR0B = 0x00; //disable while setting baud rate
 UCSR0A = 0x00;
 UCSR0C = 0x06;
 UBRR0L = 0xCF; //set baud rate lo
 UBRR0H = 0x00; //set baud rate hi
 UCSR0B = 0x18;
}

//UART1 initialize
// desired baud rate:2400
// actual baud rate:2404 (0.2%)
// char size: 8 bit
// parity: Disabled
void uart1_init(void)
{
 UCSR1B = 0x00; //disable while setting baud rate
 UCSR1A = 0x00;
 UCSR1C = 0x06;
 UBRR1L = 0x67; //set baud rate lo
 UBRR1H = 0x00; //set baud rate hi
 UCSR1B = 0x18;
}

//call this routine to initialize all peripherals
void init_devices(void)
{
 //stop errant interrupts until set up
 CLI(); //disable all interrupts
 XDIV  = 0x00; //xtal divider
 XMCRA = 0x00; //external memory
 port_init();
 spi_init();
 uart0_init();
 uart1_init();

 MCUCR = 0x00;
 EICRA = 0x00; //extended ext ints
 EICRB = 0x00; //extended ext ints
 EIMSK = 0x00;
 TIMSK = 0x00; //timer interrupt sources
 ETIMSK = 0x00; //extended timer interrupt sources
 SEI(); //re-enable interrupts
 //all peripherals are now initialized
}





//*********************************************************************/ 
//*函数名:delay()
//*函数功能:延时函数
//*函数说明:无返回值  t为一个延时的时间
//*设计者: yu  日期:2007-10-20
//**********************************************************************/
void delay(int t)
{
    int i,j ;
    for(i=0;i<t;i++)
    for(j=0;j<t;j++);
}

//////////////////////////////////////////////////////////
/*led_on_off()
/*LED的开和关闭
*/
void led_on_off(BYTE led_flag)
{
    //设置PC0口为输出0,点亮LED
    if(led_flag==1)
    {
        PBO.B4=0 ;
        PBD.B4=1 ;
    }
    //设置PC0口为输出1,关闭LED
    else 
    {
        PBO.B4=1 ;
        PBD.B4=1 ;
    }
}

void led_response (int t)
{
 int i;
 for(i = 0;i < t;i++)
  {
    led_on_off(ON);           //点亮LED灯
    delay(150);
    led_on_off(OFF);           //关闭LED灯
    delay(150);    
  }
}

void SPI_MasterInit(void)
{
/* 设置MOSI 和SCK 片选为输出,其他为输入 */
PORTB |= (1<<PB3) | (1<<PB4) | (1<<PB5) | (1<<PB6); 
DDRB = (1<<DDB2)|(1<<DDB1)|(1<<DDB0);
/* 使能SPI 主机模式,设置时钟速率为fck/16 */
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}
void SPI_MasterTransmit(char cData)
{
PORTB &=~ (1<<PB0); //强制接收方进入从模式
SPCR |= (1<<MSTR); // MSTR有时会被清零,这里强制进入主机模式
/* 启动数据传输 */
SPDR = cData;
/* 等待传输结束 */
while(!(SPSR & (1<<SPIF)));
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -