Split from: Atmega8 USART Problem

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
  

 

Hi guys, i have another problem,

im trying do send the value of ADC(0) and ADC(1), im using a joystick, but when i run the code, the x and y have the same value, sometimes, when i start to read the code, the x show me the correcto value, but after 1 while cycle, x=y

 

 

any suggestion?


/* Created: 26/09/2017 11:58:03
 * Author : Eduardo Pilar
 */ 
 // Atmega 8, @16Mhz

#include <avr/interrupt.h>
#include <stdio.h>
#ifndef F_CPU
#define F_CPU 16000000UL
#endif
#include <util/delay.h>
#define USART_BAUDRATE 9600
#define BAUD_PRESCALER (((F_CPU) / (USART_BAUDRATE * 16UL))-1)

void initADC(void)
{
	ADMUX |=(1<<REFS0); /*  VCC as Ref */
	ADCSRA |=(1<<ADEN)|(1<<ADPS0)|(1<<ADPS1)|(1<<ADPS2); /* ADEN enable do ADC, 128 Prescaler*/
	

}

uint16_t read_adc(uint8_t ch)
{
	ch &= 0b00000111; // choose channel
	ADMUX|=ch;
	ADCSRA|=(1<<ADSC); //start conversion
	while(!(ADCSRA&(1<<ADSC))); 
	return(ADC);
	
}

void initUSART(void)
{
	
	UBRRH=(BAUD_PRESCALER>>8);
	UBRRL= BAUD_PRESCALER; // baud rate de 9600
	UCSRA=0x00;
	UCSRB=(1<<RXEN)|(1<<TXEN); // enabe tx and rx 
	UCSRC=(1<<URSEL)|(1<<USBS)|(3<<UCSZ0); // 1 stops bit, 8 bit data

}


unsigned char receiveusart(void)
{
	while(!(UCSRA&(1<<RXC)));
	return UDR;
	
}

void send_usart ( uint8_t data)
{

	while((UCSRA & (1<<UDRE))==0);
	UDR = data;
}


int main(void)
{
	
	int x;
	initUSART();
	initADC();

    while (1) 
    { 
		
		
		
 		x = (uint8_t)(read_adc(0)>>2);
		y = (uint8_t)(read_adc(1)>>2);
		_delay_ms(2000);
		send_usart('a'); 
		_delay_ms(2000);
		send_usart(x);
		_delay_ms(2000);
		send_usart('b');
		_delay_ms(2000);
		send_usart(y);
		

	}

}

 

 

Last Edited: Tue. Oct 24, 2017 - 05:28 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

docasbb wrote:
i have another problem

So start a new thread, then!

 

(and don't forget to mark the old one as 'Solved')

Last Edited: Tue. Oct 24, 2017 - 09:52 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0


uint16_t read_adc(uint8_t ch)
ADMUX =(1<<REFS0)| (ch & 0x07);.... // 1rst time, your ADC has channel 1; 2nd time ... channel 1 or channel 2== channel 3 and it is stuck with channel 3
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Cross-post; continue at http://www.avrfreaks.net/forum/j...

:: Morten

 

(yes, I work for Atmel, yes, I do this in my spare time, now stop sending PMs)

Topic locked