c ++ – read serial data from Arduino in Python every 100 ms

I'm trying to send data from an Arduino to Python via USB every 100 ms. What improvements can be made to my code? I feel like it's a bit bloated and can be written better, but I'm not sure what improvements should be made.


import serial

def _has_digits(string):
    return any(char.isdigit() for char in str(string))

class Arduino():
    def __init__(self, port, baud_rate, timeout):
        self.baud_rate = baud_rate
        self.timeout = timeout
        self.port = port
        self.serial = serial.Serial(port, baud_rate, timeout = timeout)

    def read_data(self):

        last_line_recieved = ""

            while True:
                serial_bytes = self.serial.readline()
                decoded_line = str(serial_bytes.decode('utf8'))

                # Read from buffer until we capture the whole line of data
                if (len(serial_bytes) != 0) and (b'n' in serial_bytes):

                    # Check if any digits exist in the string that overflowed from the previous line
                    if _has_digits(decoded_line):
                        overflowed_digits = ( char for char in decoded_line.split() if char.isdigit() )
                        string_digits = ("").join(overflowed_digits)
                        last_line_recieved += string_digits

                    # Store the data now that we have the entire line
                    data = last_line_recieved.split(",")
                    state_vector = {
                        'pendulum_angle': data(0),
                        'cart_position': data(1),
                        'pendulum_angular_velocity': data(2),

                        # Sometimes the carriage return "r" remains in the string, so get rid of it
                        'cart_velocity': (data(3) if 'r' not in data(3) else data(3).split('r')(0))

                    # Reset the variable
                    last_line_recieved = ""

                elif len(serial_bytes) != 0:
                    last_line_recieved += decoded_line


            except KeyboardInterrupt:
                print("You have quit the serial communication.")

if __name__ == "__main__":
    arduino = Arduino("/dev/cu.usbmodem14101", baud_rate = 9400, timeout = 0)



#include "motorControllerDrokL298.h"
#include "pythonUtils.h"

// Initialize encoders
#define cartEncoderPhaseA 3
#define cartEncoderPhaseB 4
#define pendulumEncoderPhaseA 2
#define pendulumEncoderPhaseB 5

Encoder cartEncoder(cartEncoderPhaseA, cartEncoderPhaseB);
Encoder pendulumEncoder(pendulumEncoderPhaseA, pendulumEncoderPhaseB);

// Initialize named constants
const unsigned long TIMEFRAME = 100; // milliseconds
const double ENCODER_PPR = 2400.0;

// Initialize variables
unsigned long previousMilliseconds = 0;
float previousCartPosition = 0;
float previousPendulumAngle = 0;

void setup()

  // Motor controller
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(ENA, OUTPUT);

void loop()
  unsigned long currentMilliseconds = millis();
  long cartEncoderCount = cartEncoder.read();
  long pendulumEncoderCount = pendulumEncoder.read();

  // Send values to python every n milliseconds
  if ( (currentMilliseconds - previousMilliseconds) > TIMEFRAME ) {

    // Compute the state
    stateVector state;
    state.pendulumAngle = encoderCountToAngleRadians(pendulumEncoderCount, ENCODER_PPR);              // radians
    state.cartPosition = encoderCountToCartPositionInches(cartEncoderCount, ENCODER_PPR);             // in
    state.pendulumAngularVelocity = (state.pendulumAngle - previousPendulumAngle)/(TIMEFRAME/1000.0); // radians/s
    state.cartVelocity = (state.cartPosition - previousCartPosition)/(TIMEFRAME/1000.0);              // in/s


    // Store the current data for computation in the next loop
    previousMilliseconds = millis();
    previousPendulumAngle = state.pendulumAngle;
    previousCartPosition = state.cartPosition;





struct stateVector
    double pendulumAngle;
    double cartPosition;
    double pendulumAngularVelocity = 6.0;
    double cartVelocity = 5.0;

float encoderCountToAngleDegrees(long encoderCount);
float encoderCountToCartPositionInches(long cartEncoderCount, double encoderPPR);
void sendStateVectorToPython(stateVector state);

float encoderCountToAngleRadians(long encoderCount, double encoderPPR)
    return (encoderCount / encoderPPR) * (2.0 * PI);

float encoderCountToCartPositionInches(long cartEncoderCount, double encoderPPR) {
    float idlerPulleyRadius = 0.189;                                            // inches
    float cartAngle = encoderCountToAngleRadians(cartEncoderCount, encoderPPR); // radians
    return idlerPulleyRadius * cartAngle;

void sendStateVectorToPython(stateVector state)


Employee has chosen 100% Bitcoin content! Avoid these things to make a profit on Bitmex. – Advertising, offers

Visit the community for Free Crypto Signal, Bitcoin Bot and Gdax Trading – https://t.me/freebitmexsignals

As an employee at the Crypto Exchange Coin Center, Lakin was given the option to receive some or all of the cryptocurrency salary.

Lakin remarked, "Buying things with Krypto is easier than you think." There are several online retailers that accept cryptocurrency, and even third-party tools that allow you to settle bills on platforms like Amazon.

Bn4zESC.jpg "data-src =" https://i.imgur.com/Bn4zESC.jpg "src =" https://topgoldforum.com/applications/core/interface/js/spacer.png "/></p>
<p>	6% profit on #XBT (#BTC) through automated scalping trading generated via Automated Bot.
<p>	Set once – trading is based on the trend to achieve constant profit.
<p>	This was an excellent win on #BTC, #ETH and key Bitmex coins through automated bot scalping trades and bonus bitmex signals for premium members.
<p>	We have received a remarkable response for the Automated Bot + Premium Bitmex Group.
<p>        (tagsToTranslate) bitcoin (t) coinbase (t) gdax</p>
	</div><!-- .entry-content -->

	<footer class= Posted on Categories ArticlesTags , , , , , , , , ,

100% True Cisco 300-375 Certification Check Dumps – Social Media Marketing (SMM)

The practice test on the Braindumpspro website persistently urged me to set my guidelines higher and higher. It was similar to planning and configuring a messaging platform, and I tried to beat without mistakes. The Braindumpspro website worked like an individual guide for me. It inspired me to do my best in everyone Cisco 300-375 Messaging Administrator Associate Certification.

PAY – Earn more than $ 100 with additional schoolwork! * Original method! | Proxies-free

Hello everybody, if you're still in school and you know that you too get reviews, essays and exams, this is a perfect method. There's a lot of potential for earning $ 100 more if you just do a few extra schoolwork, and I've never seen this done.

* This method is original and written by me, I thought about it, so it's not a shitty method.

Server from 30 USD – 100 TB transfer, China optimized

All servers include:

– Immediate setup after order confirmation
– 100TB transfer included
– China optimized bandwidth through China Telecom and China Unicom
– DDoS reduction
– Route optimization over almost 500 peers

* Dual Intel Xeon 5420 240 SSD Preconf *

Processor: 2.5 GHz – 2 processors
8 cores / 8 threads
Memory: 240 GB SSD
1Gbit network connection
Linux OS (Windows available)
100 TB monthly transfer
5 Usable IPv4 address
/ 64 IPv6 address block **
Free love
Immediate setup

$ 0 Setup – $ 30.00 / mo ORDER HERE!

* Xeon 5520 *

Processor: 2.26 GHz – 1 processor
4 cores / 8 threads
Memory: 2x 1 TB SATA
1Gbit network connection
Linux OS (Windows available)
100 TB monthly transfer
5 Usable IPv4 address
/ 64 IPv6 address block **
Free love
Immediate setup

$ 0 Setup – $ 35.00 / mo ORDER HERE!

* i7-8700K 32GB + 2x480GB SSD *

Processor: 3.7 GHz
6 cores / 12 threads
Memory: 2x 480GB SSD
1Gbit network connection
Linux OS (Windows available)
100 TB monthly transfer
5 Usable IPv4 address
/ 64 IPv6 address block **
Free love
Immediate setup

$ 0 Setup – $ 105.00 / mo ORDER HERE!

All our other configurations can be found at http://www.wholesaleinternet.net/dedicated/

If you have any questions, please contact sales@wholesaleinternet.net.

About us:

Wholesale Internet has been in business since 1999. We are located in North Kansas City, MO, where our sister company KCFiber operates fiber-optic assets for every building and residency in the city, as well as our own backbones across the river to KC, MO.

Our network includes local connections to 1102 Grand and 1100 Walnut as well as POPs in Newark, New Jersey, Dallas, Texas, Chicago, Illinois, Seattle, Washington and Fremont, as well as San Jose, California. We have direct connections to China Telecom and Unicom, as well as direct peering relationships with nearly 500 peers through 9 Internet exchanges.

Custom server setups take 1-2 days. Instant setups are … Instant (once the order has been approved). Free love only refers to Platonic love. Romantic love can be available for a small additional charge.

Bonus 100%

We, the traders, must first make sure that all types of bonuses are sourced only from credible trading brokers. Otherwise, it is useless to have 200-300% bonuses that can not be used at all due to margin stop-outs. By the way, I'm very happy that I chose LQDFX, which gave me a 100% startup bonus that I can use for all time, including the lowest trading margins. so i get comfort while acting practically.

24 GB RAM managed dedicated server for a maximum of $ 100 / month?

Hello people – I hope you are fine!

Can you please recommend a suitable dedicated server?

Specifications I need:

– Managed server

– WHM and cPanel

– 24 GB RAM

– 200 GB / month bandwidth

– Half of our visitors come from the USA, the rest from all over the world. The server location does not play a big role at reasonable speed.

– Preferably not over 100 USD / month

Thanks a lot!