2
votes

I have a general question for the Arduino, how can I read a sensor value using AnalogRead() a certain number of times a second. Say 10 times a second, and also continously output PWM to a motor.

If I try to delay in my loop() it affects the PWM I'm using with AnalogWrite() to the motor. Is there a way to do both?

Also, for the AnalogRead() I'd like to control sample frequency, like 10 times a second or 20 times a second how can I do that?

Thanks a bunch!

1

1 Answers

3
votes

You want to review the "blink without delay" example in the Arduino IDE.

The short answer, which you will understand better after reading the example sketch, is that you perform the analogRead() call based on the difference between the most recent and previous return values from millis(), and you perform any PWM changes as they are needed. Since analogRead() returns very quickly, they won't interfere with the PWM operations provided you don't use delay() anywhere.

Keep in mind that the return value from millis() is unsigned, so the difference between two successive return values is always positive, provided you are using unsigned variables to store the return value from millis(). Since there are 1,000 milliseconds in a second, whenever the difference between two successive calls to millis() is greater than 100, you'd take another reading. To insure you stay close to 10 values per second, increment the "previous" millisecond value by 100, rather than replacing the "previous" value with the actual reading.