上QQ阅读APP看书,第一时间看更新
Raspberry Pi GPIO header
The following screenshot is a chart of the GPIO pins of the Raspberry Pi Zero. In this case, we will use the SPI configuration interface (SPI_MOSI, SPI_MISO, SPI_CLK, SPI_CE0_N
):
The following diagram shows the name of the pins of the MCP3008 chip that you connect to the Raspberry Pi:
The following image shows the temperature sensor:
You need to connect the following pins according to the next description:
- VDD to 3.3 volts
- VREF to 3.3 volts from the Raspberry Pi Zero
- Pin AGND to GND
- Pin CLK (clock) to GPIO11 of the Raspberry Pi
- DOUT to GPIO9
- Pin DIN to GPIO10
- Pin CS to GPIO8 and the pin
- Pin the MCP3008D GND to Ground
This connection is represented in the following figure:
The following image shows the connections of the sensor to the ADC MCP3008 and the Raspberry Pi:
Reading the data with a Python script
In the next section, you will create the MCP3008.py
file; you need to follow the next steps:
- Open the terminal on your Raspberry Pi Zero.
- Enter the interface in your Pi terminal.
- It's important to use
nano
before. - Type
sudo nano MCP3008.py
.
It will appear on the screen and we will describe the following lines:
- Import libraries:
import spidev1 import os1
- Open the SPI bus:
spi1 = spidev1.SpiDev1() spi1.open(0,0)
- Define the channels from the ADC MCP2008:
def ReadChannel1(channel1): adc1 = spi1.xfer2([1,(8+channel1)<<4,0]) data1 = ((adc1[1]&3) << 8) + adc1[2] return data1
- The function to convert volts is as follows:
def volts(data1,places1): volts1 = (data1 * 3.3) / float(1023) volts1 = round(volts1,places1) return volts1
- The function to convert temperature is as follows:
def Temp(data1,places1): temp1 = (data1 * 0.0032)*100 temp1 = round(temp1,places1) return temp1
- Define channels from the ADC:
channels = 0
- Define the reading time:
delay = 10
- The function to read the temperature is as follows:
while True: temp = Channels(temp) volts = Volts(temp1,2) temp = Temp(temp1,2)
- Print the results:
print"**********************************************" print("Temp : {} ({}V) {} degC".format(temp1,volts,temp))
- Wait every 5 seconds:
Time1.sleep(delay)
- Run the Python file using the following command:
sudo python MCP3008.py
- On the following screen, we can see the temperature, the ADC measurements, and the volts according to the temperature: