Hello guys, hope you're well.
I need some help on a question that I've found using arduino, because I´m new on this.
I've created a code to generate a sin function inside the for loop, and it works very well, the code is the following one:
"unsigned long amp = 500;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
for(int i=0; i<360; i++){
Serial.println((amp/1)*(sin(i * (PI/180))));
}
}"
I'm trying to print the function in a PWM output pin and than passes it through a diode and get and input of the signal on an analog pin. The trouble that I'm having is that I can't use the function that I've created out of the for loop, and I can't find a way to print this and get the plotter os the analog input (that passes through the diode) inside the for loop. Hope you guys can help me.
A PWM pin uses the analogWrite() function which uses a value between 0 and 255. The sin() function returns a value between -1.0 and 1.0. When you multiply that by 500 you get a value that ranges from -500.0 to 500.0. To get that on a PWM pin you will have to scale it:
float val = 500.0 * sin(i * (PI/180));
analogWrite(PWMPin, (val+500.0) * 255.0) / 1000.0); // Scale -500..500 to 0..255
Note that the PWM signal will be 0V or +5V at any given time. You can smooth the pulses into an analog voltage with a low-pass filter. When you read the voltage to an analog input pin and read it with analogRead() you will get a value between 0 and 1023. To turn that back into 'val':
int reading = analogRead(InputPin);
val = (reading * 1000.0) / 1024.0 - 500.0; // scale 0..1023 to -500..500