Arduino C

English

YN AROS AM GYFIEITHIAD - DYCHWELWCH YN FUAN

Cyflwyniad i Raglennu yn Arduino C

Rydym wedi addasu'r deunydd a grëwyd ar gyfer ein Clwb Roboteg i unrhyw un allu ei ddefnyddio gartref neu yn yr ysgol.

Mae pob un o'r sesiynau isod yn cynnwys gwers fideo gan un o'n staff a set o ymarferion er mwyn asesu eich dealltwriaeth. Gan fod y dudalen hon ar gyfer dysgwyr annibynnol, mae'r atebion wedi'u cynnwys.

Rydym yn argymell bod dysgwyr yn ymweld â'n Cyfres Micro:Bit Ar-lein yn gyntaf i gael cyflwyniad i raglennu, a'n Cyfres Electroneg Ar-lein i ddeall mwy am y caledwedd a'r feddalwedd a ddefnyddir.

Dewiswch bennawd sesiwn i ddechrau arni.

Ymarferion:

Bydd angen i chi gopïo ein 'Valiant' Robot Tinkercad circuit i'ch cyfrif Tinkercad ar gyfer yr ymarferion hyn

I gael eich atgoffa o sut i fewngofnodi a defnyddio Tinkercad, gweler Sesiwn Un o'n Cyfres Electroneg Ar-lein

Mae'r heriau hyn yn golygu dechrau rhaglennu robot 'Valiant'.

Dylai pob dysgwr ddechrau ar lefel efydd a gweithio eu ffordd i fyny cyn belled ag y bo modd.

Cliciwch ar bennawd pob her i'w ehangu.



Pwysig: Gwnewch yn siŵr bod panel cod ar Tinkercad wedi'i osod i Text, fel y dangosir yma:

Sgrinlun o banel cod Tinkercad gyda'r bocs cwymp chwith ar y brig yn dangos 'Text'.

Y rhaglen a ddarperir yw rhaglen Arduino ddiofyn Tinkercad sy'n goleuo LED yr Arduino ac yn ei ddifodd.

Dilëwch gynnwys y void setup() a'r void loop() fel bod eich cod cychwyn yn edrych fel hyn:

              
    //C++ code
    //
    void setup ()
    {
      
    }

    void loop ()
    {

    }
              
            
  1. Diffiniwch pin 13 (lle mae'r LED wedi'i gysylltu) fel pin allbwn yn y void setup() (ar ddechrau).


    • Wrth ddefnyddio rhaglennu bloc, mae llawer o'r gosodiad wedi ei gynnwys yn awtomatig ar ein cyfer. Nawr mae'n rhaid i ni ysgrifennu hwn ein hunain.

    • Rydym yn defnyddio pinMode() i ganfod pin sy'n cael ei ddefnyddio a gweld a yw'n INPUT neu'n OUTPUT.

    • Y tu mewn i gromfachau pinMode() mae angen i ni ychwanegu rhif y pin a'i fod yn OUTPUT.

    • Peidiwch ag anghofio'r hanner colon (;) ar ddiwedd y cyfarwyddyd.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
        //C++ code
        //
        void setup ()
        {
          pinMode(13, OUTPUT);
        }
    
        void loop ()
        {
    
        }
                        
                      

  2. Y tu mewn i'r void loop() (dolen am byth) ysgrifennwch y cod i oleuo'r LED hwn a'i ddiffodd.

    Awgrym: Bydd angen i chi ychwanegu delay() o 100ms rhwng newidiadau golau er mwyn eu gweld yn yr efelychydd.


    • Rydym yn defnyddio'r LED fel allbwn digidol (golau ymlaen neu'n diffodd) ar gyfer yr ymarfer hwn.

    • Defnyddiwch gyfarwyddiadau digitalWrite() i ddweud wrth gydran ddigidol am droi ymlaen neu ddiffodd.

    • Y tu mewn i gromfachau'r gorchymyn digitalWrite() mae angen i ni gynnwys y pin rydym ni'n ei newid ac yna HIGH neu LOW.

    • Cofiwch, wrth godio, rydym ni'n defnyddio HIGH i roi rhywbeth i fynd LOW i'w ddiffodd.

    • Mae'r cyfarwyddyd delay() yn gwneud i'r rhaglen aros am y cyfnod o amser a nodir y tu mewn i'r cromfachau - wedi'i fesur mewn milieiliadau.

    • Cofiwch, mae'r void loop() yn gweithio'r un fath â dolen am byth.

    • Mae angen i bob cyfarwyddyd/llinell orchymyn ddod i ben gyda hanner colon (;) neu ni fydd y rhaglen yn gweithio.

    • Gallwch ddefnyddio'r efelychydd i wneud yn siŵr bod eich cod yn gweithio - dylai'r LED glas yn y gylched fflachio ymlaen ac i ffwrdd yn gyflym.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
        //C++ code
        //
        void setup ()
        {
          pinMode(13, OUTPUT);
        }
    
        void loop ()
        {
          digitalWrite(13, HIGH);
          delay(100);
          digitalWrite(13, LOW);
          delay(100);
        }
                        
                      




  1. Ysgrifennwch y cyfarwyddyd sydd ei angen i roi gwybod i'n rhaglen fod gennym ni LDR/Photoresistor wedi'i gysylltu â phin A0.

    Awgrym: Mae'r LDR/Photoresistor yn ddyfais mewnbwn analog.


    • Mae angen iddo fynd i mewn i'r void setup().

    • Mae'n defnyddio'r gorchymyn pinMode() fel yr eglurir yn yr ymarferion Lefel Efydd.

    • Yn yr achos hwn, y wybodaeth allweddol sydd ei hangen yw bod y gydran yn defnyddio pin A0 a'i bod yn INPUT.

    • Does dim angen i'r gosodiad wybod a yw cydran yn ddigidol neu'n analog - bydd y wybodaeth hon yn ddefnyddiol ar ôl i ni ddechrau rhaglennu'r gwrthydd golau-ddibynnol (LDR)/'Photoresistor'.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
        //C++ code
        //
        void setup ()
        {
          pinMode(13, OUTPUT);
          pinMode(A0, INPUT);
        }
    
        void loop ()
        {
          digitalWrite(13, HIGH);
          delay(100);
          digitalWrite(13, LOW);
          delay(100);
        }
                        
                      

  2. Yn yr un modd â'n pinnau, i ddefnyddio'r monitor cyfresol yn ein rhaglen, mae angen i ni ei gynnwys yn y gosodiad.

    Awgrym: Dangoswyd sut mae sefydlu'r monitor cyfresol yn y wers fideo.


    • Bydd angen i chi ddefnyddio cyfarwyddyd Serial.begin() () y tu mewn i'r void setup().

    • Y cyflymder cyfathrebu yw'r gwerth y tu mewn i'r cromfachau ar gyfer y gorchymyn cyfresol - rydym yn argymell eich bod yn defnyddio 9600 fel gwerth diofyn.

    • Sylwer bod y cyfarwyddyd hwn ychydig yn wahanol gan ei fod yn dechrau gyda phriflythyren.

    • Nid yw hyn yn agor y monitor cyfresol yn awtomatig i chi, ond mae'n rhoi gwybod i'r rhaglen y byddwn yn ei ddefnyddio.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
        //C++ code
        //
        void setup ()
        {
          pinMode(13, OUTPUT);
          pinMode(A0, INPUT);
          Serial.begin(9600);
        }
    
        void loop ()
        {
          digitalWrite(13, HIGH);
          delay(100);
          digitalWrite(13, LOW);
          delay(100);
        }                  
                        
                      

  3. Creu newidyn o'r enw 'ldrValue' i storio gwerth y darlleniad LDR a'i osod i 0 wrth ddechrau.

    Awgrym: Mae'r gwerthoedd hyn yn gyfanrifau (rhifau cyfan). Mae hyn yn golygu bod angen i ni ddweud wrth y rhaglen fod hwn yn newidyn gyda math int.


    Pwysig: Mae'r lle y caiff newidyn ei greu yn y rhaglen yn penderfynu ble gellir ei ddefnyddio.

    Ar gyfer y pwnc hwn, byddwn yn defnyddio Newidynnau Drwy'r Cyfan. Mae'r rhain yn newidynnau rydyn ni'n eu diffinio ar ddechrau rhaglen, cyn y void setup() hyd yn oed. Mae hyn yn golygu y gallwn wedyn eu defnyddio mewn unrhyw ran a phob rhan o'r rhaglen.

    Pe byddech chi'n creu newidyn y tu mewn i ddolen/swyddogaeth, dim ond y tu mewn i'r un ddolen/swyddogaeth honno y byddai'n hygyrch ac nid yn unrhyw ran arall o'r rhaglen. Byddai hyn yn cael ei alw'n Newidyn Lleol. Cofiwch, mae hyn yn golygu y bydd y newidyn yn cael ei ail-greu bob tro y bydd y ddolen/swyddogaeth y mae wedi ei osod ynddi yn rhedeg.


    • Mae rhai ieithoedd rhaglennu, fel Arduino C, angen i ni ddweud wrtho pa fath o newidyn ydyw. Dim ond wrth greu'r newidyn y mae angen i chi gynnwys math y newidyn, nid wrth ei ddefnyddio.

    • Mae hwn yn newidyn drwy'r cyfan ac felly mae angen ei greu ar ddechrau'r rhaglen.

    • Cyflwynwyd yr arfer da o osod newidynnau i 0 trwy gydol ein pynciau Micro:Bit ac Electroneg i'ch helpu i gofio gwneud hynny mewn ieithoedd seiliedig ar destun.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
        //C++ code
        //
        int ldrValue = 0;
    
        void setup ()
        {
          pinMode(13, OUTPUT);
          pinMode(A0, INPUT);
          Serial.begin(9600);
        }
    
        void loop ()
        {
          digitalWrite(13, HIGH);
          delay(100);
          digitalWrite(13, LOW);
          delay(100);
        }
                        
                      

  4. Y tu mewn i'r void loop(), gwnewch yn siŵr bod eich newidyn gwrthydd golau-ddibynnol newydd (LDR) yn cyfateb i ddarlleniad y synhwyrydd LDR. Yna bydd y rhaglen yn argraffu gwerth y newidyn hwn i'r monitor cyfresol.

    Awgrym: Mae'r LDR yn fewnbwn analog ac mae wedi'i gysylltu â phin A0.


    • Mae rhaglenni Arduino yn 'darllen' mewnbynnau ac yn 'ysgrifennu' allbynnau.

    • Defnyddiwch gyfarwyddyd analogRead() gyda'r pin a nodir tu mewn i'w gromfachau.

    • Mae gorchymyn Serial.print() yn dweud wrth y rhaglen am argraffu beth bynnag sydd o fewn ei gromfachau ar linell newydd y monitor cyfresol.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
        //C++ code
        //
        int ldrValue = 0;
    
        void setup ()
        {
          pinMode(13, OUTPUT);
          pinMode(A0, INPUT);
          Serial.begin(9600);
        }
    
        void loop ()
        {
          digitalWrite(13, HIGH);
          delay(100);
          digitalWrite(13, LOW);
          delay(100);
          ldrValue = analogRead(A0);
          Serial.println(ldrValue);
        }
                        
                      



Mae dadfygiwr wedi ei adeiladu i mewn i olygydd cod Tinkercad. Mae hyn yn rhoi gwybod i ni pan fydd gwall yn y cod a'r math o wall. Mae'n rhedeg bob tro y byddwn yn dechrau'r efelychiad. Yn yr ymarfer hwn byddwn yn cyflwyno gwallau i'n rhaglen er mwyn ein helpu i'w cyfateb i'r negeseuon gwall.

Newidiwch eich void setup() i gyd-fynd â phob un o'r enghreifftiau isod er mwyn gweld y neges gwall a gynhyrchir.

