Assignment
measure something: add a sensor to a microcontroller board that you've made and read it
This week, I made an "LED sensing board" which uses an LED as both a sensor and an actuator.
When an electric current runs through an LED, it glows.
Oppositely, when you apply a ray onto an LED, it generates electricity.
Using this function, this board let the LED turn on when it is dark and off when bright according to the value of brightness that the LED senses.
ATmega328P with a breadboard
Firstly, I program ATmega 328P because a professor in my campus shares a program for 168, it was easy to rewrite it for 328P. (referring to this book)
Here are the codes.
▼ledsense328p.c
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/wdt.h>
#include <util/delay.h>
#define F_CPU 1.0E6 //1MHz
#define ADC_VREF 0x45 /* 0100 0101 vcc:10bit:PC5: ADCW */
int main(void){
unsigned char i;
int th;
ADMUX=ADC_VREF;
th=0;
for(i=0;i<8;i++){ //8 times measurement
ADCSRA=0xC6; //1100 0110 ADC enabled start clock/64
while (( ADCSRA & 0x10)==0){} // PC5 is ADC input
th = th+ADCW;
ADCSRA=0x96; //1001 0110
}
th=th>>3; //average generated voltage
for(;;){
ADCSRA=0xC6; //ADC enabled start clock/64
while (( ADCSRA & 0x10)==0){}
ADMUX=0; //avoid analog in order to activate digital output
if(ADCW < th-605 ){
DDRC=0x20;
for(i=0;i<4;i++){
PORTC=0x20;
_delay_us(10);
PORTC=0x00;
_delay_us(10);
}
}
else if(ADCW>= th-600){
DDRC=0x20;
for(i=0;i<20;i++){
PORTC=0x00;
_delay_us(10);
}
}
DDRC=0; //avoid digital output
PORTC=0;
ADMUX=ADC_VREF;
ADCSRA=0x96;
}
}
Then I milled a board for ATtiny45V and rewrote the program but I couldn't make it.
Writing is always successful but an LED doesn't turn on.
I tested another simple program on it and it was successful, the board itself doesn't have a problem.
So I found this is a program's problem but still cannot find how it is wrong.
▼ledsense45.c
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/wdt.h>
#include <util/delay.h>
#define ADC_VREF 0x43 /* 0100 0011 vcc:10bit:PB3: ADCW */
int main(void){
unsigned char i;
int th;
ADMUX=ADC_VREF;
th=0;
for(i=0;i<8;i++){ //8 times measurement
ADCSRA=0xC6; //1100 0110 ADC enabled start clock/64
while (( ADCSRA & 0x10)==0){} //PB3 is ADC input
th = th+ADCW;
ADCSRA=0x96; //1001 0110
}
th=th>>3; //average generated voltage
for(;;){
ADCSRA=0xC6; //1100 0110 ADC enabled start clock/64
while (( ADCSRA & 0x10)==0){}
ADMUX=0; //avoid analog in order to activate digital output
if(ADCW < th-605){
DDRB=0x08;
for(i=0;i<4;i++){
PORTB=0x08;
_delay_us(10);
PORTB=0x00;
_delay_us(10);
}
}
else if(ADCW >= (th-600)){
DDRB=0x08;
for(i=0;i<20;i++){
PORTB=0x00;
_delay_us(10);
}
}
DDRB=0; //avoid digital output
PORTB=0;
ADMUX=ADC_VREF;
ADCSRA=0x96;
}
}