# LAB: Pulse Width Modulation (PWM)

## **จุดประสงค์**&#x20;

1. &#x20;เข้าใจหลักการทำงานของ PWM
2. สามารถสร้างกราฟสัญญาณ PWM โดยใช้ Arduino board ได้

## LAB: การสร้างสัญญาณ PWM

การทดลองปรับค่า potentiometer จนได้ duty cycle 50% บันทึกผลกราฟ และอ่านค่าความถี่(Hz), แรงดัน(V) จากกราฟที่ได้

### อุปกรณ์ทดลอง

<table><thead><tr><th width="231.69613718078722">Component </th><th>Quantity</th></tr></thead><tbody><tr><td>Arduino mega2560</td><td>1</td></tr><tr><td>myDAQ</td><td>1</td></tr><tr><td>Potentiometer</td><td>1</td></tr></tbody></table>

![](https://1856353139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MClo3nC-1US0rbK8Qau%2Fuploads%2F38scY8QJZP6HyPj43dIE%2Fsfaf.png?alt=media\&token=a3e222b5-9645-4f93-8011-032f9cc93939)

### โปรแกรม

1. Arduino IDE
2. โปรแกรม NI ELVISSmx

### Schematic

![](https://1856353139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MClo3nC-1US0rbK8Qau%2Fuploads%2FSzZBWPzRwuKlICqdkqQl%2FOSC_potentiometer_schem.png?alt=media\&token=2fe78008-31ac-43f0-b44a-a73d3d2962c5)

### Circuit Diagram

![](https://1856353139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MClo3nC-1US0rbK8Qau%2Fuploads%2FSrQ98oZ8drgYm8NQTR3D%2Fguiu.png?alt=media\&token=a30b97eb-626a-4a5d-9655-848677532b56)

### Code

```arduino
//Arduino Mage 2560 read potentiometer and write LED
int sensorPin = A8;    // connect this pin to potentiometer
int ledPin = 2;      // connect this pin to external LED
int sensorValue = 0;  // variable to store the value coming from the sensor

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin, OUTPUT); // set this pin to output
  Serial.begin(9600); // start serial monitor
}


void loop() {
  // read the value from the sensor:
  sensorValue = analogRead(sensorPin);
  sensorValue = map(sensorValue, 0,1023,0,255);
  // turn the ledPin on
  analogWrite(ledPin, sensorValue);
  Serial.println(sensorValue); // bright LED with read value
  
}
```

### บันทึกผลการทดลอง

1. บันทึกภาพวงจร ผลกราฟ, serial monitor และอธิบายการทดลองลง template ที่ได้รับมอบหมาย