Awgrym: gall y rhifau ar ddechrau'r negeseuon gwall fod yn wahanol gan eu bod yn cyfeirio at rifau llinell yn y cod sy'n dibynnu ar eich bylchiad.

1. Colli '}':

                
    void setup ()
    {
      pinMode(13, OUTPUT);
      pinMode(A0, INPUT);
      Serial.begin(9600);
    
    
    void loop ()

2. Colli '{':

                
    void setup ()
    
      pinMode(13, OUTPUT);
      pinMode(A0, INPUT);
      Serial.begin(9600);
    }
               
              

3. Colli ';':

                
    void setup ()
    {
      pinMode(13, OUTPUT);
      pinMode(A0, INPUT)
      Serial.begin(9600);
    }
               
              

4. Colli '()':

                
    void setup 
    {
      pinMode(13, OUTPUT);
      pinMode(A0, INPUT);
      Serial.begin(9600);
    }
               
              

5. Camgymeriad Sillafu:

                
    void setup ()
    {
      pinMoed(13, OUTPUT);
      pinMode(A0, INPUT);
      Serial.begin(9600);
    }
               
              

6. Colli ',':

                
    void setup ()
    {
      pinMode(13 OUTPUT);
      pinMode(A0, INPUT);
      Serial.begin(9600);
    }
               
              


  1. 
        In function 'void setup()':
        13:1: error: a function-definition is not allowed here before '{' token   
        20:1: error: expected '}' at end of input
                        

  2. 
        7:3: error: expected initializer before 'pinMode'
        8:10: error: expected constructor, destructor, or type conversion before '(' token    
        9:3: error: 'Serial' does not name a type
        10:1: error: expected declaration before '}' token
                        

  3. 
          In function 'void setup()':
        9:3: error: expected ';' before 'Serial'    
                        

  4. 
        5:6: error: variable or field 'setup' declared void
        7:22: error: expected '}' before ';' token
        8:10: error: expected constructor, destructor, or type conversion before '(' token    
        9:3: error: 'Serial' does not name a type
        10:1: error: expected declaration before '}' token
                        

  5. 
          In function 'void setup()':
        7:3: error: 'pinMoed' was not declared in this scope    
        7:3: note: suggested alternative: 'pinMode'
                        

  6. 
        1:0:
          In function 'void setup()':
        44:16: error: expected ')' before numeric constant
    
    
        7:14: note: in expansion of macro 'OUTPUT'
        7:20: error: too few arguments to function 'void pinMode(uint8_t, uint8_t)'    
        1:0:
        134:6: note: declared here
                        




Ymarferion:

Mae'r ymarferion hyn yn parhau i ddefnyddio'r rhaglen a ddatblygwyd yn Sesiwn Un.

Dylai pob dysgwr ddechrau ar lefel efydd a gweithio eu ffordd i fyny cyn belled ag y bo modd.

Cliciwch ar bennawd pob her i'w ehangu.



  1. Ar gyfer yr ymarfer hwn, byddwn yn newid yr hyn y mae'r bwlb LED yn ei wneud felly mae angen i ni gael gwared â'r cyfarwyddiadau sy'n gwneud iddo fflachio.

    Awgrym: Gan ein bod yn dal i ddefnyddio'r LED, peidiwch â thynnu gosodiad pinMode.


    • Dim ond y llinellau a grëwyd yng ngham 2 Lefel Efydd yn Sesiwn Un y mae angen eu dileu.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(13, OUTPUT);
        pinMode(A0, INPUT);
        Serial.begin(9600);
      }
    
      void loop ()
      {
        ldrValue = analogRead(A0);
        Serial.println(ldrValue);
      }
                        
                      

  2. Crëwch newidyn math cyfanrif newydd o'r enw blueLED a'i osod i 13 (rhif y pin y mae wedi'i gysylltu iddo).

    Awgrym: Os gwnaethoch chi gwblhau'r ymarfer estyniad cyntaf yn llwyddiannus yn Sesiwn Un, cewch hepgor y cam hwn.


    • Mae hwn yn newidyn drwy'r cyfan felly mae angen ei sefydlu ar ddechrau'r rhaglen cyn y void setup().

    • Sicrhewch fod y newidyn newydd hwn yn hafal i 13.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(13, OUTPUT);
        pinMode(A0, INPUT);
        Serial.begin(9600);
      }
    
      void loop ()
      {
        ldrValue = analogRead(A0);
        Serial.println(ldrValue);
      }
                        
                      

  3. Crëwch newidyn math cyfanrif newydd o'r enw LDR a gosodwch hwn i A0.

    Awgrym: Er ei bod yn ymddangos bod A0 yn gymysgedd o nodau a llythrennau, mae'n rhif pin ac felly caiff ei gydnabod fel cyfanrif.


    • Mae hwn yn newidyn drwy'r cyfan felly mae angen ei sefydlu ar ddechrau'r rhaglen cyn y void setup().

    • Sicrhewch fod y newidyn newydd hwn yn hafal i A0.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(13, OUTPUT);
        pinMode(A0, INPUT);
        Serial.begin(9600);
      }
    
      void loop ()
      {
        ldrValue = analogRead(A0);
        Serial.println(ldrValue);
      }
                        
                      

  4. Nawr, rhowch y newidyn cywir ym mhob lleoliad lle caiff y pinnau eu cofnodi fel rhifau (13 ac A0) yn y rhaglen. Mae hyn yn golygu, os newidir y pin y mae cydran wedi'i chysylltu iddo, dim ond mewn un lle y mae angen addasu'r cod - sef y lle caiff y newidyn ei greu.


    • Bydd angen galw newidyn 'blueLED' unwaith yn y void setup().

    • Mae angen galw newidyn LDR unwaith yn y void setup() ac unwaith yn y void loop().

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
      }
                        
                      

  5. Ychwanegwch ddatganiad-os i'ch void loop() sy'n rhoi'r bwlb LED ymlaen pan fydd y darlleniad LDR yn llai na 160.

    Awgrym: Os aethoch chi i'r afael â'r ymarferion estyniad yn Sesiwn Un, dim ond yr amod ar gyfer y datganiad-os mae angen i chi ei newid.


    • Cofiwch ddefnyddio ein newidynnau newydd wrth alw'r pinnau.

    • Bydd angen arall-datganiad i ddiffodd yr LED pan fydd y cyflwr yn ffug.

    • Sicrhewch fod eich cyfarwyddiadau o fewn cromfachau cyrliog {} y datganiad.

    • Rydym yn defnyddio'r LED fel allbwn digidol. Mae hyn yn golygu y bydd angen i ni ddefnyddio gorchmynion digitalWrite gyda gwerthoedd HIGH a LOW.

    • Peidiwch ag anghofio rhedeg yr efelychiad er mwyn profi eich rhaglen.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
      } 
                        
                      




  1. Rydyn ni nawr am ddechrau rhaglennu ein servo. I wneud hyn, mae angen i ni ddweud wrth y rhaglen am ddefnyddio llyfrgell servo - yn debyg i'r cam o ychwanegu'r estyniad servo i ddewislen bloc y Micro:Bit.

    Awgrym: Enw'r llyfrgell/estyniad yw Servo.h


    • Rydym yn defnyddio'r gorchymyn #include i ychwanegu llyfrgell/estyniad.

    • Mae enw'r llyfrgell/estyniad yn cael ei roi o fewn cromfachau onglog < >.

    • I gael mynediad i'r llyfrgell/estyniad trwy gydol ein rhaglen (drwy'r cyfan), mae angen i ni wneud hyn cyn ein void setup().

    • Nid oes gan gyfarwyddyd #include hanner colon (;) ar y diwedd.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
    
      #include <Servo.h>
    
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
      } 
                        
                      

  2. Ychwanegwch servo i'ch rhaglen o'r enw myServo gan ddefnyddio'r gorchmynion llyfrgell newydd.

    Awgrym: Gall llyfrgelloedd ychwanegol fod â gwahanol ffyrdd o gynhyrchu newidynnau. Yn yr achos hwn, defnyddiwn y gorchymyn Servo variableName; i ychwanegu servo.


    • Mae hwn yn newidyn drwy'r cyfan y mae angen ei osod ar ddechrau'r rhaglen.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
    
      #include <Servo.h>
      Servo myServo;
    
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
      } 
                        
                      

  3. Crëwch newidyn math cyfanrif drwy'r cyfan newydd o'r enw servoPin a'i osod i 12. Defnyddiwch y newidyn newydd hwn yn y void setup() i ddweud wrth y rhaglen pa bin mae myServo wedi'i gysylltu iddo.

    Awgrym: Mae'r gorchymyn llyfrgell Servo ar gyfer adnabod pinnau yn wahanol eto. Bydd angen i chi ddefnyddio strwythur gorchymynservoName.attach(pin);


    • Gosodwch y newidyn servoPin newydd yn yr un ffordd ag y gwnaethom ar gyfer newidynnau LDR a blueLED.

    • Gan ddefnyddio strwythur gorchymyn servoName.attach(pin); rhowch myServo yn lle servoName a servoPin yn lle'r pin.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
    
      #include <Servo.h>
      Servo myServo;
    
      int servoPin = 12;
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
        myServo.attach(servoPin);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
      }
                        
                      

  4. Y tu mewn i'r void loop(), ysgrifennwch raglen gan ddefnyddio cyfarwyddiadau myServo.write(angle); i wneud i'r servo symud rhwng onglau 0°, 90°, 180°, and back to 90°. Cynhwyswch un eiliad o saib ar ôl pob symudiad.

    Awgrym: Mae cyfarwyddyd delay(); yn defnyddio milieiliadau ar gyfer y gwerth y tu mewn i'r cromfachau. 1000 milieiliadau = 1 eiliad.


    • Mae'r oedi 1000ms yn angenrheidiol i roi amser i'r servo gwblhau symudiad cyn dechrau'r nesaf.

    • Does dim angen symbol ° ar werth yr ongl yn y gorchymyn.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
    
      #include <Servo.h>
      Servo myServo;
    
      int servoPin = 12;
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
        myServo.attach(servoPin);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
        myServo.write(0);
        delay(1000);
        myServo.write(90);
        delay(1000);
        myServo.write(180);
        delay(1000);
        myServo.write(90);
        delay(1000);
      }
                          
                        
                      




  1. Crëwch newidyn drwy'r cyfan newydd o'r enw piezo neu piezoPin i storio gwerth y pin ar gyfer y swnyn piezo.

    Awgrym: Bydd angen i chi edrych ar y gylched i wybod pa bin yw hwn.


    • Cofiwch, ystyrir bod pob pin rhaglenadwy, gan gynnwys y rhai sydd â'r llythyren A yn eu henwau, yn rhifau/cyfanrifau

    • Y pin rhaglenadwy ar gyfer y swnyn piezo yw'r un sydd wedi ei gysylltu i'w derfynell bositif.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
    
      #include <Servo.h>
      Servo myServo;
    
      int piezo = A3;
      int servoPin = 12;
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
        myServo.attach(servoPin);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
        myServo.write(0);
        delay(1000);
        myServo.write(90);
        delay(1000);
        myServo.write(180);
        delay(1000);
        myServo.write(90);
        delay(1000);
      }
                        
                      

  2. Gan ddefnyddio ein newidyn piezo newydd, sefydlwch y pinMode() ar gyfer y swnyn y tu mewn i'r void setup().

    Awgrym: Bydd angen i chi ystyried a yw'r swnyn yn fewnbwn neu'n allbwn.


    • Mae'r piezo buzzer yn ddyfais allbwn analog.

    • Rhowch sylw i ba ddisgrifiadau y mae angen eu hysgrifennu mewn priflythrennau.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
    
      #include <Servo.h>
      Servo myServo;
    
      int piezo = A3;
      int servoPin = 12;
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
        myServo.attach(servoPin);
        pinMode(piezo, OUTPUT);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
        myServo.write(0);
        delay(1000);
        myServo.write(90);
        delay(1000);
        myServo.write(180);
        delay(1000);
        myServo.write(90);
        delay(1000);
      }
                        
                      

  3. Rhaglennwch eich swnyn i seinio am 0.5 eiliad yn ôl y darlleniad LDR. Yr amodau yw:

    • Os yw lefel y golau yn llai na 60, chwarae amledd tôn 65.
    • Arall, os yw lefel y golau yn llai na 100, chwarae amledd tôn 82.
    • Arall, os yw lefel y golau yn llai na 160, chwarae amledd tôn 98.
    • Arall, os yw lefel y golau yn llai na 220, chwarae amledd tôn 131.
    • Arall, os yw lefel y golau yn llai na 280, chwarae amledd tôn 165.
    • Arall, os yw lefel y golau yn llai na 340, chwarae amledd tôn 196.
    • Arall, os yw lefel y golau yn llai na 400, chwarae amledd tôn 262.
    • Arall, os yw lefel y golau yn llai na 460, chwarae amledd tôn 330.
    • Arall, os yw lefel y golau yn llai na 520, chwarae amledd tôn 392.
    • Arall, chwarae amledd tôn 523.

    Awgrym: Rhowch sylw i ddechrau pob amod i gael cliw ynghylch pa ddatganiadau sydd eu hangen ar gyfer pob un.


    • Bydd angen i chi greu os-datganiad, 8 arall-os datganiad ac arall-datganiad. Dylai'r rhain fod yn yr adran void loop() eich rhaglen.

    • Bydd rhaglenni'n mynd i lawr yr holl opsiynau nes bod un yn wir. Yna bydd yn perfformio'r camau cod a rhoi'r gorau i fynd i lawr y rhestr. Golyga hyn mai dim ond y lefel golau uchaf mae angen i ni ei ysgrifennu ym mhob datganiad.

    • Dylid ysgrifennu'r cyfarwyddyd: tone(pin, frequency, duration);

    • Mae gennym newidyn i'w ddefnyddio ar gyfer y pin, darperir yr amleddau, ac mae'r hyd yn cael ei fesur mewn milieiliadau (felly 0.5 eiliad = 500 milieiliad).

    • Pan fyddwch chi'n profi'r rhaglen, bydd saib rhwng pob tôn gaiff ei chwarae wrth i'r cyfarwyddiadau eraill gael eu cwblhau yn y void loop().

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
    
      #include <Servo.h>
      Servo myServo;
    
      int piezo = A3;
      int servoPin = 12;
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
      {
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
        myServo.attach(servoPin);
        pinMode(piezo, OUTPUT);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
        myServo.write(0);
        delay(1000);
        myServo.write(90);
        delay(1000);
        myServo.write(180);
        delay(1000);
        myServo.write(90);
        delay(1000);
        if (ldrValue < 60)
        {
          tone(piezo, 65, 500);
        }
        else if (ldrValue < 100)
        {
          tone(piezo, 82, 500);
        }
        else if (ldrValue < 160)
        {
          tone(piezo, 98, 500);
        }
        else if (ldrValue < 220)
        {
          tone(piezo, 131, 500);
        }
        else if (ldrValue < 280)
        {
          tone(piezo, 165, 500);
        }
        else if (ldrValue < 340)
        {
          tone(piezo, 196, 500);
        }
        else if (ldrValue < 400)
        {
          tone(piezo, 262, 500);
        }
        else if (ldrValue < 460)
        {
          tone(piezo, 330, 500);
        }
        else if (ldrValue < 520)
        {
          tone(piezo, 392, 500);
        }
        else 
        {
          tone(piezo, 523, 500);
        }
      }
                        
                      


