使用Arduino开发板自制波形发生器

参考链接

使用Arduino制作多种波形发生器

制作教程

PWM教程

中断

#include <PWM.h>
#include <LiquidCrystal.h>
const int rs=14, en=15, d4=10, d5=11, d6=8, d7=7;
LiquidCrystal lcd(rs, en, 16,d4, d5, d6, d7);//Mention the pin number for LCD 1602 connection

int Encoder_OutputA = 18;
int Encoder_OutputB = 19;
int Encoder_Switch =17;
int Previous_Output;
int multiplier = 1;

double angle =0 ;
double increment =0.2;
const int signal_pin = 9;
const int Sine_Pin = 5;
int32_t frequency;//frequency to be set
int32_t lower_level_freq = 1;//lowest possible freq value is 1Hz   
int32_t upper_level_freq = 10000;//Maximum possible freq is 100KHz


void setup() {
  lcd.begin(16,2);
  lcd.print("Signal Generator");//Intro Message line1
  lcd.setCursor(0,1);
  lcd.print("Circuit digital");// Message line2
  delay(2000);
  lcd.clear();
  lcd.print("Freq:00000Hz");
  lcd.setCursor(0,1);
  lcd.print("Inc. by: 1Hz");
  Serial.begin(9600);
  InitTimersSafe();//Initialize timers without disturbing timer 0
  pinMode(Encoder_OutputA,INPUT);
  pinMode(Encoder_OutputB,INPUT);
  pinMode(Encoder_Switch,INPUT);
  Previous_Output=digitalRead(Encoder_OutputA);//Read the inital value of Output A
  attachInterrupt(0,generate_sine,CHANGE);
}
void loop() {
  if (digitalRead(Encoder_OutputA)!=Previous_Output)
  {
    if (digitalRead(Encoder_OutputB)!=Previous_Output)
    {
      frequency = frequency + multiplier;
      Serial.println(frequency);
      SetPinFrequencySafe(signal_pin,frequency);
      pwmWriteHR(signal_pin,32768);//Set duty cycle to 50% by default -> for 16-bit 65536/2 = 32768
     //  pwmWrite(signal_pin,128);//Set duty 50%(0-255)
      lcd.setCursor(0, 0);
      lcd.print("Freq:     Hz");
      lcd.setCursor(5, 0);
      lcd.print(frequency);
      
      }
    else
    {
      frequency = frequency - multiplier;
      Serial.println(frequency);
      SetPinFrequencySafe(signal_pin,frequency);
      pwmWriteHR(signal_pin, 32768);
      // pwmWrite(signal_pin,128);
      lcd.setCursor(0, 0);
      lcd.print("Freq:     Hz");
      lcd.setCursor(5, 0);
      lcd.print(frequency);
      }
    }
    if(digitalRead(Encoder_Switch)==0)
    {
      multiplier = multiplier * 10;
      if(multiplier>1000)
         multiplier=1;
      Serial.println(multiplier);
      lcd.setCursor(0,1);
      lcd.print("Cng. by:     ");
      lcd.setCursor(8,1);
      lcd.print(multiplier);
      delay(500);
      while(digitalRead(Encoder_Switch)==0);
      }
     Previous_Output = digitalRead(Encoder_OutputA);  
}
    
void generate_sine()
{
  double sineValue = sin(angle);
   sineValue *= 255;
   int plot = map(sineValue, -255, +255, 0, 255);
   Serial.println(plot);
   analogWrite(Sine_Pin,plot);
   angle += increment; 

   if (angle > 180)
   angle =0;
  
}

  

posted @ 2022-01-20 14:34  xiaoberber  阅读(548)  评论(0编辑  收藏  举报