2022年12月4日 星期日

[Arduino] Blink LED

"Blinking LED" is usually the first application for beginners, and even experienced users starting with a new MCU or board will often start here. Typically, they will first learn about the basic I/O driving capabilities and how I/O performs in timing. Therefore, this is a commonly used example.

There are two types of I/O output: Sink current and Source current. The difference is the direction of current flow. Sink current is when the power current flows through the load towards the MCU, while Source current is when the MCU output current flows through the load towards ground. It is important to note that the logic of the two is exactly opposite.

Sink Current:

Source Current:

Here, it is important to pay attention to the official parameters. The official recommendation is that the current should not exceed 20 mA (for the UNO version). If it is expected to exceed this value, then it will be necessary to connect a driver output circuit.

In Arduino, we typically use "File / Examples / 01.Basics / Blink" as a template, which uses the delay() function as the main method of delay. The characteristic of delay() is to do nothing for a period of time and then continue on after that time has elapsed. If the circuit has few control items, using delay() is not a big problem. However, if there are multiple different I/O applications at the same time, such as INPUT (button) / OUTPUT (LED), problems may arise where the button is skipped and sometimes does not respond because delay() happens to skip the INPUT segment of the program.


int ledPin = 13;             

void setup() {
  pinMode(ledPin, OUTPUT); 
}

void loop() {
  digitalWrite(ledPin, HIGH);
  delay(1000);          
  digitalWrite(ledPin, LOW); 
  delay(1000);       
}

We can use the "File / Examples / 02.Digital / BlinkWithoutDelay" example, which may take some getting used to in terms of thinking. However, it is very helpful in terms of basic logic, especially when working on medium to large-sized projects where a similar approach will be required.

Required Materials:

  1.  Arduino UNO x 1
  2. Resistor: 330 ohm x 1
  3. Breadboard x 1

Circuit

code

Connect the LED to the source current and connect the PIN 12.




const int ledPin = 12;

const long interval = 1000;

int ledState = LOW;


unsigned long previousMillis = 0;


void setup() {
  // put your setup code here, to run once:
  
  pinMode(ledPin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  
 
  unsigned long currentMillis = millis();

  
  if(currentMillis - previousMillis >= interval ){
    
     previousMillis = currentMillis;
  
     ledState == LOW ? ledState = HIGH : ledState = LOW;

     digitalWrite(ledPin,ledState);
  }
}