Ar gyfer yr ymarferion hyn byddem yn argymell eich bod yn defnyddio copi o'ch rhaglen rhag ofn i bethau fynd o chwith.

Mapio: Fel gyda'r codio bloc blaenorol yn Makecode a Tinkercad, mae'n bosib mapio amrediad o werthoedd o fewnbynnau i allbynnau yn lle cael os-datganiadau mor hir.

Ar gyfer hyn mae angen i ni greu gwerth i gynnal y mapio:

int mappedVariable = map(inputValue, inputMin, inputMax, outputMin, outputMax);

Er enghraifft, os hoffem fapio amrediad potensiomedr (mewnbwn analog) i LED (allbwn analog), i wneud yr LED yn fwy disglair wrth i werth y potensiomedr gynyddu, mae angen y wybodaeth ganlynol arnom:

  • inputValue: Dyma werth presennol y potensiomedr.
  • inputMin: Gwerth lleiaf posib y potensiomedr (0).
  • inputMax: Gwerth mwyaf posib y potensiomedr (1023).
  • outputMin: Gwerth lleiaf posib yr LED (0).
  • outputMax: Gwerth mwyaf posib yr LED (255).

Byddai'r rhaglen yn edrych rhywbeth fel hyn:

            
  int potPin = A4;
  int ledPin = 9;
  int potValue = 0;
  int potMapLED = 0;

  void setup()
  {
    pinMode(potPin, INPUT);
    pinMode(ledPin, OUTPUT);
  }

  void loop()
  {
    potValue = analogRead(potPin);
    potMapLED = map(potValue, 0, 1023, 0, 255);
    analogWrite(ledPin, potMapLED);
  }
            
          
  1. Yn eich rhaglen, mapiwch amrediad y mewnbwn LDR i ongl y Servo.

    Awgrym: Amrediad LDR yn yr efelychydd Tinkercad yw 6 i 679. Caiff ongl y servo fod yn unrhyw beth rhwng 0 a 180.


  2. Nawr ceisiwch fapio'r LDR i'r swnyn piezo.

    Ystod amlder y swnyn yw 31 i 4978.


Ymarferion:

Byddwn yn parhau â'r rhaglen a gynhyrchwyd yn Sesiwn Dau.

Dylai pob dysgwr ddechrau ar lefel efydd a gweithio eu ffordd i fyny cyn belled ag y bo modd.

Cliciwch ar bennawd pob her i'w ehangu.


