If you have been following these lessons by this time you should be fairly comfortable with the Linux operating system, and you should know enough commands to do what you need to from the terminal window and command line. We now want to move forward to actually start doing things with the Pi. In order to do this, we will be using the Python programming language.
Tag Archives: Python
Python with Arduino LESSON 17: Sending and Receiving Data Over Ethernet
In LESSON 16 we showed a simple Client Server model that allows us to send strings between Python running on a PC and the arduino over Ethernet. That lesson simply passed strings back and forth to show a very basic Server on Arduino, and Python acting as the Client. In this lesson we show a more practical example, with the Arduino connected to an Adafruit BMP180 Pressure Sensor. In order to complete this lesson, you will need an Arduino, an Ethernet Shield, and the Pressure Sensor. If you do not have this particular pressure sensor, you can probably follow along in the lesson using whatever sensor you have that is of interest. The video will take you through the tutorial step-by-step, and then the code we developed is shown below.
The key issue in getting this project to work is to get your mac address and IP address from your router or network. If you are at school, simply speak to your network administrator, and he will help you get an IP address for your arduino. If you are at home, you will need to connect to your router from a browser, and configure it to assign an IP address and agree on a mac address for your arduino. Some arduino Ethernet shields have a sticker with a mac address. If your Ethernet shield has a sticker with mac address, use that one. If it does not, you will need to come up with a unique mac address. There are thousands of possible routers and networks out there, so I can not help you with that part. But if you look in the router documentation, you should be able to get the IP address and mac address worked out. The arduino itself does not have a hard wired mac address, but you set the mac address in the arduino software, and the IP address as well. The key thing is that the mac address is unique on your network, and the router and arduino agree on the IP address and mac address. If you have a clearer way to explain this, please leave a comment below.
This is the server side software to run on the arduino. Again, you should use a suitable IP address and mac address for your network. Do not think you can just copy the ones I use in 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | #include <Ethernet.h> //Load Ethernet Library #include <EthernetUdp.h> //Load the Udp Library #include <SPI.h> //Load SPI Library #include "Wire.h" //imports the wire library #include "Adafruit_BMP085.h" // import the Pressure/Temperature sensor library Adafruit_BMP085 mySensor; //Create a sensor object float tempC; //Declare variable for Temp in C float tempF; //Declare variable for Temp in F float Pressure; //Declare a variable for Pressure byte mac[] ={ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE}; //Assign mac address IPAddress ip(10, 1, 15, 243); //Assign the IP Adress unsigned int localPort = 5000; // Assign a port to talk over char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //dimensian a char array to hold our data packet String datReq; //String for our data int packetSize; //Size of the packet EthernetUDP Udp; // Create a UDP Object void setup() { Serial.begin(9600); //Initialize Serial Port Ethernet.begin( mac, ip); //Inialize the Ethernet Udp.begin(localPort); //Initialize Udp delay(1500); //delay mySensor.begin(); //initialize pressure-temp sensor } void loop() { packetSize =Udp.parsePacket(); //Reads the packet size if(packetSize>0) { //if packetSize is >0, that means someone has sent a request Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); //Read the data request String datReq(packetBuffer); //Convert char array packetBuffer into a string called datReq if (datReq =="Temperature") { //Do the following if Temperature is requested tempC = mySensor.readTemperature(); //Read the temperature tempF = tempC*1.8 + 32; //Convert temp to F Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize packet send Udp.print(tempF); //Send the temperature data Udp.endPacket(); //End the packet } if (datReq== "Pressure") { //Do the following if Pressure is requested Pressure=mySensor.readPressure(); //read the pressure Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize packet send Udp.print(Pressure); //Send the Pressure data Udp.endPacket(); //End the packet } } memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE); //clear out the packetBuffer array } |
Once you have this on your arduino, and the arduino connected to the internet via an Ethernet cable, you can test by opening a command line in Windows. Then ping the address you have assigned to the Arduino. If it pings correctly and you get a reply, you are ready to develop the Python code. The Python will be the client. It will send the requests to the Arduino, and the Arduino will respond with data. Since our circuit can measure pressure or temperature, you can request either of those. When the arduino receives a request for temperature, it will go out, make the temperature measurement and then return the data to Python. Similarly, if you request Pressure the arduino will read the request, will make the Pressure measurement, and then return pressure reading to the client (Python).
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 | from socket import * import time address= ( '10.1.15.243', 5000) #define server IP and port client_socket =socket(AF_INET, SOCK_DGRAM) #Set up the Socket client_socket.settimeout(1) #Only wait 1 second for a response while(1): data = "Temperature" #Set data request to Temperature client_socket.sendto( data, address) #Send the data request try: rec_data, addr = client_socket.recvfrom(2048) #Read response from arduino temp = float(rec_data) #Convert string rec_data to float temp print "The Measured Temperature is ", temp, " degrees F." # Print the result except: pass time.sleep(2) #delay before sending next command data = "Pressure" #Set data request to Pressure client_socket.sendto( data, address) #Send the data request try: rec_data, addr = client_socket.recvfrom(2048) #Read response from arduino Pressure = float(rec_data) #Convert string rec_data to float temp print "The Measured Pressure is ", Pressure, " Pa." # Print the result except: pass time.sleep(2) #delay before sending next command print "" |
This python code will request Temperature, will then read the response, and then will print the data. It then requests Pressure, reads the response, and then prints it. If you look at our earlier lessons you can see graphical techniques to visually present the data. The hard part is getting the data passed back and forth, which we show how to do in this lesson.
Python with Arduino LESSON 16: Simple Client Server Configuration over Ethernet
In the previous lessons we have seen that powerful analytic and graphic programs can be written that allow data taken from the arduino to be displayed on a PC via Python. We have shown how the arduino can be connected to a PC by either a serial cable or Xbee radios. To fully unleash the power of the arduino, it can be set up as a server, and connected to a network via Ethernet. In this lesson, we will show how to set the arduino up as a server which is controlled and queried by clients on PC’s on the same network. In order to complete this tutorial, you will need an Arduino Uno and an Ethernet shield. The Ethernet Shield is a relatively expensive component, but I suggest getting an authentic arduino made shield, as I have had poor results from the cheap knock offs. Understand that this lesson is intended for High School students to show them a simple technique for connecting the arduino to a network. It is not an exhaustive treatise on Ethernet communication. The goal is to provide a simple protocol which should allow you to get your arduino talking over Ethernet. It requires that you already know, or can figure out how to assign a mac address and IP address in your router. Some arduino Ethernet shields have a sticker with a mac address. If your Ethernet shield has a sticker with mac address, use that one. If it does not, you will need to come up with a unique mac address. If you are at school, the network administrator can help you get the router configured. I can not provide support in getting this to work on your network, as there are many variables. The techniques provided in this tutorial should work for most networks. This tutorial does not present the most efficient or elegant solution, but the goal is a simple protocol for people just getting started. The video below gives a step-by-step demonstration of setting up the arduino as a server, and Python on a PC as the client. It uses UDP protocol to transfer data packets.
In order to get the arduino to work over Ethernet, you must first assign an IP address to the arduino in your router. If you just plug the arduino with shield into the network, your router might assign an IP and report a mac address. If this is the case, you need to have the router assign those addresses permanently to the arduino. The bottom line is that the IP address and mac address you identify in the arduino code must match the IP address and mac address assigned in the router. I can not provide any additional help on that issue as there are so many different possible networks. You have to figure out how to do that.
Once you have the IP address and mac address sorted out, you will need to set up the arduino as a server. The video above explains how to do this, and results in this code. Note that your IP address and mac address must be set to a suitable configuration for your router and network. The numbers I use in this code would not work for your network.
This is the code developed in the video to set the arduino up:
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 | #include <Ethernet.h> //Load Ethernet Library #include <EthernetUdp.h> //Load UDP Library #include <SPI.h> //Load the SPI Library byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE}; //Assign a mac address IPAddress ip(10, 1, 15, 243); //Assign my IP adress unsigned int localPort = 5000; //Assign a Port to talk over char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; String datReq; //String for our data int packetSize; //Size of Packet EthernetUDP Udp; //Define UDP Object void setup() { Serial.begin(9600); //Turn on Serial Port Ethernet.begin(mac, ip); //Initialize Ethernet Udp.begin(localPort); //Initialize Udp delay(1500); //delay } void loop() { packetSize = Udp.parsePacket(); //Read theh packetSize if(packetSize>0){ //Check to see if a request is present Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); //Reading the data request on the Udp String datReq(packetBuffer); //Convert packetBuffer array to string datReq if (datReq =="Red") { //See if Red was requested Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize Packet send Udp.print("You are Asking for Red"); //Send string back to client Udp.endPacket(); //Packet has been sent } if (datReq =="Green") { //See if Green was requested Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize Packet send Udp.print("You are Asking for Green"); //Send string back to client Udp.endPacket(); //Packet has been sent } if (datReq =="Blue") { //See if Red was requested Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); //Initialize Packet send Udp.print("You are Asking for Blue"); //Send string back to client Udp.endPacket(); //Packet has been sent } } memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE); } |
Once you have this code in your arduino, ping the IP address of the arduino from your PC cmd line. Make sure your PC can talk to the arduino by successfully pinging it. If you get an error while you are trying to ping the arduino, you will have to stop and get figured out what is wrong. There is no reason to proceed with the lesson until you can successfully ping the arduino.
Once you can ping the arduino, you are ready to set up a client in Python. The code below is what we developed in the video. You will need to watch the video in order to understand the code. Also note, that the IP address in the code below is the IP address of the Arduino, NOT the PC. You should set this to whatever IP address is of YOUR arduino.
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 | from socket import * import time address = ( '10.1.15.243', 5000) #Defind who you are talking to (must match arduino IP and port) client_socket = socket(AF_INET, SOCK_DGRAM) #Set Up the Socket client_socket.settimeout(1) #only wait 1 second for a resonse while(1): #Main Loop data = "Blue" #Set data to Blue Command client_socket.sendto(data, address) #send command to arduino try: rec_data, addr = client_socket.recvfrom(2048) #Read response from arduino print rec_data #Print the response from Arduino except: pass time.sleep(2) #delay before sending next command data = "Red" #Set data to Blue Command client_socket.sendto(data, address) #send command to arduino try: rec_data, addr = client_socket.recvfrom(2048) #Read response from arduino print rec_data #Print the response from Arduino except: pass time.sleep(2) #delay before sending next command data = "Green" #Set data to Blue Command client_socket.sendto(data, address) #send command to arduino try: rec_data, addr = client_socket.recvfrom(2048) #Read response from arduino print rec_data #Print the response from Arduino except: pass time.sleep(2) #delay before sending next command |
Again, this is a bit of a tricky thing to set up, but if you get the PC successfully pinging the arduino, everything else should be straightforward.
Python with Arduino LESSON 15: Configuring and Using the Xbee Radios
This lesson describes how to program the Xbee Series 1 radios. It will work with either the standard Series 1 (S1) or the Series 1 Pro models. The Pro radios are higher power and will give greater range, but they cost more. The radios are configured using X-CTU software, which can be downloaded here. The video gives step by step instructions on how to configure and use the radios to communicate wirelessly over the serial port. Lesson 14 gives information on the hardware needed. Lessons 1-13 sill show you how to communicate between Python and Arduino if you need to get caught up on basic serial communication and interfacing arduino and python. The techniques provided in the video above, however, should work for just about any arduino project where you want to communicate between two arduinos, an arduino and PC, or between two PCs.
Python with Arduino LESSON 13: Calculating Height from Pressure measurements from BMP180 Pressure Sensor.
It is time to bring together a lot of things we have learned in our earlier lessons to create a Height-O-Meter, which will plot how high our BMP180 pressure sensor is above the floor. For this lesson we make simplifying assumption of constant temperature. When we use the sensor for our space probe or other high altitude experiments we will need to derive the equation again to take into account changing temperature. We went through the math of calculating height from changing pressure in LESSON 12.
In this lesson, we start with the software we developed in LESSON 11 for measuring, streaming, and plotting pressure and temperature data from the BMP180 sensor.
Remember, we connect the sensor to the Arduino as follows:
Connecting Up the BMP180 Pressure and Temperature Sensor | |
BMP180 Pin | Arduino Pin |
Vin | 5V |
GND | GND |
SCL | A5 |
SDA | A4 |
The software we are using on the arduino side is shown below, from LESSON 11.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include "Wire.h" // imports the wire library for talking over I2C #include "Adafruit_BMP085.h" // import the Pressure Sensor Library Adafruit_BMP085 mySensor; // create sensor object called mySensor float tempC; // Variable for holding temp in C float tempF; // Variable for holding temp in F float pressure; //Variable for holding pressure reading void setup(){ Serial.begin(115200); //turn on serial monitor mySensor.begin(); //initialize mySensor } void loop() { tempC = mySensor.readTemperature(); // Be sure to declare your variables tempF = tempC*1.8 + 32.; // Convert degrees C to F pressure=mySensor.readPressure(); //Read Pressure Serial.print(tempF); Serial.print(" , "); Serial.println(pressure); delay(250); //Pause between readings. } |
We modify the Python code from LESSON 11 as explained in the video above to get this code for the Python side.
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | import serial # import Serial Library import numpy as np # Import numpy import matplotlib.pyplot as plt #import matplotlib library from drawnow import * import time tempF= [] #Array for our Temperature dat pressure=[] #Array for our Pressure Data ht=[] #Array for our calculated Heights arduinoData = serial.Serial('com11', 115200) #Creating our serial object named arduinoData plt.ion() #Tell matplotlib you want interactive mode to plot live data cnt=0 def makeFig(): #Create a function that makes our desired plot plt.ylim(0,10) #Set y min and max values plt.title('My SuperCool Height-O-Meter') #Plot the title plt.grid(True) #Turn the grid on plt.ylabel('Height in Feet') #Set ylabels plt.plot(ht, 'ro-', label='Height') #plot the height array plt.legend(loc='upper left') #plot the legend plt2=plt.twinx() #Create a second y axis plt.ylim(75,85) #Set limits of second y axis- adjust to readings you are getting plt2.plot(tempF, 'b^-', label='tempF') #plot temperature array plt2.set_ylabel('temp F') #label second y axis plt2.ticklabel_format(useOffset=False) #Force matplotlib to NOT autoscale y axis plt2.legend(loc='upper right') #plot the legend tempBucket = 0 #Create bucket to hold sum of temperature readings PBucket=0 #Create bucket to hold sum of pressure readings print "PLease put Sensor Circuit on Ground for Calibration" #Calibrate sensor for readings on floor, P0 print "5" #Give user time to put sensor on floor time.sleep(1) print "4" time.sleep(1) print "3" time.sleep(1) print "2" time.sleep(1) print "1" time.sleep(1) print "Calibrating Sensor . . ." for i in np.arange(1,11,1): #Loop ten times to take ten measurements while (arduinoData.inWaiting()==0): #Wait here until there is data pass #do nothing arduinoString = arduinoData.readline() #read the line of text from the serial port dataArray = arduinoString.split(',') #Split it into an array called dataArray temp = float( dataArray[0]) #Convert first element to floating number and put in temp P = float( dataArray[1]) #Convert second element to floating number and put in P print "P = ",P, " , Temp= ", temp tempBucket=tempBucket + temp PBucket = PBucket + P P0 = PBucket/10 #Calcualte average pressure on floor tempK = ((tempBucket/10)-32)/1.8 +273.15 #Calculate average temperature on floor in K print "Baseline Temp in K is: ", tempK #Print resulrs print "Baseline Pressure inPa. : ", P0 while True: # While loop that loops forever while (arduinoData.inWaiting()==0): #Wait here until there is data pass #do nothing arduinoString = arduinoData.readline() #read the line of text from the serial port dataArray = arduinoString.split(',') #Split it into an array called dataArray temp = float( dataArray[0]) #Convert first element to floating number and put in temp P = float( dataArray[1]) #Convert second element to floating number and put in P h=98.57*tempK*np.log(P0/P) ht.append(h) tempF.append(temp) #Build our tempF array by appending temp readings pressure.append(P) #Building our pressure array by appending P readings drawnow(makeFig) #Call drawnow to update our live graph plt.pause(.000001) #Pause Briefly. Important to keep drawnow from crashing cnt=cnt+1 if(cnt>50): #If you have 50 or more points, delete the first one from the array tempF.pop(0) #This allows us to just see the last 50 data points pressure.pop(0) ht.pop(0) |
Please go through video for complete description of this software. Remember this is only valid for small changes in height over which temperature is constant.