Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5597

Interfacing (DSI, CSI, I2C, etc.) • Re: Serial communication from Pi 5 to Arduino Uno

$
0
0
Made some more progress on my project but ran into another sang. The goal of this project was to tie a servo to the blend door on my grill so I could use a Pi 5, a servo, and a Arduino UNO to regulate the temperature of the grill for smoking meats. I got the meat thermometer readings working and used the animation features in matplotlib to make the plot in real time then after a few seconds the plot closes and the measured temperature along with the desired temperature is fed into a PID control where the needed pulse width is found. The pulse width value is then sent to an Arduino through the serial port where the servo library is used. At this point everything seems to work until right after the pulse width is sent to the Arduino where the servo rotates to a position but then it rotated back to where it initially was. This is the first time I've tried using a Pi in general and I haven't had that much experience with the Arduino so I'm not really sure where to go from here. I've tried googling around but haven't found anything specific, attached is a copy of the python and Arduino scripts. If possible please let me know a direction I should go inform here.

Code:

from gpiozero import MCP3008temp1 = MCP3008(channel=0)temp2 = MCP3008(channel=1)import datetime as dtimport matplotlib.pyplot as pltimport matplotlib.animation as animationfrom gpiozero import LEDfrom signal import pauseimport re, subprocessfrom gpiozero import Servofrom time import sleeptemp1_cnt =0temp2_cnt =0temp1_array =[]temp2_array =[]# Time to check sevro positonservo = Servo(18)# Set pin to swtich on Fanfan = LED(17)# Create figure for plottingfig = plt.figure()ax = fig.add_subplot(1, 1, 1)xs = []ys = []# This function is called periodically from FuncAnimationf_num =3def animate(i, xs, ys):    temp_c =0    # Read temperature (Celsius) from TMP102    for i in range(0,10000):        temp_c = temp_c + temp1.value    temp_c = temp_c/10000    # Add x and y to lists    xs.append(dt.datetime.now().strftime('%H:%M:%S'))    ys.append(temp_c)    # Limit x and y lists to 20 items    xs = xs[-20:]    ys = ys[-20:]    # Draw x and y lists    ax.clear()    ax.plot(xs, ys)    # Format plot    plt.xticks(rotation=45, ha='right')    plt.subplots_adjust(bottom=0.30)    plt.title('TMP102 Temperature over Time')    plt.ylabel('Temperature (deg C)')        # Get CPU temp    err, msg = subprocess.getstatusoutput('vcgencmd measure_temp')    msg = msg[5:7:1]    if float(msg) >60:        fan.on()    else:        fan.off()    class PID:    def __init__(self, Kp, Ki, Kd):        self.Kp = Kp        self.Ki = Ki        self.Kd = Kd        self.last_error = 0        self.integral = 0    def update(self, error, dt):        derivative = (error - self.last_error) / dt        self.integral += error * dt        output = self.Kp * error + self.Ki * self.integral + self.Kd * derivative        self.last_error = error        return output# Set up plot to call animate() function periodicallywhile True:    print("test")    # Set up plot to call animate() function periodically    ani = animation.FuncAnimation(fig, animate, frames=12,fargs=(xs, ys), interval=1, repeat=False)    # set the timer interval 5000 milliseconds    timer = fig.canvas.new_timer(interval = 12000)    timer.add_callback(plt.close)    timer.start()    plt.show()    plt.close('all')
and the Arduino code

Code:

#include <Servo.h>boolean newData = false;String receivedChar = "";char receivedChar_1 = {};char receivedChar_2 = {};char receivedChar_3 = {};char receivedChar_4 = {};int pos = 1500;Servo myservo;  // create servo object to control a servovoid setup() {  //put your setup code here, to run once:Serial.begin(9600); myservo.attach(5);  // attaches the servo on pin 9 to the servo object}void loop() {  //myservo.writeMicroseconds(1000);  recvChar();  if (newData == true){    pos = receivedChar.toInt();    //Serial.println(pos);    myservo.writeMicroseconds(pos);    delay(1000);    newData = false;  }}void recvChar() {  if (Serial.available()>=8) {    receivedChar = "";    receivedChar_1 = Serial.read();    receivedChar.concat(receivedChar_1);    receivedChar_2 = Serial.read();    receivedChar.concat(receivedChar_2);    receivedChar_3 = Serial.read();    receivedChar.concat(receivedChar_3);    receivedChar_4 = Serial.read();    receivedChar.concat(receivedChar_4);    //Serial.println(receivedChar);    newData = true;  }  //delay(200);}

Statistics: Posted by DStansberry1 — Fri Apr 19, 2024 3:19 am



Viewing all articles
Browse latest Browse all 5597

Trending Articles