2

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help, is this what you had in mind? Thanks! long interval = 100; // do AnalogRead() 10 times a second, 1000/10 in mS void setup() { // set the analog pin as output: pinMode(analogPin, OUTPUT); // READ Analog data pinMode(pwmPin, OUTPUT); // PWM Pin to Motor } void loop() { currentMillis = millis(); if((currentMillis - previousMillis) > interval) { // save the last time you blinked the LED previousMillis += interval; analogRead() // Read analogdata 10 times a second } // DO PWM code here like analogWrite() to MOSFET pin }
Pretty much you have the hang of it. The key is to avoid using delay() or anything that might delay or loop for an excessive amount of time. You can add more "previousMillis" variables for other actions. For example, if you need to change the PMW value 5 times per second (every 200ms), you could add a "previousPwmMs".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.