Bydd yr ymarferion hyn yn dangos i chi sut i sefydlu swyddogaethau modur ar gyfer y robot hwn.

  1. Ychwanegwch 4 newidyn math cyfanrif newydd ar ddechrau eich rhaglen ar gyfer y canlynol:

    Newidyn o'r enw leftForwardPin sydd wedi'i osod i 10,
    Newidyn o'r enw leftReversePin sydd wedi'i osod i 11,
    Newidyn o'r enw rightForwardPin sydd wedi'i osod i 9,
    Newidyn o'r enw rightReversePin sydd wedi'i osod i 6.


    • Mae angen i'r rhain fynd cyn y void setup() er mwyn i ni gael eu defnyddio drwy'r cyfan.

    • Os nad ydych yn siŵr, edrychwch ar y newidynnau math cyfanrif blaenorol sydd wedi eu hysgrifennu yn eich rhaglen yn barod.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Dangosir y rhan o'r rhaglen a newidiwyd isod. Bydd y rhaglen lawn yn cael ei hychwanegu ar ddiwedd pob lefel.

                        
      //C++ code
      //
    
      #include <Servo.h>
      Servo myServo;
    
      int leftForwardPin = 10;
      int leftReversePin = 11;
      int rightForwardPin = 9;
      int rightReversePin = 6;
      int piezo = A3;
      int servoPin = 12;
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void setup ()
                        
                      

  2. Nawr mae angen i ni osod y modd pin ar gyfer pob un o'r rhain, gan ddefnyddio ein newidynnau newydd.


    • Mae moduron yn ddyfeisiau allbwn.

    • Er enghraifft: pinMode(leftForwardPin, OUTPUT);

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Dangosir y rhan o'r rhaglen a newidiwyd isod. Bydd y rhaglen lawn yn cael ei hychwanegu ar ddiwedd pob lefel.

                        
      void setup ()
      {
        pinMode(leftForwardPin, OUTPUT);
        pinMode(leftReversePin, OUTPUT);
        pinMode(rightForwardPin, OUTPUT);
        pinMode(rightReversePin, OUTPUT);
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
        myServo.attach(servoPin);
        pinMode(piezo, OUTPUT);
      }
                        
                      

  3. Nawr mae angen i ni greu ein swyddogaethau ein hunain ar gyfer gwahanol gyfeiriadau'r robot (ymlaen, yn ôl, i'r chwith, i'r dde, a stopio).

    Awgrym: Mae'r moduron a ddefnyddir yn y gylched hon yn ddyfeisiau digidol.


    • Byddem yn awgrymu gosod y swyddogaethau newydd hyn ar ôl eich newidynnau drwy'r cyfan ond cyn y void setup(). Bydd hyn yn lleihau'r risg o gymysgu'r swyddogaethau newydd hyn yn ddamweiniol o fewn y rhaglen bresennol.

    • Mae swyddogaeth newydd yn dechrau gyda void functionName() { } gyda'r cyfarwyddiadau y tu mewn i'r cromfachau cyrliog.

    • Ysgrifennir enwau swyddogaethau mewn testun camel (dechrau gyda llythyren fach, dim bylchau, a phob gair newydd yn dechrau gyda phriflythyren).

    • Y tu mewn i bob swyddogaeth bydd angen i chi gynnwys y gorchmynion digitalWrite(); ar gyfer pob newidyn modur.

    • Gan fod y rhain yn ddyfeisiau digidol, bydd angen i ni eu gosod i HIGH neu LOW.

    • Y tu mewn i'r cromfachau digitalWrite(); bydd angen i chi gynnwys y newidyn a nodi a yw'n HIGH neu'n LOW.

    • Er mwyn i'r robot droi i'r chwith, mae angen i'r olwyn dde fynd ymlaen a'r olwyn chwith yn ôl. Ac i'r gwrthwyneb er mwyn i'r robot droi i'r dde.

    • Er enghraifft, bydd swyddogaeth ymlaen yn edrych fel hyn:
                            
        void forward()
        {
          digitalWrite(leftForwardPin, HIGH);
          digitalWrite(leftReversePin, LOW);
          digitalWrite(rightForwardPin, HIGH);
          digitalWrite(rightReversePin, LOW);
        }
                            
                          

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Dangosir y rhan o'r rhaglen a newidiwyd isod. Bydd y rhaglen lawn yn cael ei hychwanegu ar ddiwedd pob lefel.

                        
      int ldrValue = 0;
    
      void robotForward()
      {
        digitalWrite(leftForwardPin, HIGH);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, HIGH);
        digitalWrite(rightReversePin, LOW);
      }
    
      void robotReverse()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, HIGH);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, HIGH);
      }
    
      void robotLeft()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, HIGH);
        digitalWrite(rightForwardPin, HIGH);
        digitalWrite(rightReversePin, LOW);
      }
    
      void robotRight()
      {
        digitalWrite(leftForwardPin, HIGH);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, HIGH);
      }
    
      void robotStop()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, LOW);
      }
    
      void setup ()
                          
                      

  4. Dechreuwch yr efelychiad i sicrhau nad oes gwallau yn eich cod. Ni fydd y moduron yn gwneud unrhyw beth eto, gan nad ydym wedi galw unrhyw un o'n swyddogaethau newydd.


                        
      //C++ code
      //
    
      #include <Servo.h>
      Servo myServo;
    
      int leftForwardPin = 10;
      int leftReversePin = 11;
      int rightForwardPin = 9;
      int rightReversePin = 6;
      int piezo = A3;
      int servoPin = 12;
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void robotForward()
      {
        digitalWrite(leftForwardPin, HIGH);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, HIGH);
        digitalWrite(rightReversePin, LOW);
      }
    
      void robotReverse()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, HIGH);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, HIGH);
      }
    
      void robotLeft()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, HIGH);
        digitalWrite(rightForwardPin, HIGH);
        digitalWrite(rightReversePin, LOW);
      }
    
      void robotRight()
      {
        digitalWrite(leftForwardPin, HIGH);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, HIGH);
      }
    
      void robotStop()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, LOW);
      }
    
      void setup ()
      {
        pinMode(leftForwardPin, OUTPUT);
        pinMode(leftReversePin, OUTPUT);
        pinMode(rightForwardPin, OUTPUT);
        pinMode(rightReversePin, OUTPUT);
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
        myServo.attach(servoPin);
        pinMode(piezo, OUTPUT);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
        myServo.write(0);
        delay(1000);
        myServo.write(90);
        delay(1000);
        myServo.write(180);
        delay(1000);
        myServo.write(90);
        delay(1000);
        if (ldrValue < 60)
        {
          tone(piezo, 65, 500);
        }
        else if (ldrValue < 100)
        {
          tone(piezo, 82, 500);
        }
        else if (ldrValue < 160)
        {
          tone(piezo, 98, 500);
        }
        else if (ldrValue < 220)
        {
          tone(piezo, 131, 500);
        }
        else if (ldrValue < 280)
        {
          tone(piezo, 165, 500);
        }
        else if (ldrValue < 340)
        {
          tone(piezo, 196, 500);
        }
        else if (ldrValue < 400)
        {
          tone(piezo, 262, 500);
        }
        else if (ldrValue < 460)
        {
          tone(piezo, 330, 500);
        }
        else if (ldrValue < 520)
        {
          tone(piezo, 392, 500);
        }
        else 
        {
          tone(piezo, 523, 500);
        }
      }
    
                        
                      




  1. Nawr rydym ni'n mynd i ychwanegu rhaglen at y void loop() sy'n galw ein swyddogaethau newydd pan fydd eu hangen. Rydym am i'n robot wneud y canlynol cyn symud ei servo:
    1. Symud ymlaen am un eiliad.
    2. Stopio am hanner eiliad.
    3. Troi i'r chwith am hanner eiliad.
    4. Troi i'r dde am eiliad.
    5. Troi i'r chwith am hanner eiliad.
    6. Stopio am hanner eiliad.
    7. Symud yn ôl am 1 eiliad.
    8. Stopio am un eiliad.

    Awgrym: Defnyddiwch y cyfarwyddyd delay(); ar gyfer yr amseroedd.


    • I alw swyddogaeth defnyddiwch gyfarwyddyd functionName(); gan ddisodli enw'r swyddogaeth i gyd-fynd â'r un rydych chi'n ei galw.

    • Mesurir saib mewn milieiladau - mae 1000 o'r rhain mewn eiliad.

    • Yn ein rhaglen ateb, defnyddiwyd yr enwau swyddogaethau robotForward(), robotReverse(), robotLeft(), robotRight(), a robotStop(). Felly, gan ddefnyddio enwau'r swyddogaethau hyn, pe baem am i'r robot symud ymlaen am 5 eiliad ac yna stopio am 2 eiliad cyn symud yn ôl am 5 eiliad, byddem yn ysgrifennu:
                          
        robotForward();
        delay(5000);
        robotStop();
        delay(2000);
        robotReverse();
        delay(5000);
        robotStop();
                          
                        

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Dangosir y rhan o'r rhaglen a newidiwyd isod. Bydd y rhaglen lawn yn cael ei hychwanegu ar ddiwedd pob lefel.

                        
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
    
        robotForward();
        delay(1000);
        robotStop();
        delay(500);
        robotLeft();
        delay(500);
        robotRight();
        delay(1000);
        robotLeft();
        delay(500);
        robotStop();
        delay(500);
        robotReverse();
        delay(1000);
        robotStop();
        delay(1000);
    
        myServo.write(0);
        delay(1000);
        myServo.write(90);
        delay(1000);
        myServo.write(180);
        delay(1000);
        myServo.write(90);
        delay(1000);
      }
                        
                      

  2. Dechreuwch yr efelychiad i sicrhau nad oes bygiau ac i sicrhau bod y moduron yn gweithio.


                      
      //C++ code
      //
    
      #include <Servo.h>
      Servo myServo;
    
      int leftForwardPin = 10;
      int leftReversePin = 11;
      int rightForwardPin = 9;
      int rightReversePin = 6;
      int piezo = A3;
      int servoPin = 12;
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void robotForward()
      {
        digitalWrite(leftForwardPin, HIGH);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, HIGH);
        digitalWrite(rightReversePin, LOW);
      }
    
      void robotReverse()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, HIGH);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, HIGH);
      }
    
      void robotLeft()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, HIGH);
        digitalWrite(rightForwardPin, HIGH);
        digitalWrite(rightReversePin, LOW);
      }
    
      void robotRight()
      {
        digitalWrite(leftForwardPin, HIGH);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, HIGH);
      }
    
      void robotStop()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, LOW);
      }
    
      void setup ()
      {
        pinMode(leftForwardPin, OUTPUT);
        pinMode(leftReversePin, OUTPUT);
        pinMode(rightForwardPin, OUTPUT);
        pinMode(rightReversePin, OUTPUT);
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
        myServo.attach(servoPin);
        pinMode(piezo, OUTPUT);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
    
        robotForward();
        delay(1000);
        robotStop();
        delay(500);
        robotLeft();
        delay(500);
        robotRight();
        delay(1000);
        robotLeft();
        delay(500);
        robotStop();
        delay(500);
        robotReverse();
        delay(1000);
        robotStop();
        delay(1000);
    
        myServo.write(0);
        delay(1000);
        myServo.write(90);
        delay(1000);
        myServo.write(180);
        delay(1000);
        myServo.write(90);
        delay(1000);
        if (ldrValue < 60)
        {
          tone(piezo, 65, 500);
        }
        else if (ldrValue < 100)
        {
          tone(piezo, 82, 500);
        }
        else if (ldrValue < 160)
        {
          tone(piezo, 98, 500);
        }
        else if (ldrValue < 220)
        {
          tone(piezo, 131, 500);
        }
        else if (ldrValue < 280)
        {
          tone(piezo, 165, 500);
        }
        else if (ldrValue < 340)
        {
          tone(piezo, 196, 500);
        }
        else if (ldrValue < 400)
        {
          tone(piezo, 262, 500);
        }
        else if (ldrValue < 460)
        {
          tone(piezo, 330, 500);
        }
        else if (ldrValue < 520)
        {
          tone(piezo, 392, 500);
        }
        else 
        {
          tone(piezo, 523, 500);
        }
      }
                      
                    



