microchip中使用printf给AVR单片机串口重定向

 

 重定向中修改需要的串口

#ifndef USART1_H_
#define USART1_H_

#ifndef F_CPU
#define  F_CPU 11059200UL
#endif
#define  BAUDRATE    9600
#include <avr/io.h>
#include <avr/interrupt.h>


#include <stdio.h>
#include <string.h>


#define PRINT
/*
* printf 重定向
  初始化串口后需要执行  stdout = &mystdout;
*/
#ifdef PRINT
static int uart_putchar(char c, FILE *stream);
static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL,_FDEV_SETUP_WRITE);
static int uart_putchar(char c, FILE *stream)  //自定义的putchar
{
	while(!(UCSR1A&0x20)); 
	UDR1 = c;
	return 0;
}
#endif


void init_USART1( void );			 // USART1 初始化
void usart1_send(uint8_t data);       // 发送采用查询方式,发送一个字节
void usart1_s(char * data);           // 发送字符串
void usart1_send_array(uint8_t send_array[],uint8_t num);

#endif /* USART1_H_ */

 初始化中一定要加入stdout = &mystdout;

#include <usart1.h>
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

void  init_USART1( void ) // USART1 初始化
{
	stdout = &mystdout;
	UCSR1B = 0x00;    // 禁止发送器和接收器,禁止串口中断
	UCSR1A = 0x00;	  // 各标志位清零
	UCSR1C = (1<<UCSZ10)|(1<<UCSZ11);	   //写 ,异步,8位数据,无奇偶校验,一个停止位,无倍速
	UBRR1L = (F_CPU/BAUDRATE/16-1)%256; //9600
	UBRR1H = (F_CPU/BAUDRATE/16-1)/256;
	
	UCSR1B = (1<<TXEN1)|(1<<RXEN1)|(1<<RXCIE1);    // 使能发送 ,使能接收,使能接收中断
	
	sei();
}
void usart1_send(uint8_t data)
{
	while(!(UCSR1A&(1<<UDRE1))); //第五位是否为1,从而满足条件退出循环发送数据
	UDR1=data;
	while(!(UCSR1A&(1<<TXC1)));
	UCSR1A|=(1<<TXC1); //写1进行清除操作
}

void usart1_s(char * data)   //发送字符串
{
	while (*data)
	{
		usart1_send(*data++);
	}
}
void usart1_send_array(uint8_t send_array[],uint8_t num) //两个参数 一是数组(的数据) 二是数组长度1-255
{
	//串口发送
	uint8_t i=0;  //定义一个局部变量  用来 发送字符串 ++运算
	while(i<num)
	{
		usart1_send(send_array[i]); // 发送数据
		i++;  //值 加一
	}
}
int main(void)
{
    /* Replace with your application code */
	wdt_enable(WDTO_1S);        // 启动看门狗,1s一次
	init_USART1();				// USART1 初始化
    while (1) 
    {
		wdt_reset();            // 喂狗
		printf("page2.t3.txt=\"%d\"\xff\xff\xff",P1[0]);
		P1[0]++;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值