I want to take a 0.5-4.5V input and turn it into a 1-750hz square wave on a Arduino Atmega 328(There is also code in there that is setting outPin2 low unless there is 2.5V or more but that's not really what I'm concentrated on right now, in theory it should work fine). I don't know why it's not working, I vary the voltage in but it has little to no effect on the very inconsistent square wave (It is flipping out on the oscilloscope, it looks square like but it looks like it is vibrating rapidly on the screen and ranges from a frequency of 62hz to 129hz). Here is my code:
// constants won't change. Used here to set pin numbers:
#include <TimerOne.h>
#define pwmRegister OCR1A // the logical pin, can be set to OCR1B
const int outPin = 9; // the number of the digital pin used to output the frequency
const int inPin = A0; // the number of the analog pin recieving the voltage for the frequecy calculations
const int outPin2 = 3; // the number of the digital pin used to
const int inPin2 = A1; // the number of the analog pin recieving the signal for the ignition switch
int sensorValue = 1;
int sensorValue2 = 1;
long period = 1;
long frequency = 1;
//int prescale[] = {0,1,8,64,256,1024};
void setup()
{
Serial.begin(9600);
// set the digital pins as outputs:
pinMode(outPin, OUTPUT);
pinMode(outPin2, OUTPUT);
Timer1.initialize(period);
}
void loop()
{
// read the voltage going into pin A0
sensorValue = analogRead(inPin);
// map it to the range of the analog out (0.5V to 4.5V represented by their bit equivalents is being converted into 1-750hz) :
frequency = map(sensorValue, 102.4, 921.6, 1, 750);
Timer1.setPeriod(1 / frequency);
Timer1.pwm(outPin, 512, period);
//read the voltage going into pin A1
sensorValue = analogRead(inPin2);
//Sets the output of digitalOut2 low
digitalWrite(outPin2, LOW);
//If there is there is 2.5V or more going into analogInPin2 digitalOut2 will go high
if (sensorValue2 > 512)
{
digitalWrite(outPin2, HIGH);
}
}
Any ideas about what's going wrong or ways to figure it out?