Search code examples
c++cmbed

How to not repeat the if statements and allow it to look them up somehow? I am very new, im sure this is basic


I am very new and was wondering if there was a way to make the code look up the if statements rather than having to copy and past them

Also any other tips on how to clean this up is much appreciated, not a serious project just playing around and trying to learn

This code is done on mbed using Nucleo board to get the output

#include "mbed.h" 
#include "../lib/uopmsb/uop_msb_2_0_0.h"
using namespace uop_msb_200;

Buzzer buzz;

DigitalOut greenLED(LED1);
DigitalOut blueLED(LED2);
DigitalOut redLED(LED3);


int main()
 {     while(true)
 {

    greenLED = 1; 
    blueLED = 0;
    redLED = 0;
    if( greenLED == 1 )
 {
 buzz.playTone("C");
 }
 else {
 NULL;
 }
 if( blueLED == 1 )
 {
 buzz.playTone("D");
 }
 else {
 NULL;
 }
 if( redLED == 1 )
 {
 buzz.playTone("G");
 }
 else {
 NULL;
 }
    wait_us(2500000); 

    greenLED = 0;
    blueLED = 1;
    redLED = 0;
    if( greenLED == 1 )
{
 buzz.playTone("C");
 }
 else {
 NULL;
 }
 if( blueLED == 1 )
 {
 buzz.playTone("D");
 }
 else {
 NULL;
 }
 if( redLED == 1 )
 {
 buzz.playTone("G");
 }
 else {
 NULL;
 }
    wait_us(2500000); 

    greenLED = 0;
    blueLED = 0;
    redLED = 1;
    if( greenLED == 1 )
 {
 buzz.playTone("C");
 }
 else {
 NULL;
 }
 if( blueLED == 1 )
 {
 buzz.playTone("D");
 }
 else {
 NULL;
 }
 if( redLED == 1 )
 {
 buzz.playTone("G");
 }
 else {
 NULL;
 }
    wait_us(2500000); 

    greenLED = 0;
    blueLED = 0;
    redLED = 0;
    if( greenLED == 1 )
 {
 buzz.playTone("C");
 }
 else {
 NULL;
 }
 if( blueLED == 1 )
 {
 buzz.playTone("D");
 }
 else {
 NULL;
 }
 if( redLED == 1 )
 {
 buzz.playTone("G");
 }
 else {
 NULL;
 }
  }
   }

Solution

  • you could always make a void function like this before the main function, this will let you call it, run what ever is inside and then return back to the main function.

    void play(){
        if( greenLED == 1 ){
         buzz.playTone("C");
        }
        if( blueLED == 1 ){
         buzz.playTone("D");
        }
        if( redLED == 1 ){
         buzz.playTone("G");
        }
     }
    

    So youll implement it like this, calling the function everytime you want to play a sound.

    Buzzer buzz;
    
        DigitalOut greenLED(LED1);
        DigitalOut blueLED(LED2);
        DigitalOut redLED(LED3);
    
    void play(){
        if( greenLED == 1 ){
         buzz.playTone("C");
        }
        if( blueLED == 1 ){
         buzz.playTone("D");
        }
        if( redLED == 1 ){
         buzz.playTone("G");
        }
     }
    
    
    
    int main(){ 
        while(true){
    
        greenLED = 1; 
        blueLED = 0;
        redLED = 0;
    
        play();
    
        wait_us(2500000);
    
        greenLED = 0; 
        blueLED = 1;
        redLED = 0;
    
        play();
    
        wait_us(2500000);  
    

    And then itterate turning your led's on and off etc.