我正在尝试使用USART通信接收和发送数据,我使用atmega16。我在PC中创建程序将字符串发送到micro,如果字符串匹配,micro将激活adc并将adc数据发送到PC。
这是我的微控制器中的代码
#include <mega16.h>
#include <delay.h>
#include <stdio.h>
#include <string.h>
#define ADC_VREF_TYPE 0xC0
unsigned int read_adc(unsigned char pin_adc)
{
ADMUX=pin_adc | ADC_VREF_TYPE;
// Delay needed for the stabilization of the ADC input voltage
delay_us(10);
// Start the AD conversion
ADCSRA|=0x40;
// Wait for the AD conversion to complete
while ((ADCSRA & 0x10)==0);
ADCSRA|=0x10;
return ADCW;
}
//unsigned char DataInput = 0x00;
unsigned long int osilator = 12000000;
unsigned long int UBRR;
unsigned int t0, t1, t2, t3;
float t00, t11, t22, t33;
void inisialisasiUART(unsigned long int baud_rate);
//unsigned char getData(void);
unsigned char compare[30] = "a";
unsigned char input[30];
unsigned char buf[30];
void main(void)
{
ADMUX = ADC_VREF_TYPE;
ADCSRA = 0x85;
inisialisasiUART(9600);
while(1)
{
//DataInput = getData();
scanf("%s", input);
if(strcmp(input, compare) == 0)
{
t0 = read_adc(0);
t00 = (float)t0*256/1024;
t1 = read_adc(1);
t11 = (float)t0*256/1024;
t2 = read_adc(2);
t22 = (float)t0*256/1024;
t3 = read_adc(3);
t33 = (float)t0*256/1024;
sprintf(buf, "a%.2f %.2f %.2f %.2fa", t00, t11, t22, t33);
printf("%s", buf);
}
}
}
void inisialisasiUART(unsigned long int baud_rate)
{
UBRR = (osilator/(16*baud_rate))-1;
UBRRL = UBRR;
UBRRH = UBRR>>8;
UCSRB = 0x18;
UCSRC = 0x86;
}
unsigned char getData(void)
{
while(!(UCSRA & 0x80));
return UDR;
}
从我的代码中,错误在哪里?我可以使用scanf接收usart数据吗?什么是接收和发送数据的最佳方式?使用UDR或printf scanf? 谢谢
答案 0 :(得分:0)
嗯,你可以使用strncmp(),但我个人使用的是strstr(),当我需要解析&#34;解析&#34;响应。
答案 1 :(得分:-2)
enter code here
include<stdlib.h>
char str2[40];
float dist_klimeter;
dist_klimeter=cust5_distance/1000.00;
ftoa(dist_klimeter, 2, str2);
sprintf(string, " d:%sKm" , str2);