Unit 20: Keypadless Digits

 

 

 

Code for Sketch One: 



// Pin definitions
const int ledPin = 7;      // LED connected to pin 7
const int joystickX = A0;  // Joystick X-axis connected to analog pin A0
const int joystickY = A1;  // Joystick Y-axis connected to analog pin A1

// Threshold for detecting “fully top right” position
const int threshold = 100;  // Adjust this value if needed

void setup() {
  pinMode(ledPin, OUTPUT);   // Set LED pin as output
  Serial.begin(9600);        // Start serial communication for debugging
}

void loop() {
  // Read joystick positions
  int xPos = analogRead(joystickX);
  int yPos = analogRead(joystickY);

  // Print joystick values for debugging
  Serial.print("X Position: ");
  Serial.print(xPos);
  Serial.print(" | Y Position: ");
  Serial.println(yPos);

  // Check if joystick is pushed fully top right (X and Y at max values)
  if (xPos > (1023 - threshold) && yPos < threshold) {
    digitalWrite(ledPin, HIGH);   // Turn on LED
    Serial.println("LED ON: Joystick fully top right");
  } else {
    digitalWrite(ledPin, LOW);    // Turn off LED
  }

  delay(100);  // Small delay for smooth reading
}


  

Code for Sketch Two (Serial output):



#include  // Library for the TM1637TinyDisplay

// Pin definitions for TM1637TinyDisplay
const int CLK = 2;       // Clock pin for TM1637
const int DIO = 3;       // Data pin for TM1637
TM1637TinyDisplay display(CLK, DIO);  // Create a display object

// Pin definitions
const int ledPin = 7;      // LED connected to pin 7
const int joystickX = A0;  // Joystick X-axis connected to pin A0
const int joystickY = A1;  // Joystick Y-axis connected to pin A1

// Threshold for “score” range
const int minScore = 100;
const int maxScore = 200;

void setup() {
  pinMode(ledPin, OUTPUT);  // Set LED pin as output
  display.setBrightness(7); // Set display brightness (0 to 7)
  Serial.begin(9600);       // Start serial communication for debugging
}

void loop() {
  // Read joystick positions
  int xPos = analogRead(joystickX);
  int yPos = analogRead(joystickY);

  // Combine x and y values to create a “score”
  int score = abs(xPos - 512) + abs(yPos - 512); // Calculate distance from center

  // Print joystick values and score for debugging
  Serial.print(“X Position: “);
  Serial.print(xPos);
  Serial.print(“ | Y Position: “);
  Serial.print(yPos);
  Serial.print(“ | Score: “);
  Serial.println(score);

  // Display the score on the 4-digit display
  display.showNumber(score);

  // Check if the score is within the target range
  if (score >= minScore && score <= maxScore) {
    digitalWrite(ledPin, HIGH);   // Turn on LED if within range
    Serial.println(“LED ON: Score within range”);
  } else {
    digitalWrite(ledPin, LOW);    // Turn off LED if out of range
  }

  delay(100);  // Small delay for smooth operation
}

  

 

Notes: