So I did some searching and couldn't find exactly what I am looking for. I want to be able to generate pwm at a certain duty cycle and frequency. To do this I would like to create a library that I can easily call upon during my current project and all my future projects to come. I am new here and apologize if I am asking a question you guys get on a daily basis (I hate those guys), but I couldn't find my answer.
So the goal is to turn a signal from a wii nunchunck into a pwm signal, with them will output to motor. I understand the math involved, but I am not sure exactly how to package it all together.
Here is what I got:
int pwmPin = 11
int hertz;
int duty;
int timeHigh;
int timeLow;
int totalTime;
void setup ()
{
pinMode (pwmPin, OUTPUT);
}
void loop ()
{
totalTime = 1000000 / hertz;
duty = duty / 100;
timeHigh = totalTime * duty;
timeLow = totalTime - timeHigh;
digitalWrite (pwmPin, LOW);
delayMicroseconds (timeLow);
digitalWrite (pwmPin, HIGH);
delayMicroseconds (timeHigh);
}
Here is what I know is wrong.
duty and hertz never get assigned anything, therefore no other variables are assigned anything. To fix this I want those numbers to be inputed in this manner:
setPWM (duty, hertz)
That would be how I call upon the library.
So how do I do that?
I am ok if you don't want to type a response and you link me somewhere.
Also I am aware that some variables would be truncated. That was intentional. And I also know that I need a header file, but I will do that after I have this working.
I think you have this a bit backwards. The setup and loop functions do not go in a library.
A library defines a class that is instantiated in your sketch. Look at any of the libraries available for the Arduino for examples of how a library is structured and used.
If you want to create a library, you would have a constructor and setPWM methods. The setPWM method could have two reference arguments that defined where to store values.
If this does not make sense to you, I don't think you are ready to be creating libraries.
Ya I was alittle confused. I understand, what needs to be done now. I need to do some more reading. I am more familiar with java, but I will read into C which will help when I try and apply this the arduino.
This approach (using the delay function) will work fine as long as your program isn't doing anything else.
A more general approach is to set up one of the ATmega's timers to do PWM in the background. This is the approach used by the Arduino analogWrite() function.
This library was written to provide low frequency (0.25 to 128 Hz) PWM output for controlling things like electric heaters through a solid state relay. So it is probably not exactly what you need. But it may get you started.
Thanks. The delay approach wont work. I didnt even think about it delaying the rest of my program. I wanted to go thus way to bypass the standard 490hz. I will take a look at ur library and see if i can repurpose it.
Thanks alot
Mike