Rydym ni nawr yn mynd i sefydlu a rhaglennu'r synhwyrydd uwchsain.

  1. Crëwch newidynnau math cyfanrif a gosodwch y dulliau pin ar gyfer y canlynol:

    • Newidyn o'r enw ultrasonicTrigger - wedi'i gysylltu â phin 7 - allbwn.

    • Newidyn o'r enw ultrasonicEcho - wedi'i gysylltu â phin 8 - mewnbwn.


    • Gosodwch y newidynnau cyfanrif newydd i werth y pin.

    • Defnyddiwch y newidyn yn y moddau pin, yn hytrach na rhif y pin.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Dangosir y rhannau o'r rhaglen a newidiwyd isod. Bydd y rhaglen lawn yn cael ei hychwanegu ar ddiwedd pob lefel.

                        
      int ultrasonicTrigger = 7;
      int ultrasonicEcho = 8;
      int leftForwardPin = 10;
      int leftReversePin = 11;
      int rightForwardPin = 9;
      int rightReversePin = 6;
      int piezo = A3;
      int servoPin = 12;
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
                        
                      
                        
      void setup ()
      {
        pinMode(ultrasonicTrigger, OUTPUT);
        pinMode(ultrasonicEcho, INPUT);
        pinMode(leftForwardPin, OUTPUT);
        pinMode(leftReversePin, OUTPUT);
        pinMode(rightForwardPin, OUTPUT);
        pinMode(rightReversePin, OUTPUT);
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
        myServo.attach(servoPin);
        pinMode(piezo, OUTPUT);
      }
                        
                      

  2. Pwysig: Mae gan y synhwyrydd uwchsain broses osod gymhleth nad oes angen i chi boeni am ei dysgu ar hyn o bryd. Yn lle hynny, gofynnwn i chi gopïo'r swyddogaeth gyfrifo isod yn ofalus i'ch rhaglen yn union ar ôl eich swyddogaethau modur ond cyn y void setup();.

                    
      int readUltrasonic() 
      {
        digitalWrite(ultrasonicTrigger,LOW); // Clear the signal
        delayMicroseconds(2);
        digitalWrite(ultrasonicTrigger, HIGH); // Send out new signal
        delayMicroseconds(10);
        digitalWrite(ultrasonicTrigger,LOW); // Stop sending signal
    
        unsigned long duration = pulseIn(ultrasonicEcho, HIGH);
        int distance = duration /2 /29;
        Serial.print(distance);
        Serial.print("cm");
        return distance;
      }
                    
                  

    Mae'r swyddogaeth hon yn rhoi'r pellter i wrthrych mae'n ei synhwyro mewn centimetrau. Gallwn nawr ei alw yn ein rhaglen i helpu gyda gweddill yr ymarfer hwn.

    Sylwer os gwelwch yn dda: Os ydych chi'n defnyddio enwau newidyn gwahanol i'r rhai a ddarperir yng ngham 1, ni fydd hyn yn gweithio.


  3. Crëwch newidynnau cyfanrif drwy'r cyfan newydd o'r enw 'left','front', a 'right'. Gosodwch pob un i 0. Ateb

    Dangosir y rhan o'r rhaglen a newidiwyd isod. Bydd y rhaglen lawn yn cael ei hychwanegu ar ddiwedd pob lefel.

                      
      int left = 0;
      int front = 0;
      int right = 0;
      int ultrasonicTrigger = 7;
      int ultrasonicEcho = 8;
      int leftForwardPin = 10;
      int leftReversePin = 11;
      int rightForwardPin = 9;
      int rightReversePin = 6;
      int piezo = A3;
      int servoPin = 12;
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
                      
                    

  4. Mae ein rhaglen eisoes yn cynnwys symudiadau servo fel y dangosir isod.
                    
      myServo.write(0);
      delay(1000);
      myServo.write(90);
      delay(1000);
      myServo.write(180);
      delay(1000);
      myServo.write(90);
      delay(1000);
                    
                  
    Rydym ni nawr eisiau cymryd darlleniadau uwchsonig o bob cyfeiriad. Felly, ar ôl symud i 0°, mewnosodwch linell sy'n gosod ein newidyn 'left' newydd i alw ein swyddogaeth readUltrasonic(). Yna, ar ôl iddo symud i 90°, gosodwch y newidyn 'front' i alw'r un swyddogaeth. Ailadroddwch eto am 180° gyda newidyn 'right'. Nid oes angen darllen y pedwerydd symudiad gan ein bod eisoes wedi cymryd hwnnw.

    Awgrym: Cofiwch, pwrpas y seibiau yw rhoi amser i'r servos orffen eu symudiadau felly dylid cymryd y darlleniadau ar ôl y saib ond cyn y symudiad nesaf.


    • Dyma sut i ychwanegu'r darlleniad chwith fel enghraifft:
                            
        myServo.write(0);
        delay(1000);
        left = readUltrasonic();
        myServo.write(90);
        delay(1000);
        myServo.write(180);
        delay(1000);
        myServo.write(90);
        delay(1000);
                            
                          

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Dangosir y rhan o'r rhaglen a newidiwyd isod. Bydd y rhaglen lawn yn cael ei hychwanegu ar ddiwedd pob lefel.

                        
      myServo.write(0);
      delay(1000);
      left = readUltrasonic();
      myServo.write(90);
      delay(1000);
      front = readUltrasonic();
      myServo.write(180);
      delay(1000);
      right = readUltrasonic();
      myServo.write(90);
      delay(1000);
                        
                      

  5. Rydym eisoes wedi rhaglennu llwybr symud i'r robot. Nawr, mae angen i ni sicrhau bod hyn yn ddiogel i'r robot ac na fydd yn taro i mewn i unrhyw beth. Gan mai dim ond mynd yn ôl ac ymlaen gyda rhywfaint o droi yw'r llwybr presennol, dim ond gwneud yn siŵr nad oes unrhyw beth o'i flaen sydd angen. Newidiwch eich rhaglen i stopio os yw darlleniad y synhwyrydd blaen yn llai na metr.

    Awgrym: Mae swyddogaeth readUltrasonic() yn rhoi pellter mewn centimedrau.


    • Mae hyn yn gofyn am ddatganiad-os ar gyfer pan fo'r tu front < 100.

    • Bydd angen i ni roi ein cyfarwyddiadau modur blaenorol mewn arall-datganiad.

    • Cofiwch, i roi'r gorau i symud, mae gennym swyddogaeth stopio a wnaed yn gynharach.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Dangosir y rhan o'r rhaglen a newidiwyd isod. Bydd y rhaglen lawn yn cael ei hychwanegu ar ddiwedd pob lefel.

                        
      if (front < 100)
      {
        robotStop();
      }
      else
      {
        robotForward();
        delay(1000);
        robotStop();
        delay(500);
        robotLeft();
        delay(500);
        robotRight();
        delay(1000);
        robotLeft();
        delay(500);
        robotStop();
        delay(500);
        robotReverse();
        delay(1000);
        robotStop();
        delay(1000);
      }                  
                        
                      

  6. Yn eich void loop(), crëwch set o gyfarwyddiadau a fydd yn argraffu i'r monitor cyfresol p'un ai'r ochr dde ynteu'r chwith sydd fwyaf diogel i deithio iddi.

    Awgrym: Bydd hyn yn gofyn am os-ddatganiad, arall-os datganiad, ac arall-datganiad. Defnyddir y datganiad arall i dangos pan fo'r ddau fesuriad yr un peth.


    • Os dde > chwith, rydym am i'r monitor cyfresol ddangos y gair right, gan mai dyma'r cyfeiriad mwyaf diogel.

    • Arall os chwith>dde, rydym am i'r monitor cyfresol ddangos y gair left.

    • Arall, rydym am i'r monitor cyfresol ddangos yr ymadrodd 'no problem'.

    • Cofiwch, wrth argraffu geiriau i'r monitor cyfresol, rydym yn defnyddio dyfynodau dwbl: Serial.println("gair");

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Dangosir y rhan o'r rhaglen a newidiwyd isod. Bydd y rhaglen lawn yn cael ei hychwanegu ar ddiwedd pob lefel.

                        
      myServo.write(0);
      delay(1000);
      left = readUltrasonic();
      myServo.write(90);
      delay(1000);
      front = readUltrasonic();
      myServo.write(180);
      delay(1000);
      right = readUltrasonic();
      myServo.write(90);
      delay(1000);
    
      if (right > left)
      {
        Serial.println("right");
      }
      else if (left > right)
      {
        Serial.println("left");
      }
      else
      {
        Serial.println("no problem");
      }
                        
                      

  7. Gobeithio eich bod wedi bod yn gwirio eich cod ar ôl pob cam. Os ddim, dechreuwch yr efelychiad er mwyn sicrhau nad oes bygiau ac i brofi'ch rhaglen.


                      
      //C++ code
      //
    
      #include <Servo.h>
      Servo myServo;
    
      int left = 0;
      int front = 0;
      int right = 0;
      int ultrasonicTrigger = 7;
      int ultrasonicEcho = 8;
      int leftForwardPin = 10;
      int leftReversePin = 11;
      int rightForwardPin = 9;
      int rightReversePin = 6;
      int piezo = A3;
      int servoPin = 12;
      int ldr = A0;
      int blueLED = 13;
      int ldrValue = 0;
    
      void robotForward()
      {
        digitalWrite(leftForwardPin, HIGH);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, HIGH);
        digitalWrite(rightReversePin, LOW);
      }
    
      void robotReverse()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, HIGH);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, HIGH);
      }
    
      void robotLeft()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, HIGH);
        digitalWrite(rightForwardPin, HIGH);
        digitalWrite(rightReversePin, LOW);
      }
    
      void robotRight()
      {
        digitalWrite(leftForwardPin, HIGH);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, HIGH);
      }
    
      void robotStop()
      {
        digitalWrite(leftForwardPin, LOW);
        digitalWrite(leftReversePin, LOW);
        digitalWrite(rightForwardPin, LOW);
        digitalWrite(rightReversePin, LOW);
      }
    
      int readUltrasonic() 
      {
        digitalWrite(ultrasonicTrigger,LOW); // Clear the signal
        delayMicroseconds(2);
        digitalWrite(ultrasonicTrigger, HIGH); // Send out new signal
        delayMicroseconds(10);
        digitalWrite(ultrasonicTrigger,LOW); // Stop sending signal
    
        unsigned long duration = pulseIn(ultrasonicEcho, HIGH);
        int distance = duration /2 /29;
        Serial.print(distance);
        Serial.print("cm");
        return distance;
      }
    
      void setup ()
      {
        pinMode(ultrasonicTrigger, OUTPUT);
        pinMode(ultrasonicEcho, INPUT);
        pinMode(leftForwardPin, OUTPUT);
        pinMode(leftReversePin, OUTPUT);
        pinMode(rightForwardPin, OUTPUT);
        pinMode(rightReversePin, OUTPUT);
        pinMode(blueLED, OUTPUT);
        pinMode(ldr, INPUT);
        Serial.begin(9600);
        myServo.attach(servoPin);
        pinMode(piezo, OUTPUT);
      }
    
      void loop ()
      {
        ldrValue = analogRead(ldr);
        Serial.println(ldrValue);
        if (ldrValue < 160)
        {
          digitalWrite(blueLED, HIGH);
        }
        else
        {
          digitalWrite(blueLED, LOW);
        }
    
        if (front < 100)
        {
          robotStop();
        }
        else
        {
          robotForward();
          delay(1000);
          robotStop();
          delay(500);
          robotLeft();
          delay(500);
          robotRight();
          delay(1000);
          robotLeft();
          delay(500);
          robotStop();
          delay(500);
          robotReverse();
          delay(1000);
          robotStop();
          delay(1000);
        }   
    
        myServo.write(0);
        delay(1000);
        left = readUltrasonic();
        myServo.write(90);
        delay(1000);
        front = readUltrasonic();
        myServo.write(180);
        delay(1000);
        right = readUltrasonic();
        myServo.write(90);
        delay(1000);
    
        if (right > left)
        {
          Serial.println("right");
        }
        else if (left > right)
        {
          Serial.println("left");
        }
        else
        {
          Serial.println("no problem");
        }
    
        if (ldrValue < 60)
        {
          tone(piezo, 65, 500);
        }
        else if (ldrValue < 100)
        {
          tone(piezo, 82, 500);
        }
        else if (ldrValue < 160)
        {
          tone(piezo, 98, 500);
        }
        else if (ldrValue < 220)
        {
          tone(piezo, 131, 500);
        }
        else if (ldrValue < 280)
        {
          tone(piezo, 165, 500);
        }
        else if (ldrValue < 340)
        {
          tone(piezo, 196, 500);
        }
        else if (ldrValue < 400)
        {
          tone(piezo, 262, 500);
        }
        else if (ldrValue < 460)
        {
          tone(piezo, 330, 500);
        }
        else if (ldrValue < 520)
        {
          tone(piezo, 392, 500);
        }
        else 
        {
          tone(piezo, 523, 500);
        }
      }                  
                      
                    


I gael her ychwanegol rhowch gynnig ar y canlynol mewn copi o'ch rhaglen.

Dilëwch y symudiadau presennol o'ch void loop() () ac ysgrifennwch raglen newydd sydd yn golygu bod y robot yn defnyddio ei servos a'i ddarlleniadau uwchsonig cyn penderfynu pa ffordd i symud. Cofiwch, mae ein symudiadau chwith a dde yn cynnwys troi yn y fan a'r lle, mae'n rhaid i chi wedyn yrru ymlaen er mwyn mynd y ffordd honno.


Video Lesson

Ymarferion:

This session, we shall be using a different Tinkercad circuit to revise everything covered in this topic.

You will need to copy our Sensor Board circuit to use for these exercises.

This sensor board has several sensors and LEDS fitted and will allow us to replicate a series of different home devices.

All learners should start with the bronze level and work their way up as far as they can.

Click on each challenge heading to expand.


