Devices & Components
ATmega328
Project description
Code
understandig_PWM.ino
c_cpp
This sketch was meant to give you a better understanding what exactly is going to happen when you are using the analogWrite command.
1/* 2 Understanding PWM: 3 Requirement: 4 any Arduino that contains an ATmega328, even a barebone would do. 5 External hardware: 6 7 n nnn ooo n nnn eee 8 nn n o o nn n e e 9 n n o o n n eeeee 10 n n o o n n e 11 n n ooo n n eee 12 13 PWM out: Pin-9 (controlled by TIMER-1) 14 Option: Connect anode of an LED to pin-9, 15 cathode of LED to GND (don't forget the resistor). 16 Start the Serial plotter and set the baud rate to 115200. 17 Since 1.6.7 the IDE supports drawing of multiples graphs at once. 18 The area below the blue and the red graph will always be the same. 19 The Serial Plotter replaces a dual beam oscilloscope. 20 You can also watch the 20 minutes video of Paul McWhorter 21 (https://www.youtube.com/watch?v=YfV-vYT3yfQ) 22 who is using a GW Instek GOS-620FG analogue oscilloscope 23 to demonstrate how PWM works, or any other of the 7 million links 24 Google shows for PWM tutorial. 25 Side note: as soon as the pwm value exceeds 255 it goes back to 0. 26 No special treatment is required. 27*/ 28 29void setup() { 30 /* 31 all this stuff is just to make sure the legend 32 next to the blue and red bar will show up properly. 33 In case it shows some garbage just restart the plotter. 34 */ 35 delay(700); 36 Serial.flush(); 37 Serial.begin(115200); 38 delay(700); 39 Serial.flush(); 40 Serial.println("PWM_signal mean_value"); 41} 42 43byte pwm; 44 45void loop() { 46 // Serial plotter always shows 500 samples: 47 const int N = 500; 48 byte a[N]; 49 analogWrite(9, pwm); 50 // to synchronize the plotter TIMER1 has to 51 // start from zero to give a stable picture 52 TCNT1 = 0; 53 // read 500 samples fast: 54 for (int i = 0; i < N; i++) { 55 // trick to read pin-9: 56 // sorry but this won't work: a[i] = digitalRead(9); 57 a[i] = PINB & 2; // result always 0 or 2 58 // with 21 you see exactly four pulses in the plot 59 delayMicroseconds(21); 60 } 61 // calculate the mean value: 62 float mean = 5.0 * pwm / 255; 63 String s = " " + String(mean); 64 // plot the samples (2 * 2.5 = 5 volts) and mean: 65 for (int i = 0; i < N; i++) { 66 Serial.print(a[i] * 2.5); 67 Serial.println(s); 68 } 69 delay(400); 70 pwm++; 71} 72
Downloadable files
no_wires_z6TdlhDPHJ.png
no_wires_z6TdlhDPHJ.png

no_wires_z6TdlhDPHJ.png
no_wires_z6TdlhDPHJ.png

Comments
Only logged in users can leave comments