CSI 012: Micro-Controller Programming Using Arduino - Q&A
Q1. What is a sketch in Arduino?
A sketch is a program written using the Arduino IDE, consisting of a setup() and loop() function. It is uploaded
to the board for execution.
Q2. What are comments and why are they useful?
Comments are lines ignored by the compiler, used to document code and improve readability.
Q3. Sketch using comparison operators to control LED:
int ledPin = 13;
int sensorPin = A0;
void setup() { pinMode(ledPin, OUTPUT); }
void loop() {
int val = analogRead(sensorPin);
if (val > 500) digitalWrite(ledPin, HIGH);
else digitalWrite(ledPin, LOW);
Q4. Significance of analog in pins:
Analog in pins (A0-A5) read variable voltages using ADC, returning values from 0-1023.
Q5. Why be cautious with delay():
Excessive use blocks code execution, making Arduino unresponsive. Prefer millis() for non-blocking timing.
Q6(a). Sketch using comparison/logical operators:
if (value > 800 || value < 300) triggerBuzzer();
if (value >= 300 && value <= 800) lightLED();
Q6(b). While loop until condition met:
while (analogRead(A0) < 600) { delay(200); } // waits until sensor exceeds 600
Q7(a). Potentiometer with analogRead():
int value = analogRead(A0); Serial.println(value); // reads and prints pot value
Q7(b). map() to control LED brightness:
int pot = analogRead(A0);
int brightness = map(pot, 0, 1023, 0, 255);
analogWrite(9, brightness);
Q8(a). Blink with millis():
if (millis() - previousTime >= 500) {
previousTime = millis();
ledState = !ledState;
digitalWrite(13, ledState);
Q8(b). Improve randomness:
randomSeed(analogRead(A0)); // uses electrical noise for better randomness
Q9(a). for loop usage:
for (int i = 0; i < 10; i++) { digitalWrite(ledPin, HIGH); delay(100); digitalWrite(ledPin, LOW); }
Q9(b). continue statement:
for (int i = 0; i < 10; i++) { if (i % 2 == 0) continue; Serial.println(i); }
Q10(a). PWM vs analogWrite():
PWM simulates analog output via digital pulses; analogWrite() generates PWM using 0-255 values.
Q10(b). Serial control of servo:
if (Serial.available()) {
char c = Serial.read();
if (c == 'L') servo.write(0);
else if (c == 'R') servo.write(180);
}
Q11(a). attachInterrupt() usage:
attachInterrupt(digitalPinToInterrupt(2), stopMotor, FALLING);
void stopMotor() { emergencyStop = true; }
Q11(b). Timing with delay():
digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(1000);
Q12(a). Function with pin parameter:
void togglePin(int pin) {
digitalWrite(pin, HIGH); delay(500); digitalWrite(pin, LOW);
Q12(b). Hardware interrupt example:
attachInterrupt(digitalPinToInterrupt(2), emergencyStopISR, FALLING);
void emergencyStopISR() { emergencyStop = true; }