shedboy71
Compass
This module lets you access the built-in electronic compass. Before using, the compass should be calibrated, otherwise the readings may be wrong.
Warning:
Calibrating the compass will cause your program to pause until calibration is complete. Calibration consists of a little game to draw a circle on the LED display by rotating the device.
Functions
microbit.compass.calibrate()
Starts the calibration process. An instructive message will be scrolled to the user after which they will need to rotate the device in order to draw a circle on the LED display.
microbit.compass.is_calibrated()
Returns True if the compass has been successfully calibrated, and returns False otherwise.
microbit.compass.clear_calibration()
Undoes the calibration, making the compass uncalibrated again.
microbit.compass.get_x()
Gives the reading of the magnetic force on the x axis, as a positive or negative integer, depending on the direction of the force.
microbit.compass.get_y()
Gives the reading of the magnetic force on the x axis, as a positive or negative integer, depending on the direction of the force.
microbit.compass.get_z()
Gives the reading of the magnetic force on the x axis, as a positive or negative integer, depending on the direction of the force.
microbit.compass.heading()
Gives the compass heading, calculated from the above readings, as an integer in the range from 0 to 360, representing the angle in degrees, clockwise, with north as 0.
microbit.compass.get_field_strength()
Returns an integer indication of the magnitude of the magnetic field around the device.
Code
A python example written with the Mu editor
[codesyntax lang=”python”]
from microbit import * compass.calibrate() while True: bearing = compass.heading() print(bearing) sleep(100)
[/codesyntax]
Open the REPL to see the readings
Accelerometer
This object gives you access to the on-board accelerometer. The accelerometer also provides convenience functions for detecting gestures. The recognised gestures are: up, down, left, right, face up, face down, freefall, 3g, 6g, 8g, shake.
Functions
microbit.accelerometer.get_x()
Get the acceleration measurement in the x axis, as a positive or negative integer, depending on the direction.
microbit.accelerometer.get_y()
Get the acceleration measurement in the y axis, as a positive or negative integer, depending on the direction.
microbit.accelerometer.get_z()
Get the acceleration measurement in the z axis, as a positive or negative integer, depending on the direction.
microbit.accelerometer.get_values()
Get the acceleration measurements in all axes at once, as a three-element tuple of integers ordered as X, Y, Z.
microbit.accelerometer.current_gesture()
Return the name of the current gesture.
Note
MicroPython understands the following gesture names: “up”, “down”, “left”, “right”, “face up”, “face down”, “freefall”, “3g”, “6g”, “8g”, “shake”. Gestures are always represented as strings.
microbit.accelerometer.is_gesture(name)
Return True or False to indicate if the named gesture is currently active.
microbit.accelerometer.was_gesture(name)
Return True or False to indicate if the named gesture was active since the last call.
microbit.accelerometer.get_gestures()
Return a tuple of the gesture history. The most recent is listed last. Also clears the gesture history before returning.
Code
This is a python example which was written in the Mu editor
[codesyntax lang=”python”]
from microbit import * while True: if accelerometer.is_gesture("up"): display.show(Image.ARROW_S) elif accelerometer.is_gesture("right"): display.show(Image.ARROW_E) elif accelerometer.is_gesture("down"): display.show(Image.ARROW_N) elif accelerometer.is_gesture("left"): display.show(Image.ARROW_W) else: display.clear() sleep(20)
[/codesyntax]
Buttons
There are two buttons on the board, called button_a and button_b.
Attributes
button_a
A Button instance representing the left button.
button_b
A Button instance representing the right button.
Classes
class Button
Represents a button.
Note
This class is not actually available to the user, it is only used by the two button instances, which are provided already initialized.
is_pressed()
Returns True if the specified button button is pressed, and False otherwise.
was_pressed()
Returns True or False to indicate if the button was pressed since the device started or the last time this method was called.
get_presses()
Returns the running total of button presses, and resets this total to zero before returning.
Code
Here is an example written in python using the Mu editor
[codesyntax lang=”python”]
from microbit import * while True: if button_a.is_pressed(): display.show("A") elif button_b.is_pressed(): display.show("B") else: display.clear()
[/codesyntax]
Here is an example using the Block Editor
WARNING: Preprocessor macros, although tempting, can produce quite unexpected results if not done right. Always keep in mind that macros are textual substitutions done to your source code before anything is compiled. The compiler does not know anything about the macros and never gets to see them. This can produce obscure errors, amongst other negative effects. Prefer to use language features, if there are equivalent (In example use const int or enum instead of #defined constants).
That said, there are cases, where macros are very useful (see the debug macro below for an example).
The #define directive is used to define values or macros that are used by the preprocessor to manipulate the program source code before it is compiled. Because preprocessor definitions are substituted before the compiler acts on the source code, any errors that are introduced by #define are difficult to trace.
By convention, values defined using #define are named in uppercase. Although doing so is not a requirement, it is considered very bad practice to do otherwise. This allows the values to be easily identified when reading the source code.
Today, #define is primarily used to handle compiler and platform differences. E.g., a define might hold a constant which is the appropriate error code for a system call. The use of #define should thus be limited unless absolutely necessary; typedef statements and constant variables can often perform the same functions more safely.
In the Arduino world you commonly see #define used when you are setting up I/O pins for sensors, LEDs and other tasks. Lets look at an example
[codesyntax lang=”cpp”]
void setup() { pinMode(11, OUTPUT); //set the LED pin as an output pinMode(10, OUTPUT); //set the LED pin as an output pinMode(9, OUTPUT); //set the LED pin as an output }
[/codesyntax]
Then in the loop you may have
digitalWrite(11, HIGH); // red led off
The code above is perfectly valid and will work but the problem is that it’s not overly clear what these are used for and if you had numerous pins used it could quickly get confusing. Instead you could do the following
[codesyntax lang=”cpp”]
#define redled 11 #define blueled 10 #define greenled 9 void setup() { pinMode(redled, OUTPUT); //set the LED pin as an output pinMode(blueled, OUTPUT); //set the LED pin as an output pinMode(greenled, OUTPUT); //set the LED pin as an output }
[/codesyntax]
Then in the loop you may have
digitalWrite(redled, HIGH); // red led off
That looks a lot better to me
When we create a function, it must be given a name. The naming convention for functions is the same as for variables:
•The function name can be made up of alphanumeric characters (A to Z; a to z; 0 to 9) and the underscore (_).
•The function name may not start with a number
•A function name must not be used that is the same as a language keyword or existing function.
A function must have a return type. If teh example function does not return anything, it will have a return type of void.
The function body is made up of a variety of statements placed between braces {}.
1) each function must have a unique name,
2) the function name is followed by parentheses ()
3) functions have a return type, e.g. void,
4) the body of a function is enclosed in opening and closing braces {}.
To call the function, you use the function name followed by opening and closing parentheses and then put a semi colon after it.
There are advantages of using functions is that they avoid having to write the same code over and over again. Every time you call a function, we are just reusing code that has been written once.
If you were to write code that say performed the same task 5 times then if you wished to update this for some reason you would have to modify the code in 5 places but if you were to use a function and call it 5 times then all you have to do is modify the function. Functions can be used to break a sketch up into pieces which make it easier to understand.
We are using the following circuit in the example later
We will take some of the code we created in previous tutorials and adapt this to use functions instead
[codesyntax lang=”cpp”]
int redled = 11; int blueled = 10; int greenled = 9; void setup() { pinMode(redled, OUTPUT); //set the LED pin as an output pinMode(blueled, OUTPUT); //set the LED pin as an output pinMode(greenled, OUTPUT); //set the LED pin as an output } void loop() { int i = 1; AllOff(); delay(1000); while(i<=3) { switch (i) { case 1: RedOn(); delay(1000); break; case 2: BlueOn(); delay(1000); break; case 3: GreenOn(); delay(1000); break; default: break; } i++; } } void AllOff() { digitalWrite(redled, HIGH); // red led off digitalWrite(blueled, HIGH); //blue led off digitalWrite(greenled, HIGH); //green led off } void RedOn() { digitalWrite(redled, LOW); // red led on digitalWrite(blueled, HIGH); //blue led off digitalWrite(greenled, HIGH); //green led off } void BlueOn() { digitalWrite(redled, HIGH); // red led off digitalWrite(blueled, LOW); //blue led on digitalWrite(greenled, HIGH); //green led off } void GreenOn() { digitalWrite(redled, HIGH); // red led off digitalWrite(blueled, HIGH); //blue led off digitalWrite(greenled, LOW); //green led on }
[/codesyntax]
The most basic Arduino sketch consists of two functions called setup() and loop(). The Arduino IDE once installed has a basic example that shows this. Open the Arduino IDE and select File → Examples → 01.Basics → BareMinimum to see the following in the IDE
[codesyntax lang=”cpp”]
void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: }
[/codesyntax]
The setup() function is called when a sketch starts. Use it to initialise variables, pins, start using libraries, etc. The setup function will only run once, after each power up or reset of the Arduino board.
Statements in the loop() function will run continuously from top to bottom and then back to the top. Lets you had 2 statements in your loop(), statement 1 would run first and then statement 2, once statement 2 had completed you would go back to statement 1 again and so on.
Code example
[codesyntax lang=”cpp”]
void setup() { Serial.begin(9600); Serial.println("*** We are in the setup loop ***"); delay(2000); } void loop() { Serial.println("Now in main loop about to pause for 2 seconds."); delay(2000); Serial.println("This would be a statement or function"); delay(2000); Serial.println("Arduino now at bottom of main loop."); }
[/codesyntax]
Open the serial monitor and you should see the following, imagine these were different statements or functions that were running
*** We are in the setup loop ***
Now in main loop about to pause for 2 seconds.
This would be a statement or function
Arduino now at bottom of main loop.
Now in main loop about to pause for 2 seconds.
This would be a statement or function
Arduino now at bottom of main loop.
Now in main loop about to pause for 2 seconds.
This would be a statement or function
Arduino now at bottom of main loop.
Now in main loop about to pause for 2 seconds.
This would be a statement or function
Arduino now at bottom of main loop.
Now in main loop about to pause for 2 seconds.
This would be a statement or function
Arduino now at bottom of main loop.
As you can see the serial output in the setup() loop ran once and the other serial output will keep running and looping
An if statement can be followed by an optional else statement, which executes when the expression is false.
Syntax
The syntax of an if…else statement is
[codesyntax lang=”cpp”]
if(expression) { /* statement(s) will execute if the expression is true */ } else { /* statement(s) will execute if the expression is false */ }
[/codesyntax]
If the expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed.
else can proceed another if test, so that multiple, mutually exclusive tests can be run at the same time.
Each test will proceed to the next one until a true test is encountered. When a true test is found, its associated block of code is run, and the program then skips to the line following the entire if/else construction. If no test proves to be true, the default else block is executed, if one is present, and sets the default behavior.
Note that an else if block may be used with or without a terminating else block and vice versa. An unlimited number of such else if branches is allowed.
Lets look at some examples
Code
[codesyntax lang=”cpp”]
void setup() { int i = 1; Serial.begin(9600); while(i<=10) { if(i >=5 ) { Serial.print("if (true) = "); Serial.println(i); } else { Serial.print("else (false) = "); Serial.println(i); } i++; } } void loop() { }
[/codesyntax]
Open the serial monitor and you will see the following
else (false) = 1
else (false) = 2
else (false) = 3
else (false) = 4
if (true) = 5
if (true) = 6
if (true) = 7
if (true) = 8
if (true) = 9
if (true) = 10
Lets look at en if / else if / else example
[codesyntax lang=”cpp”]
void setup() { int i = 1; Serial.begin(9600); while(i<=30) { if(i >=1 && i <=10 ) //runs from 5 to 10 { Serial.print("if = "); Serial.println(i); } else if (i >=11 && i<=20) //runs from 11 to 20 { Serial.print("elseif = "); Serial.println(i); } else { Serial.print("else = "); // runs from 1 to 4 Serial.println(i); } i++; } } void loop() { }
[/codesyntax]
Open the serial monitor window
if = 1
if = 2
if = 3
if = 4
if = 5
if = 6
if = 7
if = 8
if = 9
if = 10
elseif = 11
elseif = 12
elseif = 13
elseif = 14
elseif = 15
elseif = 16
elseif = 17
elseif = 18
elseif = 19
elseif = 20
else = 21
else = 22
else = 23
else = 24
else = 25
else = 26
else = 27
else = 28
else = 29
else = 30
if, which is used in conjunction with a comparison operator, tests whether a certain condition has been reached, such as an input being above a certain number.
If the expression evaluates to true, then the block of code inside the ‘if’ statement will be executed.
The syntax of the if statement is as follows:
if (expression > 50)
{
// do something here
}
The program tests to see if someVariable is greater than 50. If it is, the program takes a particular action. Put another way, if the statement in parentheses is true, the statements inside the brackets are run. If not, the program skips over the code.
The brackets may be omitted after an if statement. If this is done, the next line (defined by the semicolon) becomes the only conditional statement. The following examples are all valid ways of writing an if statement
[codesyntax lang=”cpp”]
if (x > 120) digitalWrite(LEDpin, HIGH);
if (x > 120)
digitalWrite(LEDpin, HIGH);
if (x > 120){ digitalWrite(LEDpin, HIGH); }
if (x > 120){
digitalWrite(LEDpin1, HIGH);
digitalWrite(LEDpin2, HIGH);
}
[/codesyntax]
I prefer the following approach, even if there was only statement to be executed, its only best to be consistent and use the same approach in all of your code.
[codesyntax lang=”cpp”]
if (x > 120)
{
digitalWrite(LEDpin1, HIGH);
}
[/codesyntax]
Code Examples
Lets look at a code example, this uses a while loop and will run 10 times. In our if statement we will only run the statements in the brackets which output via the serial monitor if the value of i is less than or equal to 5
[codesyntax lang=”cpp”]
void setup()
{
int i = 1;
Serial.begin(9600);
while(i<=10)
{
if(i <=5 )
{
Serial.print(“i = “);
Serial.println(i);
}
i++;
}
}
void loop() {
}
[/codesyntax]
In the serial monitor you will see the following
i = 1
i = 2
i = 3
i = 4
i = 5
You can use other comparison operators as well. Change the code to the following and run again. This one will only run the statements in the brackets if the value of i is equal to 5
[codesyntax lang=”cpp”]
void setup()
{
int i = 1;
Serial.begin(9600);
while(i<=10)
{
if(i ==5 )
{
Serial.print(“i = “);
Serial.println(i);
}
i++;
}
}
void loop() {
}
[/codesyntax]
This time in the serial monitor window you will see the following
i = 5
Now change the code to the following and run again. This one will only run the statements in the brackets if the value of i is greatr than or equal to 5
[codesyntax lang=”cpp”]
void setup()
{
int i = 1;
Serial.begin(9600);
while(i<=10)
{
if(i >=5 )
{
Serial.print(“i = “);
Serial.println(i);
}
i++;
}
}
void loop() {
}
[/codesyntax]
This time in the serial monitor window you will see the following
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10
We have shown you some comparison operators above, here is a list of comparison operators you can use.
x == y (x is equal to y)
x != y (x is not equal to y)
x < y (x is less than y)
x > y (x is greater than y)
x <= y (x is less than or equal to y)
x >= y (x is greater than or equal to y)
Later on you will see that you can also use other operators such as boolean operators as well, here’s a taster
[codesyntax lang=”cpp”]
if (digitalRead(2) == HIGH && digitalRead(3) == HIGH)
{
//statements to be run here
}
[/codesyntax]
The do loop works in the same manner as the while loop, with one difference in that the condition is tested at the end of the loop, so the do loop will always run at least once even if the test expression was false.
The do while loop is shown below.
do {
Statement 1
Statement 2
…
} while (test expression);
Code Examples
OK, here is the standard do while equivalent of the previous for loop and while loop examples
[codesyntax lang=”cpp”]
void setup()
{
int i = 1;
Serial.begin(9600);
do
{
Serial.print(“i = “);
Serial.println(i);
i++;
}while(i<=10);
}
void loop() {
}
[/codesyntax]
Open the serial monitor window and you will see the following, looks good
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10
Just for fun, lets remove the i++ from the code above and run again and look at the serial monitor window
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
i = 1
As you can see because the varable wasn’t incremented then the test expression will always be true , i will always be less than or equal to 10. Infinite loop.
Back to the RGB led again
Now lets repeat the fading an led and flashing an led 10 times examples
[codesyntax lang=”cpp”]
//change the brightness of an LED
int redled = 11;
int i =1;
void setup()
{
pinMode(redled, OUTPUT); //set the LED pin as an output
Serial.begin(9600);
do{
Serial.print(“loop = “);
Serial.println(i);
analogWrite(redled, i);
delay(10);
i++;
}while(i<=255);
}
void loop()
{
}
[/codesyntax]
Now flash the LED 10 times again
[codesyntax lang=”cpp”]
//flash the red led of the RGB led 10 times
int redled = 11;
int i = 1; //init the variable
void setup()
{
Serial.begin(9600);
pinMode(redled, OUTPUT); //set the LED pin as an output
//this will run 10 times
do
{
Serial.print(“loop = “);
Serial.println(i);
digitalWrite(redled, LOW); // led on
delay(500);
digitalWrite(redled, HIGH); //led off
delay(500);
i++; //dont forget this
}while(i<=10);
}
void loop()
{
}
[/codesyntax]
while loops will loop continuously, and infinitely, until the expression inside the parenthesis, () becomes false. Something must change the tested variable, or the while loop will never exit. This could be in your code, such as an incremented variable, or an external condition, such as testing a sensor.
The while loop has a structure as follows:
while (test expression) {
Statement 1
Statement 2
…
}
test expression – a (boolean) C statement that evaluates to true or false
Lets look at some examples
Code Examples
[codesyntax lang=”cpp”]
void setup() { int i = 1; Serial.begin(9600); while(i<=10) { Serial.print("i = "); Serial.println(i); i++; } } void loop() { }
[/codesyntax]
Open the serial monitor and you should see the following
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10
As you can see we set the variable to 1, we then test whether the variable is less than or equal to 10. If it is not then the statements will run in the brackets which is basically outputing this value via the serial monitor. Important part is that we increment the variable using i++.
This increments the value of the variable by 1, this is the same incidentally as writing i = i + 1; which is sometimes used as well. Forgetting this would cause the while loop to always run – an infinite loop. You can remove the i++ and see what happens.
Now back to the RGB led example
Now lets fade that led again like in the for loop example
[codesyntax lang=”cpp”]
//change the brightness of an LED int redled = 11; int i =0; void setup() { pinMode(redled, OUTPUT); //set the LED pin as an output Serial.begin(9600); while(i<=255) { Serial.print("loop = "); Serial.println(i); analogWrite(redled, i); delay(10); i++; } } void loop() { }
[/codesyntax]
Lets flash that red led 10 times again
[codesyntax lang=”cpp”]
//flash the red led of the RGB led 10 times int redled = 11; int i = 1; //init the variable void setup() { Serial.begin(9600); pinMode(redled, OUTPUT); //set the LED pin as an output //this will run 10 times while(i<=10) { Serial.print("loop = "); Serial.println(i); digitalWrite(redled, LOW); // led on delay(500); digitalWrite(redled, HIGH); //led off delay(500); i++; //dont forget this } } void loop() { }
[/codesyntax]
Arduino for beginners : for loops
The for statement is used to repeat a block of statements enclosed in curly braces. An increment counter is usually used to increment and terminate the loop. The for statement is useful for any repetitive operation, and is often used in combination with arrays to operate on collections of data/pins.
There are three parts to the for loop:
for (initialization; condition; increment)
{
//statement(s);
}
The initialization happens first and exactly once. Each time through the loop, the condition is tested; if it’s true, the statement block, and the increment is executed, then the condition is tested again. When the condition becomes false, the loop ends.
Code Examples
[codesyntax lang=”cpp”]
void setup()
{
int i;
Serial.begin(9600);
for (i = 0; i < 10; i++)
{
Serial.print(“i = “);
Serial.println(i);
}
}
void loop() {
}
[/codesyntax]
Open the serial monitor and you should see the following output
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
In these examples we will connect an RGB led to our Arduino, this will be used in several examples. Here is a breadboard layout and schematic, we used a common anode type
We will only use the red led of the RGB led in these examples
[codesyntax lang=”cpp”]
//change the brightness of an LED
int redled = 11;
void setup()
{
pinMode(redled, OUTPUT); //set the LED pin as an output
Serial.begin(9600);
for (int i=1; i <= 255; i++)
{
Serial.println(“loop = “);
Serial.println(i);
analogWrite(redled, i);
delay(10);
}
}
void loop()
{
}
[/codesyntax]
As this is in the setup() it will only run once, changing this to the loop() will mean the led continuously runs through the for loop and fading the LED
[codesyntax lang=”cpp”]
//change the brightness of an LED
int redled = 11;
void setup()
{
pinMode(redled, OUTPUT); //set the LED pin as an output
}
void loop()
{
for (int i=1; i <= 255; i++)
{
analogWrite(redled, i);
delay(10);
}
}
[/codesyntax]
In this example we will flash the red of an RGB led on and off 10 times
[codesyntax lang=”cpp”]
//flash the red led of the RGB led 10 times int redled = 11; void setup() { Serial.begin(9600); pinMode(redled, OUTPUT); //set the LED pin as an output //this will run 10 times for (int i=1; i <= 10; i++) { Serial.print("loop = "); Serial.println(i); digitalWrite(redled, LOW); // led on delay(500); digitalWrite(redled, HIGH); //led off delay(500); } } void loop() { }
[/codesyntax]
Here we show you how to create a custom image on the led matrix, we use the Mu editor
[codesyntax lang=”python”]
from microbit import *
im = Image(‘99999:90009:90009:90009:99999:’)
display.show(im)
[/codesyntax]
You can vary the brightness by changing the value of the digits from 0 – 9.
[codesyntax lang=”python”]
from microbit import *
im = Image(‘99999:96369:96369:96369:99999:’)
display.show(im)
[/codesyntax]
A simple animation example
[codesyntax lang=”python”]
from microbit import *
imgs = [
Image(‘90000:00000:00000:00000:00000:’),
Image(‘00000:09000:00000:00000:00000:’),
Image(‘00000:00000:00900:00000:00000:’),
Image(‘00000:00000:00000:00090:00000:’),
Image(‘00000:00000:00000:00000:00009:’)
]
display.show(imgs, delay=1000,loop=True)
[/codesyntax]
You can also set a pixel and move it around
[codesyntax lang=”python”]
from microbit import * img = Image('00000:00000:00900:00000:00000:') display.show(img) sleep(1000) while True: img = img.shift_up(2) display.show(img) sleep(1000) img = img.shift_right(2) display.show(img) sleep(1000) img = img.shift_down(2) display.show(img) sleep(1000) img = img.shift_left(2) display.show(img) sleep(1000)
[/codesyntax]
shift_left(n)
Return a new image created by shifting the picture left by n columns.
shift_right(n)
Same as image.shift_left(-n).
shift_up(n)
Return a new image created by shifting the picture up by n rows.
shift_down(n)
Same as image.shift_up(-n).
The MCP9808 digital temperature sensor converts temperatures between -20°C and +100°C to a digital word with ±0.5°C (max.) accuracy. The MCP9808 comes with user-programmable registers that provide flexibility for temperature sensing applications. The registers allow user-selectable settings such as Shutdown or low-power modes and the specification of temperature Event and Critical output boundaries.
When the temperature changes beyond the specified boundary limits, the MCP9808 outputs an Event signal. The user has the option of setting the event output signal polarity as an active-low or active-high comparator output for thermostat operation, or as temperature event interrupt output for microprocessor-based systems. The event output can also be configured as a Critical temperature output. This sensor has an industry standard 2-wire, SMBus and Standard I2C™Compatible compatible (100kHz/400kHz bus clock) serial interface, allowing up to eight sensors to be controlled in a single serial bus.
Features
Accuracy:
±0.25°C (typical) from -40°C to +125°C
±0.5°C (maximum) from -20°C to +100°C
User Selectable Measurement Resolution:
0.5°C, 0.25°C, 0.125°C, 0.0625°C
User Programmable Temperature Limits:
Temperature Window Limit
Critical Temperature Limit
User Programmable Temperature Alert Output
Operating Voltage Range: 2.7V to 5.5V
More details about the sensor at http://www.microchip.com/wwwproducts/en/MCP9808
This typically comes in a breakout such as the one in the breakout below
Code
You will need the adafruit MCP9808 library which is available at https://github.com/adafruit/Adafruit_MCP9808_Library/archive/master.zip
[codesyntax lang=”cpp”]
#include <Wire.h> #include "Adafruit_MCP9808.h" // Create the MCP9808 temperature sensor object Adafruit_MCP9808 tempsensor = Adafruit_MCP9808(); void setup() { Serial.begin(9600); if (!tempsensor.begin()) { Serial.println("Couldn't find MCP9808!"); while (1); } } void loop() { // Read and print out the temperature, then convert to *F float c = tempsensor.readTempC(); float f = c * 9.0 / 5.0 + 32; Serial.print("Temp: "); Serial.print(c); Serial.print(" C\t"); Serial.print(f); Serial.println(" F"); delay(250); tempsensor.shutdown_wake(1); delay(2000); tempsensor.shutdown_wake(0); }
[/codesyntax]
Results
Open the serial monitor and you should see something like this
Temp: 21.69 C 71.04 F
Temp: 21.62 C 70.93 F
Temp: 24.50 C 76.10 F
Temp: 25.06 C 77.11 F
Temp: 25.37 C 77.68 F
Temp: 25.56 C 78.01 F
Temp: 24.25 C 75.65 F
Temp: 23.87 C 74.97 F
Links
Adafruit MCP9808 High Accuracy I2C Temperature Sensor Breakout Board [ADA1782]