In this section, we shall be creating a program using the LDR/Photoresistor to control the brightness of the red LED.

  1. Create integer type variables for the LDR and red LED pins.


    • You can use the circuit to determine which programmable pins the components are connected to.

    • Remember, all pin names are classed as whole numbers (integers), even those that include the letter A.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
    
      int ldrPin = A5;
      int redLEDPin = 3;
    
      void setup ()
      {
        
      }
    
      void loop ()
      {
    
      }
                        
                      

  2. Set the pinMode(); for these two components.


    • The pinMode(); instruction requires you to tell it (inside the brackets) the pin's value and whether it is an input or output.

    • Remember, input and output are written in block capitals for this.

    • Instead of writing the pin's number, use the variable created in the previous step.

    • Sensors that collect information are input devices.

    • Components that we control, using the program, are outputs.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                         
      //C++ code
      //
    
      int ldrPin = A5;
      int redLEDPin = 3;
    
      void setup ()
      {
        pinMode(ldrPin, INPUT);
        pinMode(redLEDPin, OUTPUT);
      }
    
      void loop ()
      {
    
      }
                         
                       

  3. In the void loop() write a program to store the LDR's value in a variable.

    Awgrym: You will need to create a new integer type variable for this.


    • This is where choosing names for variables is important. You need to be able to tell which variable is the pin value and which is the reading. Especially, as your program for this requires both.

    • Make this new variable globally available and initially set to zero.

    • Remember, the LDR is an analog input device.

    • We 'read' inputs and 'write' outputs.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                         
      //C++ code
      //
    
      int ldrPin = A5;
      int redLEDPin = 3;
      int ldrReading = 0;
    
      void setup ()
      {
        pinMode(ldrPin, INPUT);
        pinMode(redLEDPin, OUTPUT);
      }
    
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
      }                       
                         
                       

  4. Print this value in the serial monitor.

    Awgrym: Don't forget to include the necessary set-up instruction to use the serial monitor.


    • In the void setup() function you will need to add the Serial.begin(9600); instruction so the program knows to use the serial monitor.

    • Inside the void loop() you will need to write the variable value to the serial monitor.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                         
      //C++ code
      //
    
      int ldrPin = A5;
      int redLEDPin = 3;
      int ldrReading = 0;
    
      void setup ()
      {
        pinMode(ldrPin, INPUT);
        pinMode(redLEDPin, OUTPUT);
        Serial.begin(9600);
      }
    
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
        Serial.println(ldrReading);
      }                       
                         
                        

  5. Use the simulator to find the minimum and maximum values of the LDR.


    • If the code doesn't work, check it against the answer for the above section. The most common error involves too many or too few semi-colons.

    • Remember, you can change the values of the LDR in the simulator by selecting it and then adjuster the slider that appears.

    • You will need the serial monitor open at the bottom of your code window to see the values.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The range of the LDR in the Tinkercad simulator is 6 - 679.


  6. Map the LDR reading to the range of the red LED (0 - 255) and store the value in a new integer type variable.

    Mapping: As with the previous block coding in Makecode and Tinkercad, it is possible to map ranges of values from inputs to outputs instead of having such long if-statements.

    For this we need to create a value to hold the mapping:

    int mappedVariable = map(inputValue, inputMin, inputMax, outputMin, outputMax);

    For example, if we wanted to map the range of a potentiometer (analog input) to an LED (analog output), making the LED brighter as the potentiometer value increases, we need the following information:

    • inputValue: This is the current value of the potentiometer.
    • inputMin: The minimum possible value of the potentiometer (0).
    • inputMax: The maximum possible value of the potentiometer (1023).
    • outputMin: The minimum possible value of the LED (0).
    • outputMax: The maximum possible value of the LED (255).

    The program would look something like this:

                      
      int potPin = A4;
      int ledPin = 9;
      int potValue = 0;
      int potMapLED = 0;
    
      void setup()
      {
        pinMode(potPin, INPUT);
        pinMode(ledPin, OUTPUT);
      }
    
      void loop()
      {
        potValue = analogRead(potPin);
        potMapLED = map(potValue, 0, 1023, 0, 255);
        analogWrite(ledPin, potMapLED);
      }
                      
                    


    • Create an integer type global variable and set it to zero. This is where we will then store the mapped LDR value inside our program.

    • Looking at the structure of map(inputValue, inputMin, inputMax, outputMin, outputMax); we know the inputValue is our reading from step 4, the inputMin is 6 as we discovered in step 5, and from the same step we also know that inputMax is 679. The output is an LED, which always has a range of 0 - 255.

    • Set your new variable for the mapped value to equal the mapping function inside the void loop().

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
     //C++ code
     //
    
     int ldrPin = A5;
     int redLEDPin = 3;
     int ldrReading = 0;
     int ldrMapValue = 0;
    
     void setup ()
     {
       pinMode(ldrPin, INPUT);
       pinMode(redLEDPin, OUTPUT);
       Serial.begin(9600);
     }
    
     void loop ()
     {
       ldrReading = analogRead(ldrPin);
       Serial.println(ldrReading);
       ldrMapValue = map(ldrReading, 6, 679, 0, 255);
     }                       
                        
                       

  7. Use this mapped value to set the brightness of the red LED.


    • As we are adjusting the brightness of the LED, we are using it as an analog output device.

    • Remember, we 'read' inputs and 'write' outputs.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                        
      //C++ code
      //
    
      int ldrPin = A5;
      int redLEDPin = 3;
      int ldrReading = 0;
      int ldrMapValue = 0;
    
      void setup ()
      {
        pinMode(ldrPin, INPUT);
        pinMode(redLEDPin, OUTPUT);
        Serial.begin(9600);
      }
    
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
        Serial.println(ldrReading);
        ldrMapValue = map(ldrReading, 6, 679, 0, 255);
        analogWrite(redLEDPin, ldrMapValue);
      }                       
                        
                       

  8. If this was part of a home circuit to turn the lights on and off, we have a problem. Currently the LED is at its brightest when the light level is at its highest. We would want it to be the other way round. Can you work out how to set it so the LED gets brighter as the light level drops?


    • We do not need to add any new lines of code, just to alter what we currently have.

    • By changing the range of the redLED in the mapping function from 0 - 255 to 255 - 0, we can reverse the program.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


                         
      //C++ code
      //
    
      int ldrPin = A5;
      int redLEDPin = 3;
      int ldrReading = 0;
      int ldrMapValue = 0;
    
      void setup ()
      {
        pinMode(ldrPin, INPUT);
        pinMode(redLEDPin, OUTPUT);
        Serial.begin(9600);
      }
    
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
        Serial.println(ldrReading);
        ldrMapValue = map(ldrReading, 6, 679, 255, 0);
        analogWrite(redLEDPin, ldrMapValue);
      }   
                         
                       



Continue using the program developed in the Lefel Efydd.

In this set of exercises, we shall be creating a simulation of a home heating system. For this, we will need to use the temperature sensor to collect readings, the potentiometer to set our preferred heating level, and the blue and green LEDs to indicate when it is too cold, at the correct temperature, and too hot.

  1. As we are adding new components to our program, we need to create variables to store their pin values.

    Awgrym: There are four new components being added; the temperature sensor, the potentiometer, the blue LED, and the green LED.


    • Choose suitable variable names.

    • These are all integer type variables.

    • Look at the wiring of the components in the provided circuit to determine which programmable pin they each use.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The section of the program altered is shown below. The full program will be added at the end of the level.

                         
      //C++ code
      //
    
      int ldrPin = A5;
      int redLEDPin = 3;
      int ldrReading = 0;
      int ldrMapValue = 0;
      int tempPin = A4;
      int potPin = A3;
      int greenLEDPin = 5;
      int blueLEDPin = 6;
    
                         
                       

  2. Now complete the necessary void setup() instructions for these components.


    • This means creating the pinMode() for each component.

    • Two of these components are inputs.

    • Use your pin value variables in place of the pin numbers.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The section of the program altered is shown below. The full program will be added at the end of the level.

                         
      void setup ()
      {
        pinMode(ldrPin, INPUT);
        pinMode(redLEDPin, OUTPUT);
        Serial.begin(9600);
        pinMode(tempPin, INPUT);
        pinMode(potPin, INPUT);
        pinMode(greenLEDPin, OUTPUT);
        pinMode(blueLEDPin, OUTPUT);
      }
                         
                       

  3. Print the temperature sensor reading to the serial monitor and find its range of values.

    Awgrym: You will need a new variable to store this value.


    • We have already set-up the serial monitor for usage in the Lefel Efydd exercises.

    • The new variable is a global integer type variable which will store the temperature sensor's reading.

    • The temperature sensor is an analog input device.

    • Use the Serial.println() command in your void loop() to print the value of your new variable.

    • Remember, you are already printing the LDR value, so will get 2 values in the serial monitor each time the void loop() runs.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The sections of the program altered is shown below. The full program will be added at the end of the level.

                        
     //C++ code
     //
    
     int ldrPin = A5;
     int redLEDPin = 3;
     int ldrReading = 0;
     int ldrMapValue = 0;
     int tempPin = A4;
     int potPin = A3;
     int greenLEDPin = 5;
     int blueLEDPin = 6;
     int tempReading = 0;
    
                        
                      

                         
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
        Serial.println(ldrReading);
        ldrMapValue = map(ldrReading, 6, 679, 255, 0);
        analogWrite(redLEDPin, ldrMapValue);
        tempReading = analogRead(tempPin);
        Serial.println(tempReading);
      } 
                         
                       

    The range of the temperature sensor in this simulator is 20 - 358.


  4. The values we are currently collecting from the temperature sensor do not have much meaning in their current form. Map the temperature value onto a range of -40°C to 125°C, the program will the do the mathematical conversion to a known measurement for us.

    Awgrym: You will need a new variable to hold your converted temperature value.


    • Create a global integer type variable to store this value in and initially set it to zero.

    • When mapping values, we can map them to a new set of values rather than to an output's range.

    • Replace the outputMin value in the mapping function with -40, and the outputMax value to 125.

    • Use the range values from step 3 for the inputMin and inputMax values.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The sections of the program altered is shown below. The full program will be added at the end of the level.

                        
     //C++ code
     //
    
     int ldrPin = A5;
     int redLEDPin = 3;
     int ldrReading = 0;
     int ldrMapValue = 0;
     int tempPin = A4;
     int potPin = A3;
     int greenLEDPin = 5;
     int blueLEDPin = 6;
     int tempReading = 0;
     int tempDegreesC = 0;
    
                        
                      

                         
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
        Serial.println(ldrReading);
        ldrMapValue = map(ldrReading, 6, 679, 255, 0);
        analogWrite(redLEDPin, ldrMapValue);
        tempReading = analogRead(tempPin);
        Serial.println(tempReading);
        tempDegreesC = map(tempReading, 20, 358, -40, 125);
      } 
                         
                       

  5. If the temperature is more than 20°C, we want the green LED to turn on. However, if the temperature gets too high (over 50°C), we want the green LED to flash on and off every 250ms as a warning.

    Awgrym: Don't forget to turn the LED off when the temperature drops back down.


    • As we are simply turning the green LED on and off, we can use the digitalWrite() command, with the HIGH and LOW instructions.

    • You will need to think about the order of your if and else-if statements. The program will run the first one that is true. So, if you first check to see if the temperature is over 20°C, this will be true when it's over 50°C too and the warning light program will not work.

    • Remember, the instructions included in these statements need to be inside the curly brackets, { }. The statements themselves do not require semi-colons, but the instructions inside do.

    • We are using the newly mapped values of temperature in °C for these statement conditions.

    • For the flashing light, you will need to include delay() instructions.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The section of the program altered is shown below. The full program will be added at the end of the level.

                         
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
        Serial.println(ldrReading);
        ldrMapValue = map(ldrReading, 6, 679, 255, 0);
        analogWrite(redLEDPin, ldrMapValue);
        tempReading = analogRead(tempPin);
        Serial.println(tempReading);
        tempDegreesC = map(tempReading, 20, 358, -40, 125);
        if (tempDegreesC > 50)
        {
          digitalWrite(greenLEDPin, HIGH);
          delay(250);
          digitalWrite(greenLEDPin, LOW);
          delay(250);
        }
        else if (tempDegreesC > 20)
        {
          digitalWrite(greenLEDPin, HIGH);
        }
        else
        {
          digitalWrite(greenLEDPin, LOW);
        }
      } 
                         
                       

  6. We need to add the potentiometer to our program as a temperature control dial. This means it needs to be mapped onto a more suitable range of values, in this case 5°C to 35°C.

    Awgrym: This is using the same method as converting the temperature readings.


    • Create global integer type variables for your potentiometer reading and the mapped potentiometer value and set them to zero.

    • If you do not know the range of the potentiometer, you will need to use the serial monitor to help you find it.

    • To test your mapping use the serial monitor. You may need to start printing additional information to separate the different values currently being produced. For this you can use Serial.print("") which will print whatever is typed between the quotation marks inside the brackets.

    • Add a one second delay at the end of your void loop() to give you chance to read the serial monitor before the program repeats.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The sections of the program altered is shown below. The full program will be added at the end of the level.

                         
      //C++ code
      //
      
      int ldrPin = A5;
      int redLEDPin = 3;
      int ldrReading = 0;
      int ldrMapValue = 0;
      int tempPin = A4;
      int potPin = A3;
      int greenLEDPin = 5;
      int blueLEDPin = 6;
      int tempReading = 0;
      int tempDegreesC = 0;
      int potReading = 0;
      int potDegreesC = 0;
                         
                       

                        
     void loop ()
     {
       ldrReading = analogRead(ldrPin);
       Serial.println(ldrReading);
       ldrMapValue = map(ldrReading, 6, 679, 255, 0);
       analogWrite(redLEDPin, ldrMapValue);
       tempReading = analogRead(tempPin);
       Serial.println(tempReading);
       tempDegreesC = map(tempReading, 20, 358, -40, 125);
       if (tempDegreesC > 50)
       {
         digitalWrite(greenLEDPin, HIGH);
         delay(250);
         digitalWrite(greenLEDPin, LOW);
         delay(250);
       }
       else if (tempDegreesC > 20)
       {
         digitalWrite(greenLEDPin, HIGH);
       }
       else
       {
         digitalWrite(greenLEDPin, LOW);
       }
       potReading = analogRead(potPin);
       Serial.println("Potentiometer reading: ");
       Serial.println(potReading);
       potDegreesC = map(potReading, 0, 1023, 5, 35);
       Serial.println("Potentiometer in degrees: ");
       Serial.println(potDegreesC);
       delay(1000);
     } 
                        
                      

  7. Now turn on the blue LED when the temperature is lower than that set on the potentiometer.

    Awgrym: Imagine that this is turning on the heating at the same time.


    • You will need to compare the mapped values for both the temperature sensor and the potentiometer inside an if-statement for this.

    • Remember to include an else statement to turn the Led off again when the temperature is reached.

    • You can remove any delay you may have added to help read the serial monitor in the previous step.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The section of the program altered is shown below. The full program will be added at the end of the level.

                         
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
        Serial.println(ldrReading);
        ldrMapValue = map(ldrReading, 6, 679, 255, 0);
        analogWrite(redLEDPin, ldrMapValue);
        tempReading = analogRead(tempPin);
        Serial.println(tempReading);
        tempDegreesC = map(tempReading, 20, 358, -40, 125);
        if (tempDegreesC > 50)
        {
          digitalWrite(greenLEDPin, HIGH);
          delay(250);
          digitalWrite(greenLEDPin, LOW);
          delay(250);
        }
        else if (tempDegreesC > 20)
        {
          digitalWrite(greenLEDPin, HIGH);
        }
        else
        {
          digitalWrite(greenLEDPin, LOW);
        }
        potReading = analogRead(potPin);
        Serial.println("Potentiometer reading: ");
        Serial.println(potReading);
        potDegreesC = map(potReading, 0, 1023, 5, 35);
        Serial.println("Potentiometer in degrees: ");
        Serial.println(potDegreesC);
        if (tempDegreesC < potDegreesC)
        {
          digitalWrite(blueLEDPin, HIGH);
        }
        else
        {
          digitalWrite(blueLEDPin, LOW);
        }
      } 
                         
                       

  8. Run the simulation to check for bugs and to test your heating system works as expected.


                      
      //C++ code
      //
      
      int ldrPin = A5;
      int redLEDPin = 3;
      int ldrReading = 0;
      int ldrMapValue = 0;
      int tempPin = A4;
      int potPin = A3;
      int greenLEDPin = 5;
      int blueLEDPin = 6;
      int tempReading = 0;
      int tempDegreesC = 0;
      int potReading = 0;
      int potDegreesC = 0;
    
      void setup ()
      {
        pinMode(ldrPin, INPUT);
        pinMode(redLEDPin, OUTPUT);
        Serial.begin(9600);
        pinMode(tempPin, INPUT);
        pinMode(potPin, INPUT);
        pinMode(greenLEDPin, OUTPUT);
        pinMode(blueLEDPin, OUTPUT);
      }
    
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
        Serial.println(ldrReading);
        ldrMapValue = map(ldrReading, 6, 679, 255, 0);
        analogWrite(redLEDPin, ldrMapValue);
        tempReading = analogRead(tempPin);
        Serial.println(tempReading);
        tempDegreesC = map(tempReading, 20, 358, -40, 125);
        if (tempDegreesC > 50)
        {
          digitalWrite(greenLEDPin, HIGH);
          delay(250);
          digitalWrite(greenLEDPin, LOW);
          delay(250);
        }
        else if (tempDegreesC > 20)
        {
          digitalWrite(greenLEDPin, HIGH);
        }
        else
        {
          digitalWrite(greenLEDPin, LOW);
        }
        potReading = analogRead(potPin);
        Serial.println("Potentiometer reading: ");
        Serial.println(potReading);
        potDegreesC = map(potReading, 0, 1023, 5, 35);
        Serial.println("Potentiometer in degrees: ");
        Serial.println(potDegreesC);
        if (tempDegreesC < potDegreesC)
        {
          digitalWrite(blueLEDPin, HIGH);
        }
        else
        {
          digitalWrite(blueLEDPin, LOW);
        }
      } 
                      
                    



