Python serial write and read to arduino with a K0183 shield and RGB

Showing communication to arduino which used a RGB shield which is setup to be controlled via serial com port

using Python 3.7

Red num,Green num,Blue number   0-255

example 100,0,0  will turn on Red Led of RGB with a 100 intensity

Entering q or Q will quit the running python script.

I already create a similar LabVIEW® to control the arduino with RGB serial controlled code. See other post ( https://testengineerresource.com/2019/11/11/lv-arduino-serial-comm-and-k0183-shield).

Here we are using a python script to show similar control as was done in LabVIEW® post

code below


RGB Shield code

/*
  Reading a serial ASCII-encoded string.

 This sketch demonstrates the Serial parseInt() function.
 It looks for an ASCII string of comma-separated values.
 It parses them into ints, and uses those to fade an RGB LED.

 Circuit: Common-Anode RGB LED wired like so:
 * Red Cathode: digital pin 9
 * Green Cathode: digital pin 10
 * Blue Cathode: digital pin 11
 * Anode : GND
 *
Used  example- communication - ReadASCIIstring code as starting point  (changed for Common Anode)
 created 13 Apr 2012
 by Tom Igoe
  modified 14 Mar 2016
 by Arturo Guadalupi

modified from origianl example for K0183 Keyestudio shield
 by AC 2019
 This example code is public domain.
 */

// pins for the LEDs:
const int redPin = 9;
const int greenPin = 10;
const int bluePin = 11;

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // make the pins outputs:
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  Serial.write("R,G,B   example type 100,10,10 then press Send\n"); // help line
}

void loop() {
  // if there's any serial available, read it:
 // Serial.write("R,G,B   example 100,10,10");
 // if there's any serial available, read it:
  while (Serial.available() > 0) {

    // look for the next valid integer in the incoming serial stream: n,n,n
    int red = Serial.parseInt();
    // do it again:
    int green = Serial.parseInt();
    // do it again:
    int blue = Serial.parseInt();

    // look for the newline. That's the end of your
    // sentence:
    if (Serial.read() == '\n') {
      // constrain the values to 0 - 255 and invert
      // if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
      red = constrain(red, 0, 255);
      green = constrain(green, 0, 255);
      blue = constrain(blue, 0, 255);

      // fade the red, green, and blue legs of the LED:
      analogWrite(redPin, red);
      analogWrite(greenPin, green);
      analogWrite(bluePin, blue);

      // print the three numbers in one string as decimal:
      Serial.print("Arduino Echo ");   // added 11/19/2019
      Serial.print(red, DEC);
      Serial.print(",");
      Serial.print(green, DEC);
      Serial.print(",");
      Serial.println(blue, DEC);
    } //cr

  }//serial data to read
}//loop

python code script

# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 13:01:15 2019

@author: aleja
close the Arduino IDE before running since two serial connection may cause issues
An Arduino is connected to Com Port sending out Serial Data.
Since its connects to the PC via the USB cable it is automatically send out data
(as aka COM4 in my case)
Suggest if you get a message about cannot open port ,port already open - try unplug Arduino USB cable and reconnect.
then run this code.
Also the IPython console my need to restarted if a error occured during initial setup or wrong com port
This is a write and read  example when an arduino is connected to the PC via its USB cable(COMn) , you COMn can be different
For Arduino, have some serial.println("Your own message"); may 3 in this example  so you get the /r/n needed by ser.readline()
"""

import serial,time
import serial.tools.list_ports as port_list

#Get all comm ports
print("Please use correct comport from list below\n")
ports = list(port_list.comports())
for p in ports:
    print (p)

ser = serial.Serial('COM4', 9600)
#removed ser.open because when arduino is connect com3 is already open (when you connected the USB cable (you cannot open and opened port)
#arduino is already coded and sending out serial data that was using for debugging in arduino serial monitor
#ser.open()

#clean out serial data buffers
ser.flushInput() #flush input buffer from PCs serial driver
ser.flushOutput()#flush output buffer from PCs serial driver
time.sleep(0.5)  #give the serial port on PC sometime to complete
response = ser.readline() # a new serial instance reset the serial on the arduino so get first read
print(response.decode("utf-8"))
# Only get a sample number of lines(/r/n) of the the data coming out from the ardunio.
numOfLines = 0
#numOfLinesToRead=3
while True:
  commandstr=str(input("Enter R,G,B   0-255  ex 100,0,0 to quit enter Q or Quit\n"))
  commandstr=commandstr+"\n"
  if (commandstr.find("Q")<0 and commandstr.find("q")= numOfLinesToRead):
#        break
  else:
      break
ser.close() # even if you dont use the serial open you still need to close it.
print("Done")

IPython console output

 

Please use correct comport from list below

COM4 – Arduino Uno (COM4)
R,G,B example type 100,10,10 then press Send
Enter R,G,B 0-255 ex 100,0,0 to quit enter Q or Quit
100,0,0
b’Arduino Echo 100,0,0\r\n’
Arduino Echo 100,0,0
Enter R,G,B 0-255 ex 100,0,0 to quit enter Q or Quit
Q
Done


 

Arduino Uno used,

Python 3.7

LabVIEW® is a National Instrument product
This post is not connected or endorsed by any company.
Created to spark ideas on the subject.
Use at your own risk.

About LV_TS_Test_Engineer_3000_VI

Automated Test Equipment Software
This entry was posted in Test Sector and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s