In the previous blog post we learned how to setup and run Arduino IDE, saw the example programs and even wrote one by ourselves. Pretty good so far, I’d say! Now it’s time to put our knowledge into test and write actual program for the Lab from the scratch by ourselves!
In order to write a program we will follow a standard developer path: “Design, then build”. By “designing” I mean creating a meaningful concept of the program which will be later executed by the code in IDE (execution=”building”). Since Lab provides us with phototransistor, today we will build an automatic light controlling system utilizing its’ functions by fullest. How will it work you might ask? The answer is simple yet effective: when Lab is in place with low illuminance level, LED will automatically be powered. This is used in real world in Smart-House solutions nowadays.
So we designed an idea for our program, now it is time to build it. IMPORTANT: before connecting Lab to Arduino IDE, switch DIP switches in left bottom corner of the Lab (No.11 on the picture below)
So it will be that 1st switch is ON while 2nd is OFF. This will allow you to program Lab outside of RobboScratch (in Arduino IDE). Then connect Lab to PC, run IDE and do common revision: check COMs and select Arduino Nano in Tools:
Now we are all set up and ready to write some code!
Let me quickly explain what is happening here. We define our LED and sensor at void setup(). Since LED is attached to pin number 5 (digital) and light sensor is to A4 (analog), we write as it is. Remember, since light sensor is collecting data, we claim it as an output. In void loop() we write logical statement saying that “if illuminance level is less than (number) turn the lights on, otherwise keep it off”. To get this number, we need to read data from the sensors first. Serial.println(analogRead(A4)) prints the values of illuminance level after we press Ctrl+Shift+M hotkey (this hotkey is for PC, Mac users need to check the one working for you). You will see a window with a lot of numbers:
Those numbers represent the current illuminance level in your room. So if in my case it is around 200, I should put a value less than 200, however it might be different for you, so firstly check the values and then put it in logical statement. After everything is done, press “Upload” button.
Now it is time to test our function in the work! Turn off the light in your room and observe what is going on with LED. Since our light sensor is connected to pin A4, you may also just find it on the board (located on the left shield, No.10 on the picture) and block the light coming to it with finger.
This is the third blog post brought to you by ROBBO to help you to become a pro robot hacker. Learning has never been so interactive!