Get in touch

Donate

Category: IOT

This the the third part of tutorial series React Native Smart Switch App. If you have directly reached to this part of tutorial then you can check the previous part here. In the previous part we created hardware ( using Arduino) and software (i.e. Mobile App) for turning LED light on and off. In this part we will be actually building our virtual switch and App to control it.

Our Arduino connection will remain same as previous part of tutorial but we will make changes to the code. Update the old code with the code below :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

intflag=0;

unsignedlonglightStartTime;

unsignedlongcurrentTime;

unsignedlonginterval=5000;

voidsetup(){

// put your setup code here, to run once:

pinMode(LED_BUILTIN,OUTPUT);

Serial.begin(9600);

}

voidloop(){

// put your main code here, to run repeatedly:

if(Serial.available()>0){

chardata=Serial.read();

switch(data){

case'A':switchOn(5);

break;

case'B':switchOn(10);

break;

case'C':switchOn(15);

break;

case'D':switchOn(20);

break;

case'E':switchOn(25);

break;

case'F':switchOn(30);

break;

}

}

if(flag==1){

currentTime=millis();

if(lightStartTime+interval<currentTime){

digitalWrite(LED_BUILTIN,LOW);

flag=0;

}

}

}

voidswitchOn(unsignedlongtimePeriod)

{

digitalWrite(LED_BUILTIN,HIGH);

lightStartTime=millis();

flag=1;

interval=timePeriod*1000;

}

In the above code, above code we are first setting the pin 13 as output pin and communication speed as 9600 baud (bps). In the loop we are cheking if some data is there and reading it. If the data code is ‘A’ then we are setting time interval to 5 seconds, changing flag value to 1, turning on LED connected to pin 13 and saving the LED lit/glow up time to ‘lightStartTime’ variable. Next, we are cheking if flag value is 1 i.e. led is turned on and current time is more than LED lit/glow up time then we are turning LED off.

In the above code, When the user taps voice button and gives a voice command then voice is converted to text using Dialogflow API. Next we check the important keywords of the command like ‘switch’, ‘on’ and no. of seconds. If the right keyword is there then we match the no. of seconds with specific code and transmit the code to Arduino device. Finally our Arduino device catches the code using bluetooth and turn on LED light for specific time period.