analog in serial out


SUBMITTED BY: Guest

DATE: Aug. 19, 2014, 3:13 p.m.

FORMAT: C++

SIZE: 1.9 kB

HITS: 834

  1. /*
  2. Analog input, analog output, serial output
  3. Reads an analog input pin, maps the result to a range from 0 to 255
  4. and uses the result to set the pulsewidth modulation (PWM) of an output pin.
  5. Also prints the results to the serial monitor.
  6. The circuit:
  7. * potentiometer connected to analog pin 0.
  8. Center pin of the potentiometer goes to the analog pin.
  9. side pins of the potentiometer go to +5V and ground
  10. * LED connected from digital pin 9 to ground
  11. created 29 Dec. 2008
  12. modified 9 Apr 2012
  13. by Tom Igoe
  14. This example code is in the public domain.
  15. */
  16. // These constants won't change. They're used to give names
  17. // to the pins used:
  18. const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
  19. const int analogOutPin = 9; // Analog output pin that the LED is attached to
  20. int sensorValue = 0; // value read from the pot
  21. int outputValue = 0; // value output to the PWM (analog out)
  22. void setup() {
  23. // initialize serial communications at 9600 bps:
  24. Serial.begin(9600);
  25. }
  26. void loop() {
  27. // read the analog in value:
  28. sensorValue = analogRead(analogInPin);
  29. // map it to the range of the analog out:
  30. outputValue = map(sensorValue, 0, 1023, 0, 255);
  31. // change the analog out value:
  32. analogWrite(analogOutPin, outputValue);
  33. // print the results to the serial monitor:
  34. Serial.print("sensor = " );
  35. Serial.print(sensorValue);
  36. Serial.print("\t output = ");
  37. Serial.println(outputValue);
  38. // wait 2 milliseconds before the next loop
  39. // for the analog-to-digital converter to settle
  40. // after the last reading:
  41. delay(2);
  42. }

comments powered by Disqus