Oscilloscope code

https://circuitdigest.com/microcontroller-projects/arduino-oscilloscope-code-circuit

Для тех, кто программирует на Python в Windows, рекомендую простой редактор https://thonny.org/

With pip installed, we can now install the other libraries we need.

Open the command prompt for windows users, terminal for linux users and enter the following;

pip install pyserial

With this done, install matplotlib using;

pip install matplotlib

Drawnow is sometimes installed alongside matplotlib but just to be sure, run;

pip install drawnow

Немного скорректированный код

import time
import matplotlib.pyplot as plt
from drawnow import *
import serial
val = [ ]
cnt = 0
#create the serial port object
port = serial.Serial('COM6', 9600, timeout=0.5)
plt.ion()
 
#create the figure function
def makeFig():
    plt.ylim(-1023,1023)
    plt.title('Osciloscope')
    plt.grid(True)
    plt.ylabel('data')
    plt.plot(val, 'ro-', label='Channel 0')
    plt.legend(loc='lower right')
 
while (True):
    port.write(b's') #handshake with Arduino
    if (port.inWaiting()):# if the arduino replies
        value = port.readline()# read the reply
        print(value)#print so we can monitor it
        decode = value.decode('utf-8').strip()
        print(decode)
 
        number = int(decode) #convert received data to integer 
        print('Channel 0: {0}'.format(number))
        # Sleep for half a second.
        time.sleep(0.01)
        val.append(number)
        drawnow(makeFig)#update plot to reflect new data input
        plt.pause(.000001)
        cnt = cnt+1
    if(cnt>50):
        val.pop(0)#keep the plot fresh by deleting the data at position 0
int sensorpin = A0;
void setup() {
  // initialize serial communication at 115200 bits per second to match that of the python script:
  Serial.begin(9600);
}
void loop() {
  // read the input on analog pin 0:########################################################
  int sensorValue = analogRead(sensorpin);
  byte data = Serial.read();
  if (data == 's')
  {
    Serial.println(sensorValue);
    delay(100);        // delay in between reads for stability
  }
}