Skip to main content

Lab sketch: how it works and what goes wrong

The sketch for Labs 5c, 5d and 5e is on your lab sheet. This page explains the parts that matter and what to check when it does not work.

Wiring: temperature sensor on A0, ultrasonic sensor on D7, LCD on I2C (A4/A5). See the individual sensor pages.

The parts that matter​

  • Serial.begin(9600): the Pi must open the port at the same speed (9600), or it reads garbage.
  • The output format: the sketch prints Dist=42 and Temp=25.31 on separate lines, once per second. The Pi's Python code cuts off the first 5 characters (Dist= / Temp=) with [5:]. If you change the labels (for example to Distance=), the Python slicing must change too.
  • The order: distance first, then temperature. The lab's Python code assumes this order. See a safer version that checks the label instead.
  • delay(1000): one reading per second. A shorter delay means more rows in the database very quickly.
  • The temperature formula turns the analog reading (0-1023) into a resistance and then into degrees Celsius using the thermistor's B value (4275) and R0 (100k). You do not need to change it.

What goes wrong​

ProblemCause and fix
rgb_lcd.h: No such file or directoryThe Grove LCD library is not installed. Sketch → Include Library → Manage Libraries, search "Grove LCD RGB Backlight". Same for Ultrasonic.h ("Grove Ultrasonic Ranger").
Upload fails (avrdude: ser_open(): can't open device)Wrong board or port in Tools, or the Pi / Serial Monitor is holding the port. Close the Serial Monitor; if the Arduino is plugged into the Pi, stop the Python script first.
LCD lights up but shows nothingCheck the cable is in an I2C socket, not a digital one. Re-upload.
Temperature shows about -273The analog read is 0: the sensor is not on A0 or the cable is loose.
Distance is always 0 or a huge numberSensor not on D7, or nothing in front of it within range (about 3-350 cm).
Serial Monitor shows strange charactersSet the Serial Monitor speed to 9600 baud.
Values look right in the Serial Monitor but the Pi reads nothingClose the Serial Monitor: only one program can use the port.