Continuing with our program we shall now program a home security system with some of the other components.

  1. Create global integer variables to store the PIR (motion sensor) and filament lightbulb pin values. Then use these to set-up the pin modes for both components.


    • The PIR is a digital input device that detects motion/movement.

    • For this exercise, the filament lightbulb is a digital output.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The sections of the program altered is shown below. The full program will be added at the end of the level.

                         
      //C++ code
      //
      
      int ldrPin = A5;
      int redLEDPin = 3;
      int ldrReading = 0;
      int ldrMapValue = 0;
      int tempPin = A4;
      int potPin = A3;
      int greenLEDPin = 5;
      int blueLEDPin = 6;
      int tempReading = 0;
      int tempDegreesC = 0;
      int potReading = 0;
      int potDegreesC = 0;
      int pirPin = 4;
      int bulbPin = 12;
                         
                       

                        
      void setup ()
      {
        pinMode(ldrPin, INPUT);
        pinMode(redLEDPin, OUTPUT);
        Serial.begin(9600);
        pinMode(tempPin, INPUT);
        pinMode(potPin, INPUT);
        pinMode(greenLEDPin, OUTPUT);
        pinMode(blueLEDPin, OUTPUT);
        pinMode(pirPin, INPUT);
        pinMode(bulbPin, OUTPUT);
      }
                        
                      

  2. New Variable Type: The PIR sensor is a digital input device which reads TRUE when it detects motion, and FALSE when it does not. When a variable is true or false, it is called a Boolean type variable.

    So, when creating a variable to store a digital input value, we use bool instead of int.


  3. Create a global Boolean type variable and set it to 0. Then, in the void loop() set this new variable to read the PIR's digital input.


    • Use this new type of variable in the same way you would any other.

    • You will need to use the digitalRead() instruction.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The sections of the program altered is shown below. The full program will be added at the end of the level.

                        
     //C++ code
     //
     
     int ldrPin = A5;
     int redLEDPin = 3;
     int ldrReading = 0;
     int ldrMapValue = 0;
     int tempPin = A4;
     int potPin = A3;
     int greenLEDPin = 5;
     int blueLEDPin = 6;
     int tempReading = 0;
     int tempDegreesC = 0;
     int potReading = 0;
     int potDegreesC = 0;
     int pirPin = 4;
     int bulbPin = 12;
     bool pirReading = 0;
                        
                      

                         
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
        Serial.println(ldrReading);
        ldrMapValue = map(ldrReading, 6, 679, 255, 0);
        analogWrite(redLEDPin, ldrMapValue);
        tempReading = analogRead(tempPin);
        Serial.println(tempReading);
        tempDegreesC = map(tempReading, 20, 358, -40, 125);
        if (tempDegreesC > 50)
        {
          digitalWrite(greenLEDPin, HIGH);
          delay(250);
          digitalWrite(greenLEDPin, LOW);
          delay(250);
        }
        else if (tempDegreesC > 20)
        {
          digitalWrite(greenLEDPin, HIGH);
        }
        else
        {
          digitalWrite(greenLEDPin, LOW);
        }
        potReading = analogRead(potPin);
        Serial.println("Potentiometer reading: ");
        Serial.println(potReading);
        potDegreesC = map(potReading, 0, 1023, 5, 35);
        Serial.println("Potentiometer in degrees: ");
        Serial.println(potDegreesC);
        if (tempDegreesC < potDegreesC)
        {
          digitalWrite(blueLEDPin, HIGH);
        }
        else
        {
          digitalWrite(blueLEDPin, LOW);
        }
        pirReading = digitalRead(pirPin);
      } 
                         
                       

  4. We now want the filament lightbulb to turn on for 5 seconds when the PIR detects movement.

    Boolean conditions: The conditions of an if statement (or else if statement), are Boolean - they are either true or false. If it is true, then the program runs its contents. If it is not true (false) then it skips to the next section.

    This means that when we create an if statement checking to see if a Boolean variable is true we can simply use if (booleanVariable) because the condition is already checking to see if it is true.

    For example: Let's say we have a Boolean variable called 'active' that tells the program to program to turn on an LED connected to pin 3 when 'active' is true. Here is the resulting program:

                      
      bool active = 0;
    
      void setup() 
      {
        pinMode(3, OUTPUT);
      }
    
      void loop()
      {
        active = FALSE;
        if (active)
        {
          digitalWrite(3, HIGH);
        }
        else
        {
          digitalWrite(3, LOW);
        }
      }
                      
                    

    This program is checking to see if the Boolean value of active is true, which it is not, so the light will not turn on.

    If you wanted to change the program to do the opposite, turning the LED on when 'active' is false, you have two options. You could simply switch the instructions around in the previous program, like this:

                      
      if (active)
      {
        digitalWrite(3, LOW);
      }
      else
      {
        digitalWrite(3, HIGH);
      }  
                      
                    

    Alternatively, you could have changed the condition to false using an exclaimation mark (!) before the variable name, like this:

                      
      if (!active)
      {
        digitalWrite(3, HIGH);
      }
      else
      {
        digitalWrite(3, LOW);
      }
                      
                    

    If you do write if(boolVariable = TRUE) or if(boolVariable = FALSE), it will still work. However, it demonstrates that the programmer does not fully understand how if-statements work.



    • You will need to turn the light off again after the 5 seconds.

    • Using a delay and a turn off command in the if-statement means we do not need an else statement.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The section of the program altered is shown below. The full program will be added at the end of the level.

                         
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
        Serial.println(ldrReading);
        ldrMapValue = map(ldrReading, 6, 679, 255, 0);
        analogWrite(redLEDPin, ldrMapValue);
        tempReading = analogRead(tempPin);
        Serial.println(tempReading);
        tempDegreesC = map(tempReading, 20, 358, -40, 125);
        if (tempDegreesC > 50)
        {
          digitalWrite(greenLEDPin, HIGH);
          delay(250);
          digitalWrite(greenLEDPin, LOW);
          delay(250);
        }
        else if (tempDegreesC > 20)
        {
          digitalWrite(greenLEDPin, HIGH);
        }
        else
        {
          digitalWrite(greenLEDPin, LOW);
        }
        potReading = analogRead(potPin);
        Serial.println("Potentiometer reading: ");
        Serial.println(potReading);
        potDegreesC = map(potReading, 0, 1023, 5, 35);
        Serial.println("Potentiometer in degrees: ");
        Serial.println(potDegreesC);
        if (tempDegreesC < potDegreesC)
        {
          digitalWrite(blueLEDPin, HIGH);
        }
        else
        {
          digitalWrite(blueLEDPin, LOW);
        }
        pirReading = digitalRead(pirPin);
        if (pirReading)
        {
          digitalWrite(bulbPin, HIGH);
          delay(5000);
          digitalWrite(bulbPin, LOW);
        }
      } 
                         
                       
  5. You now have a working security light which activates whenever something moves nearby.

  6. Create more variables to store the pin values for the force sensor, RGB LED, ultrasonic sensor and tilt sensor.

    Awgrym: Some of these components need more than one variable.


    • The RGB LED will require three different variables for the red, green and blue pins.

    • The ultrasonic sensor needs two variables. One for the trigger pin, the other for the echo pin.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Here is an example of the new code that needs adding. Remember, your variable names may vary. The complete program is available at the end of this level.

                        
      int forcePin = A1;
      int rgbRedLEDPin = 9;
      int rgbGreenLEDPin = 10;
      int rgbBlueLEDPin = 11;
      int tiltPin = 2;
      int ultraTrigPin = 7;
      int ultraEchoPin = 8;
                        
                      

  7. Now create the pin modes in the void setup() for these new components.


    • The force sensor is an analog input device.

    • The RGB LED is an output.

    • The tilt sensor is a digital input.

    • The trigger pin on the ultrasonic is an output, whilst the echo pin is an input.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Here is an example of the new code that needs adding. Remember, your variable names may vary. The complete program is available at the end of this level.

                        
      pinMode(forcePin, INPUT);
      pinMode(rgbRedLEDPin, OUTPUT);
      pinMode(rgbGreenLEDPin, OUTPUT);
      pinMode(rgbBlueLEDPin, OUTPUT);
      pinMode(tiltPin, INPUT);
      pinMode(ultraTrigPin, OUTPUT);
      pinMode(ultraEchoPin, INPUT);
                        
                      

  8. As we are using the ultrasonic, we need to add the below function to the program, like we did for Session Three's Lefel Aur exercises. This function produces an integer value of the distance (in cm) an object is from the ultrasonic sensor.

                    
      int readUltrasonic() 
      {
        digitalWrite(ultrasonicTrigger,LOW); // Clear the signal
        delayMicroseconds(2);
        digitalWrite(ultrasonicTrigger, HIGH); // Send out new signal
        delayMicroseconds(10);
        digitalWrite(ultrasonicTrigger,LOW); // Stop sending signal
    
        unsigned long duration = pulseIn(ultrasonicEcho, HIGH);
        int distance = duration /2 /29;
        Serial.print(distance);
        Serial.print("cm");
        return distance;
      }
                    
                  

    You will need to change the variables of ultrasonicTrigger and ultrasonicEcho in this code to match the variable names you created for the ultrasonic sensor's trigger and echo pins.

    Awgrym: As this is a function, have it in your code after the variables, but before the void setup() section

    .

    We've re-written the code provided to match the variable names in our answer program.

                      
      int readUltrasonic() 
      {
        digitalWrite(ultraTrigPin,LOW); // Clear the signal
        delayMicroseconds(2);
        digitalWrite(ultraTrigPin, HIGH); // Send out new signal
        delayMicroseconds(10);
        digitalWrite(ultraTrigPin,LOW); // Stop sending signal
    
        unsigned long duration = pulseIn(ultraEchoPin, HIGH);
        int distance = duration /2 /29;
        Serial.print(distance);
        Serial.print("cm");
        return distance;
      }
                      
                    

  9. Create a new function which we will be using to contain an alarm system program.

    Here is an example of the new code that needs adding. Remember, your function name may be different. The complete program is available at the end of this level.

                      
      void alarmSystem()
      {
    
      }
                      
                    

  10. Inside our alarm system function we want to write a program that increases the brightness of the red pin on the RGB LED as the force sensor reading increases.


    • You will need to create a variable to store your force sensor reading and another for the mapped value.

    • In you void loop(), use the serial monitor to work out the range for the force sensor. Remember, you already have lots of values being printed, so include some text. You may also need to add a delay to slow the serial monitor printouts.

    • Once you have the range of the force sensor, you can map them onto the red pin of the RGB LED.

    • To test your program, you will need to call the alarm system function inside the void loop().

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Here is an example of setting the necessary variables for this:

                        
      int forceReading = 0;
      int forceMapRed = 0;
                        
                      

    Here is the code needed to find the range of the force sensor. This needs to be removed after use.

                        
      forceReading = analogRead(forcePin);
      Serial.println("Force Reading: ");
      Serial.println(forceReading);
      delay(1000);
      alarmSystem(); //to test our new function's program.
                        
                      

    Here is the code for our alarm system function:

                        
      forceReading = analogRead(forcePin);
      forceMapRed = map (forceReading, 0, 466, 0, 255);
      analogWrite(rgbRedLEDPin, forceMapRed);
                        
                      

  11. Continuing with the program inside the alarm system function, add instructions for the blue light in the RGB LED to increase as an object moves closer to the ultrasonic sensor.


    • You do not need to create a variable for the ultrasonic reading as we already have a function for that.

    • Follow the same steps as we did for the force sensor mapping.

    • Remember, by setting the range of an LED the other way around (255 - 0) in a mapping, we get a brighter light for lower values.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.


    Here is an example of setting the necessary variables for this:

                          
      int ultraMapBlue = 0;
                          
                        

    Here is the code needed to find the range of the force sensor. This needs to be removed after use.

                          
      Serial.println("Ultrasonic Distance:");
      Serial.println(readUltrasonic());
      delay(1000);
      alarmSystem(); //to test our new function's program.
                          
                        

    Here is the code for our alarm system function:

                          
      ultraMapBlue = map (readUltrasonic(), 2, 331, 255, 0);
      analogWrite(rgbBlueLEDPin, ultraMapBlue);
                          
                        

  12. In our alarm system function we now need to add instructions that if the tilt sensor gets a positive reading (is tilted), the green light in the RGB LED turns on.


    • We are using the tilt sensor as a digital input like the PIR. This means you will need a Boolean variable to store the reading.

    • This does not require mapping as we are using digital read and write for this.

    • Make sure the light turns off when the condition is not being met.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    You will need to add a new variable for the tilt sensor reading.

                          
      bool tiltReading = 0;
                          
                        

    The program you'll need to add to you alarm system function. Variable names may differ to your own.

                          
      tiltReading = digitalRead(tiltPin);
      if (tiltReading)
      {
        digitalWrite(rgbGreenLEDPin, HIGH);
      }
      else
      {
        digitalWrite(rgbGreenLEDPin, LOW);
      }
                          
                        

  13. Currently, if more than one sensor of our alarm system triggers, we get a mixed colour from the RGB LED. Instead, we want the program to flash each colour one after the other. That way, the user can clearly see which sensors are triggered.


    • We need to add delays between each different sensor - 250ms should be enough.

    • Also, we need to set the pins back to zero before the next sensor.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    The alarm system function should now look like this:

                          
      void alarmSystem()
      {
        forceReading = analogRead(forcePin);
        forceMapRed = map (forceReading, 0, 466, 0, 255);
        analogWrite(rgbRedLEDPin, forceMapRed);
        delay(250);
        analogWrite(rgbRedLEDPin, 0);
        ultraMapBlue = map (readUltrasonic(), 2, 331, 255, 0);
        analogWrite(rgbBlueLEDPin, ultraMapBlue);
        delay(250);
        analogWrite(rgbBlueLEDPin, 0);
        tiltReading = digitalRead(tiltPin);
        if (tiltReading)
        {
          digitalWrite(rgbGreenLEDPin, HIGH);
        }
        else
        {
          digitalWrite(rgbGreenLEDPin, LOW);
        }
        delay(250);
        digitalWrite(rgbGreenLEDPin, LOW);
      }
                          
                        

  14. Although we have included been calling the alarm system function inside our void loop() during testing, we have yet to decide when it should be called. Create a new Boolean type variable called 'activate'. We shall use this to tell the program that the alarm system needs to run if activate is set to TRUE.


    • We don't have a physical input device to read for this variable. Instead, we will need to set the variable to 1 (TRUE) or 0 (FALSE) inside the void loop() to test.

    • Remember, this is a Boolean condition for the if-statement.

    Os ydych chi'n dal yn sownd, defnyddiwch y botwm ateb isod.

    Here are the sections of code that need adding to your program. Remember, the variable and function names might be different to your own.

                          
      bool activate = 0;
                          
                        

                          
      activate = 1;                      
      if (activate)
      {
        alarmSystem();
      }
                          
                        

  15. Hopefully, you've been constantly testing your program throughout these exercises. If not, it could be difficult to debug at such a late stage.


                        
      //C++ code
      //
      
      int ldrPin = A5;
      int redLEDPin = 3;
      int ldrReading = 0;
      int ldrMapValue = 0;
      int tempPin = A4;
      int potPin = A3;
      int greenLEDPin = 5;
      int blueLEDPin = 6;
      int tempReading = 0;
      int tempDegreesC = 0;
      int potReading = 0;
      int potDegreesC = 0;
      int pirPin = 4;
      int bulbPin = 12;  
      bool pirReading = 0;
      int forcePin = A1;
      int rgbRedLEDPin = 9;
      int rgbGreenLEDPin = 10;
      int rgbBlueLEDPin = 11;
      int tiltPin = 2;
      int ultraTrigPin = 7;
      int ultraEchoPin = 8;
      int forceReading = 0;
      int forceMapRed = 0;
      int ultraMapBlue = 0;
      bool tiltReading = 0;
      bool activate = 0;
    
      int readUltrasonic() 
      {
        digitalWrite(ultraTrigPin,LOW); // Clear the signal
        delayMicroseconds(2);
        digitalWrite(ultraTrigPin, HIGH); // Send out new signal
        delayMicroseconds(10);
        digitalWrite(ultraTrigPin,LOW); // Stop sending signal
    
        unsigned long duration = pulseIn(ultraEchoPin, HIGH);
        int distance = duration /2 /29;
        Serial.print(distance);
        Serial.print("cm");
        return distance;
      }
    
      void alarmSystem()
      {
        forceReading = analogRead(forcePin);
        forceMapRed = map (forceReading, 0, 466, 0, 255);
        analogWrite(rgbRedLEDPin, forceMapRed);
        delay(250);
        analogWrite(rgbRedLEDPin, 0);
        ultraMapBlue = map (readUltrasonic(), 2, 331, 255, 0);
        analogWrite(rgbBlueLEDPin, ultraMapBlue);
        delay(250);
        analogWrite(rgbBlueLEDPin, 0);
        tiltReading = digitalRead(tiltPin);
        if (tiltReading)
        {
          digitalWrite(rgbGreenLEDPin, HIGH);
        }
        else
        {
          digitalWrite(rgbGreenLEDPin, LOW);
        }
        delay(250);
        digitalWrite(rgbGreenLEDPin, LOW);
      }
    
      void setup ()
      {
        pinMode(ldrPin, INPUT);
        pinMode(redLEDPin, OUTPUT);
        Serial.begin(9600);
        pinMode(tempPin, INPUT);
        pinMode(potPin, INPUT);
        pinMode(greenLEDPin, OUTPUT);
        pinMode(blueLEDPin, OUTPUT);
        pinMode(pirPin, INPUT);
        pinMode(bulbPin, OUTPUT);
        pinMode(forcePin, INPUT);
        pinMode(rgbRedLEDPin, OUTPUT);
        pinMode(rgbGreenLEDPin, OUTPUT);
        pinMode(rgbBlueLEDPin, OUTPUT);
        pinMode(tiltPin, INPUT);
        pinMode(ultraTrigPin, OUTPUT);
        pinMode(ultraEchoPin, INPUT);
      }
    
      void loop ()
      {
        ldrReading = analogRead(ldrPin);
        Serial.println(ldrReading);
        ldrMapValue = map(ldrReading, 6, 679, 255, 0);
        analogWrite(redLEDPin, ldrMapValue);
        tempReading = analogRead(tempPin);
        Serial.println(tempReading);
        tempDegreesC = map(tempReading, 20, 358, -40, 125);
        if (tempDegreesC > 50)
        {
          digitalWrite(greenLEDPin, HIGH);
          delay(250);
          digitalWrite(greenLEDPin, LOW);
          delay(250);
        }
        else if (tempDegreesC > 20)
        {
          digitalWrite(greenLEDPin, HIGH);
        }
        else
        {
          digitalWrite(greenLEDPin, LOW);
        }
        potReading = analogRead(potPin);
        Serial.println("Potentiometer reading: ");
        Serial.println(potReading);
        potDegreesC = map(potReading, 0, 1023, 5, 35);
        Serial.println("Potentiometer in degrees: ");
        Serial.println(potDegreesC);
        if (tempDegreesC < potDegreesC)
        {
          digitalWrite(blueLEDPin, HIGH);
        }
        else
        {
          digitalWrite(blueLEDPin, LOW);
        }
        pirReading = digitalRead(pirPin);
        if (pirReading)
        {
          digitalWrite(bulbPin, HIGH);
          delay(5000);
          digitalWrite(bulbPin, LOW);
        }
        activate = 1;                      
        if (activate)
        {
          alarmSystem();
        }
      } 
                        
                      


Should you wish to continue working with this circuit and program, here are some additional ideas for you.