PySerial Example


#!/usr/bin/python

import serial
import time
import random

color1 = 0
color2 = 0
color3 = 0

ser = serial.Serial(port = "/dev/ttyUSB0", baudrate=9600)
ser.close()
ser.open()
random.seed()
while(1):
	if ser.isOpen(): 	  			
			temp = ''
			color1 = random.randint(0,255)
			color2 = random.randint(0,255)
			color3 = random.randint(0,255)

			if(color2 <0):
				color2 = 0
			if(color3 < 0):
				color3 = 0		
			temp +=str(color1)
			temp +=','
			temp +=str(color2)
			temp+=','
			temp +=str(color3)
			temp += "\r\n"    
			print(temp)
			ser.write(temp)
			time.sleep(1)
			

This code is used to continuously create random numbers, concatenate them to a string and send them across the line.

Leave a Reply