Arduino Color
Arduino Color
h>
#include <avr/interrupt.h>
#include <util/delay.h>
// Pin definitions
#define BUTTON1_PIN 2 // Button1 pin
#define BUTTON2_PIN 3 // Button2 pin
#define BUTTON0_PIN 4 // Button0 pin
#define JOYSTICK_X_PIN 0 // Joystick X-axis pin (ADC0)
#define JOYSTICK_Y_PIN 1 // Joystick Y-axis pin (ADC1)
// Global variables
volatile uint8_t joystickXValue = 0; // Variable to store joystick X-axis value
volatile uint8_t joystickYValue = 0; // Variable to store joystick Y-axis value
volatile uint8_t redDutyCycle = 0; // Duty cycle for Red LED (0-255)
volatile uint8_t greenDutyCycle = 0; // Duty cycle for Green LED (0-255)
volatile uint8_t blueDutyCycle = 0; // Duty cycle for Blue LED (0-255)
// Function declarations
void setup();
void loop();
void initializeADC();
void initializePWM();
void initializeInterrupts();
void readJoystick();
void updateLEDs();
void button1ISR();
void button2ISR();
void button0ISR();
void setup() {
// Initialize ADC, PWM, and interrupts
initializeADC();
initializePWM();
initializeInterrupts();
}
void loop() {
readJoystick(); // Read joystick values
updateLEDs(); // Update LED PWM based on joystick values
_delay_ms(1000); // Delay for 1 second
}
void initializeADC() {
// Set ADC prescaler to 128 for 16MHz clock (ADC clock = 16MHz / 128 = 125kHz)
ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
// Enable ADC, enable ADC auto trigger, set ADC auto trigger source to Free
Running mode
ADCSRA |= (1 << ADEN) | (1 << ADATE) | (1 << ADIE);
// Start conversion
ADCSRA |= (1 << ADSC);
}
void initializePWM() {
// Set OC0A (RGB_GREEN_PIN) and OC0B (RGB_RED_PIN) pins as output
DDRD |= (1 << DDD6) | (1 << DDD5);
void initializeInterrupts() {
// Set Button1 and Button2 pins as input with pull-up resistors
DDRD &= ~(1 << DDD2) & ~(1 << DDD3);
PORTD |= (1 << PORTD2) | (1 << PORTD3);
void readJoystick() {
// Start ADC conversion
ADCSRA |= (1 << ADSC);
void updateLEDs() {
// Map joystick X-axis value to red duty cycle
redDutyCycle = joystickXValue;
ISR(INT1_vect) {
// Button1 ISR
// Increment green duty cycle by 5
greenDutyCycle += 5;
if (greenDutyCycle > 255) greenDutyCycle = 255; // Clamp at 255
}
ISR(INT0_vect) {
// Button0 ISR
// Prompt user to enter a three-digit number
Serial.println("Please enter a three-digit number:");
while (Serial.available() < 3) {} // Wait until three digits are entered
int number = 0;
for (int i = 0; i < 3; i++) {
number *= 10;
number += (Serial.read() - '0'); // Convert ASCII to integer
}
// Display each digit for one second on 7-Segment
for (int i = 2; i >= 0; i--) {
Serial.println(number / pow(10, i));
_delay_ms(1000);
number %= (int)pow(10, i);
}
}