Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Proof of concept Python script to receive POST data (over network) from a Touchdevelop app to send to an Arduino
- # Tested/developed on Python version 2.7.3
- """ NOTE: I'm a newbie Python programmer, the server bit's mostly cut n paste from elsewhere and the POST data processing to Arduino bit
- was learnt on the fly. This script is supplied as is, feel free to chop, change point and laugh etc but I cant't supply much
- in the way of support.
- Midge
- """
- from BaseHTTPServer import BaseHTTPRequestHandler
- # Set serial Arduino port
- # You'll need the PYSerial module if it's not already installed
- import serial
- ser = serial.Serial('COM3', 9600,) #Note COM3,
- ser.write(chr(0)) #reset Arduino LED's on startup
- #Set Port to listen on
- my_port = 90
- buttonstatus = 0 #declare buttonstatus
- # datasend fnc receives POST data and sends it to the Arduino oveer Serial
- def datasend(input):
- global buttonstatus
- decimal_val=int(input) # turn POST data to a number (int)
- if decimal_val==255: #shake to reset
- print("Phone Shook (reset)") # Debug info
- blank=chr(0)
- ser.write(blank) # Write 0 to Arduino, turn off LED's
- buttonstatus=0 # reset values
- else:
- buttonstatus ^= (decimal_val) # Take incoming data and XOR it with current (to toggle LED value)
- print 'Data sent (binary) ' + (bin(buttonstatus)) # Debug info
- send_val=chr(buttonstatus) # Convert to char**
- ser.write(send_val) # Send data over serial to Arduino
- """ ** This was a bloody pain to get working!, it turned out that Pyserial sends data as strings so my lovely binary numbers
- were being mangled before being sent. The workaround is to convert the number into the corresponding character and send that,
- The Arduino is set to read a (one byte) char from serial.
- """
- class PostHandler(BaseHTTPRequestHandler):
- def do_POST(self):
- content_len = int(self.headers.getheader('content-length'))
- post_body = self.rfile.read(content_len) # Read Post data
- datasend(post_body) # Call datasend function and pass POST data
- # Below commented out, no response set to phone
- # Begin the response
- #self.send_response(200)
- #self.end_headers()
- #self.wfile.write('Client: %s\n' % str(self.client_address))
- #self.wfile.write('Path: %s\n' % self.path)
- #self.wfile.write('Form data:\n')
- return
- if __name__ == '__main__':
- from BaseHTTPServer import HTTPServer
- server = HTTPServer(('', my_port), PostHandler)
- print 'Starting server, use <Ctrl-C> to stop'
- server.serve_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement