Send Two Different Strings to Arduino From Python

Hello,
I am creating a stock market ticker from an adafruit 32x64 display. Currently, I have the data sending very well from yahoo finance and have posted the code below. My only problem is that I would also like to send a command from python to tell it when to change the color of the text from red to green for stocks going up and down. If you have any suggestions for changing the color of the text when the stock price is lower the next day than the previous or ways to send two different strings to Arduino. Thanks!

/**
 * Author:    UseMyTools.Net
 * Created:   2021.01.20
 *
 * (c) Copyright by UseMyTools.Net.
 *  MIT license
 *
 **/

#include <Adafruit_GFX.h>
#include <TimeLib.h>
#include <DS3232RTC.h>
#include <Wire.h>


/*
 * Adafruit_GFX Core graphics library
 * Written by Limor Fried/Ladyada & Phil Burgess/PaintYourDragon
 * for Adafruit Industries.
 *  BSD license, all text above must be included in any redistribution.
*/

/*
 * code snippet from Time_Message_ESP8266_Matrix-P4
 * https://arduino-projects-free.blogspot.com/2020/08/time-message-esp8266-matrix-p4-weather.html
 *
 */


#include <RGBmatrixPanel.h> // Hardware-specific library
#include <Adafruit_GFX.h>   // Core graphics library


// Similar to F(), but for PROGMEM string pointers rather than literals
#define F2(progmem_ptr) (const __FlashStringHelper *)progmem_ptr


#define CLK 11   // USE THIS ON ARDUINO MEGA
#define OE   9
#define LAT 10
#define A   A0
#define B   A1
#define C   A2
#define D   A3




// Last parameter = 'true' enables double-buffering, for flicker-free,
// buttery smooth animation.  Note that NOTHING WILL SHOW ON THE DISPLAY
// until the first call to swapBuffers().  This is normal.
//RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, true);
RGBmatrixPanel matrix(A, B, C, D, CLK, LAT, OE, true, 64);



uint16_t myRED = matrix.Color333(7,0,0);
uint16_t myGREEN = matrix.Color333(0,7,0);
uint16_t myBLUE = matrix.Color333(0,0,7);
uint16_t myWHITE = matrix.Color333(7, 7,7);
uint16_t myYELLOW = matrix.Color333(7,7,0);
uint16_t myCYAN = matrix.Color333(0,7,7);
uint16_t myMAGENTA = matrix.Color333(7,0,7);
uint16_t myShadow = matrix.Color333(4,0,7);
uint16_t myROSE = matrix.Color333(7,0,4);
uint16_t myBLACK = matrix.Color333(0,0,0);
uint16_t myCOLORS[9] = {myRED, myGREEN, myWHITE, myMAGENTA, myBLUE, myYELLOW, myCYAN, myShadow, myROSE};

String s;

//int    textX   = matrix.width(),
int    textX   = 14,

       //textMin = sizeof(str) * -12,
       textMin = -90;



  void setup() {
  Serial.begin(74880); //opens serial port, sets data rate to 74880 bps
  matrix.begin();
  matrix.setTextWrap(false); // Allow text to run off right edge
  matrix.setTextSize(1);
  setTime(19,52,50,24,12,21);

}



void display_footer()
{
  matrix.setCursor(3, 25);
  matrix.setTextColor(myBLUE);
  matrix.print(day());
  matrix.print("/");
  matrix.print(month());
  matrix.print("/");
  matrix.print(year());
}



void display_header()
{
  matrix.setCursor(13, 0);
  matrix.setTextColor(myBLUE);
  matrix.print(hour());
  matrix.print(":");
  matrix.print(minute());
  matrix.print(":");
  matrix.print(second());
}

void display_middle(){


int ypos = 12;

  // Draw big scrolly text on top
matrix.setTextColor(myGREEN);
matrix.setCursor(textX, ypos);
matrix.print(s);

  // Move text left (w/wrap), increase hue
  if((--textX) < textMin) textX = 14;

}

void loop() {

  matrix.fillScreen(matrix.Color333(0, 0, 0));

  display_header();
  display_middle();
  display_footer();

  // Update display
  matrix.swapBuffers(false);

  if (Serial.available()>0){
  s = Serial.readString();
  }
}

Python Code:

import yfinance as yf
import serial
import time
StockShares = ['SPY', 'DOW', 'AAPL', 'AMC', 'AMD', 'AMZN']

ser = serial.Serial('COM5',74880)
def printShare(share,name):
    ser.write(name + ': *' + share.get_open()+','+share.get_price())
    print (name + ': *' + share.get_open()+','+share.get_price())
    time.sleep(.1)
def mainProgram():
    x = 0
    for stock in StockShares:
        TickerSym = StockShares[x]
        Ticker = yf.Ticker(TickerSym)
        daily_increase = str(round(100 - (Ticker.info['open'] / Ticker.info['regularMarketPrice']) * 100, 2))
        #ser.write (str.encode("99"))
        #ser.write (str.encode(TickerSym+ str(Ticker.info['regularMarketPrice'])))
        ser.write (str.encode(TickerSym + " $" + str(round(Ticker.info['regularMarketPrice'], 4)) + " %" + daily_increase))
        print(TickerSym, round(Ticker.info['regularMarketPrice'], 4), "↑ %", daily_increase, "SENT")
        x = x + 1
        time.sleep(10)
    mainProgram()
mainProgram()

This is done by sending "escape" codes to change the colour. You send the ESC character (decimal 27 or 0x1B) followed by one or two characters as needed.

Your Arduino code looks for the ESC and when it sees it, it reads the next one or two (however you have defined them) characters and instead of attempting to print them, uses them to decide on what colour or other characteristic of the text that you want to print from then on until another ESC sequence is sent.

This is a very old standard.

Thanks for the reply.
So if I would like to print the text in red instead of green, what would I append to the end of my python line to make the Arduino do that.
Sorry, I code in python and am a bit of an Arduino noob.

It is up to you determine what escape codes you use, though there are no doubt some conventions.

The escape code is sent before the text to which it applies.

Could i see an example of this in a string of code please?

Now you're asking! :astonished:

Sorry, I have no code to hand. I fancy it is for you to figure out.

Have you read the Wikipedia article?

I did read it but I do not understand how to implement it. I have tried adding the escape codes to the end of the line and they just print on the screen

Well, of course you have to re-write the Arduino code so that it detects the ESC character and the character(s) following and uses that to select the different colour.

The Arduino does not have any idea how to do this unless you code it to. You want the extra functionality, you have to code it. That's how Arduino works. :grin:

It can be as simple as putting a 'g' or 'r' in front of the string you're sending to indicate the color.
Instead of sending for example "IBM: 130.45, 130.89", your python script would send "gIBM: 130.45, 130.89".

Your arduino code sets the color based on the first char, and removes that char from the string (so the rest of your code can stay the same) :

s = Serial.readString();
c=s.charAt(0); 
if (c='r') { matrix.setTextColor(myRED); }
if (c='g') { matrix.setTextColor(myGREEN); }
s.remove(0, 1);  //removes first char from s