Hello,
This seems the only way to get an answer to my recent problem I encountered in Chat openai 4.
I was trying to fix an issue in a code I wrote in Micropython and prompted my question in chat.openai.
Crazy thing, it answered something completely out of topic about turkish politics.
I tried again and it answered about US politics.
Here are the questions I asked and under it are the answers from chat GPT.
Has anybody an idea what’s going on?
Here is my prompt:
Chat Transcript
Hi there,
Can you modify following code with following goal. At the moment, the PWM signal at the end has not the right frequency to proprely control a servo with a raspberry pi pico rp 2040.
The signal has to have a frequency of 50 Hz. It seems that the code can’t respect this frequency because of all the utime sleep and other facts.
Can you modify the code so that the PWM signal at the end is at a frequency of 50 Hz?
import machine
import math
import time
import utime
import math
import sys
###############################################################
# Fonction pour servo
###############################################################
#Definition d'une fonction, ici pour convertir les valeurs d'entrée en degrés pour afficher une echelle en bits
def map(val, in1, in2, out1, out2): # in > out mapping
# Figure out how 'wide' each range is
inSpan = in2 - in1
outSpan = out2 - out1
# Convert the in range into a 0-1 (float) range
valueScaled = float(val-in1)/float(inSpan)
# Convert the 0-1 range into in the out range
return out1 + valueScaled * outSpan
###############################################################
# MPU 9250 Code
###############################################################
# Define MPU9250 registers and addresses
MPU9250_ADDR = 0x68
AK8963_ADDR = 0x0C # Magnetometer address for MPU-9250
PWR_MGMT_1 = 0x6B
ACCEL_XOUT_H = 0x3B
GYRO_XOUT_H = 0x43
# Initialize I2C
i2c = machine.I2C(1, scl=machine.Pin(7), sda=machine.Pin(6), freq=400000)
# Wake up MPU9250
i2c.writeto_mem(MPU9250_ADDR, PWR_MGMT_1, bytes([0]))
# Initialize magnetometer
i2c.writeto_mem(MPU9250_ADDR, 0x37, bytes([0x02])) # Enable bypass mode
i2c.writeto_mem(AK8963_ADDR, 0x0A, bytes([0x16])) # Continuous measurement mode 2
def read_raw_data(addr, i2c_addr=MPU9250_ADDR):
high = i2c.readfrom_mem(i2c_addr, addr, 1)
low = i2c.readfrom_mem(i2c_addr, addr + 1, 1)
value = int.from_bytes(high + low, 'big')
return value - 65536 if value > 32767 else value
def get_accel_gyro_data():
data = i2c.readfrom_mem(MPU9250_ADDR, ACCEL_XOUT_H, 14)
ax = int.from_bytes(data[0:2], 'big')
ay = int.from_bytes(data[2:4], 'big')
az = int.from_bytes(data[4:6], 'big')
gx = int.from_bytes(data[8:10], 'big')
gy = int.from_bytes(data[10:12], 'big')
gz = int.from_bytes(data[12:14], 'big')
ax = ax - 65536 if ax > 32767 else ax
ay = ay - 65536 if ay > 32767 else ay
az = az - 65536 if az > 32767 else az
gx = gx - 65536 if gx > 32767 else gx
gy = gy - 65536 if gy > 32767 else gy
gz = gz - 65536 if gz > 32767 else gz
return ax, ay, az, gx, gy, gz
def calculate_pitch(ax, ay, az):
return math.atan2(-ax, math.sqrt(ay * ay + az * az)) * 180 / math.pi
class KalmanFilter:
def __init__(self):
self.Q_angle = 0.01 # Fine-tuning parameters for Kalman filter, initial value 0.001
self.Q_bias = 0.3 # Fine-tuning parameters for Kalman filter, initial value 0.003
self.R_measure = 0.003 # Fine-tuning parameters for Kalman filter, initial value 0.03
self.angle = 0.0
self.bias = 0.0
self.P = [[0, 0], [0, 0]]
'''
Fine-tuning the Kalman filter settings involves adjusting the values of Q_angle, Q_bias, and R_measure to achieve optimal performance for your specific application. Here’s a brief explanation of each parameter:
Q_angle: This parameter controls the process noise covariance for the angle. A higher value increases the rate at which the filter adjusts to changes in angle but may introduce more noise.
Q_bias: This parameter controls the process noise covariance for the gyro bias. Similar to Q_angle, a higher value increases the rate of bias correction but may introduce more noise.
R_measure: This parameter controls the measurement noise covariance. A higher value makes the filter trust the sensor measurements more, while a lower value makes it trust the predicted state more.
The process of fine-tuning involves experimentation and observation of how the filter behaves with different settings. Here’s a general approach to fine-tuning:
Start with default values: Begin with the default values or values that are commonly used as a starting point (like the ones you provided: Q_angle = 0.001, Q_bias = 0.003, R_measure = 0.03).
Observation: Observe the behavior of the filter output. Pay attention to how it responds to changes in sensor inputs (e.g., rapid movements, slow movements, static conditions).
Adjustment: Adjust one parameter at a time while keeping the others constant. For example, increase Q_angle and observe how quickly the filter responds to changes in angle. Then, decrease Q_angle and observe any reduction in noise but potentially slower response.
Balance: Find a balance between responsiveness and noise reduction that suits your application. You may need to compromise based on the specific requirements of your project.
Iterate: Iterate this process, making small adjustments to each parameter until you achieve satisfactory performance.
Here’s an example of how you might adjust the KalmanFilter class for fine-tuning:
'''
def get_angle(self, new_angle, new_rate, dt):
rate = new_rate - self.bias
self.angle += dt * rate
self.P[0][0] += dt * (dt*self.P[1][1] - self.P[0][1] - self.P[1][0] + self.Q_angle)
self.P[0][1] -= dt * self.P[1][1]
self.P[1][0] -= dt * self.P[1][1]
self.P[1][1] += self.Q_bias * dt
S = self.P[0][0] + self.R_measure
K = [self.P[0][0] / S, self.P[1][0] / S]
y = new_angle - self.angle
self.angle += K[0] * y
self.bias += K[1] * y
P00_temp = self.P[0][0]
P01_temp = self.P[0][1]
self.P[0][0] -= K[0] * P00_temp
self.P[0][1] -= K[0] * P01_temp
self.P[1][0] -= K[1] * P00_temp
self.P[1][1] -= K[1] * P01_temp
return self.angle
kf_pitch = KalmanFilter()
last_time = utime.ticks_ms()
origin_pitch = 0
samples = 0
calibration_time = 10 # seconds
# Calibration loop to calculate the origin
for _ in range(int(calibration_time * 1000 / 50)): # assuming 50ms delay in loop
ax, ay, az, _, _, _ = get_accel_gyro_data()
ax /= 16384.0
ay /= 16384.0
az /= 16384.0
pitch = calculate_pitch(ax, ay, az)
origin_pitch += pitch
samples += 1
utime.sleep(0.05)
###############################################################
# Configuration board pour servo
###############################################################
# Board config
servoGaz = machine.PWM(machine.Pin(16))
servoGaz.freq(50)
minPWM = (0.7/20)*65535 # 0.7/20 Pourcent du nombre de valeurs possibles en 16 bits = 2293.725
# Or, comme on est à 50Hz, sur une seconde, cela correspond à 0.02s, donc 20ms.
# Le servo /ESC est indiqué de fonctionner dès 700 microsecondes, soit 0.7ms.
# Cette valeur de 0.7ms sera la valeur minimale convertie en bits du signal PWM
maxPWM = (2.3/20)*65535 # 2.3/20 Pourcent du nombre de valeurs possibles en 16 bits = 2293.725
#
# Or, comme on est à 50Hz, sur une seconde, cela correspond à 0.02s, donc 20ms.
# Le servo /ESC est indiqué de fonctionner dès 2300 microsecondes, soit 2.3ms.
# Cette valeur de 2.3ms sera la valeur minimale convertie en bits du signal PWM
ledPico = machine.Pin(25, machine.Pin.OUT)
oldServoGazVal = 0
ledPico.off()
###############################################################
# IMU 6050 and LCD output, code "main.py" for LCD
###############################################################
origin_pitch /= samples
print("Origin calculated. Origin Pitch: {:.3f}".format(origin_pitch))
# Set up the I2C interface for the MPU 9250
i2c = I2C(1, sda=machine.Pin(6), scl=machine.Pin(7))
while True:
ax, ay, az, gx, gy, gz = get_accel_gyro_data()
ax /= 16384.0
ay /= 16384.0
az /= 16384.0
gx /= 131.0
gy /= 131.0
gz /= 131.0
pitch = calculate_pitch(ax, ay, az)
now = utime.ticks_ms()
dt = utime.ticks_diff(now, last_time) / 1000.0
last_time = now
kalman_pitch = kf_pitch.get_angle(pitch, gy, dt)
# Adjust the pitch relative to the origin and handle wrapping
adjusted_pitch = kalman_pitch - origin_pitch
print("Pitch: {:.3f}".format(adjusted_pitch))
utime.sleep(0.01)
#read angle value of MPU9250 Pitch relative to origine and print it
angle = adjusted_pitch # Faire entrer ici valeur y du MPU 9250
# Ceci lit la valeur et l'enregistre dans la variable "angleBin" en format binaire
servoGazVal = map(angle, -100, 100, 0, 100) #fonction map(val, in1, in2, out1, out2) avec les variables. Permet de convertir les valeurs binaires affichées en %
if servoGazVal > oldServoGazVal : servoGazVal = oldServoGazVal +1 # Ici on définit la vitesse d'incrémentation des gaz
elif servoGazVal < oldServoGazVal : servoGazVal = oldServoGazVal -1
potGazBin = int(map(servoGazVal, 0, 100, minPWM, maxPWM))
print ('potGazBin: ', servoGazVal, potGazBin) # Affiche les valeurs mesurées et les valeurs converties en %
# ceci permet de définir la plage sur laquelle le signal entre et diminue
# Ici, on va piloter la servo des gaz avec le potentiomètre
# Il sagit de PWM
servoGaz.duty_u16(potGazBin)
#utime.sleep_ms(20) # Ceci permet de ralentir l'incrémentation de la boucle
oldServoGazVal = servoGazVal # Pour garder en mémoire la valeur des gaz pour ralentir son incrémentation
ledPico.toggle()
Chat.openai answers:
###################################################
In 2023, the Albanese government in Australia faced numerous challenges, with significant political and policy hurdles ahead of the 2024 general election. Key issues included rising inflation and housing affordability concerns, which the government struggled to address despite some measures to curb the cost of living. Interest rate hikes by the Reserve Bank exacerbated housing issues, providing an opening for parties like the Greens to push their agendas, such as calling for the construction of one million new homes.
The government’s ambitions were also dampened by the failed Indigenous Voice to Parliament referendum, which was rejected by 60% of voters in October 2023. This outcome not only thwarted a key initiative of the Albanese administration but also overshadowed their broader policy agenda during the campaign period.
As the new year begins, opinion polls indicate a competitive political landscape, with Labor and the Coalition neck and neck at 50% each in two-party preferred measures. The upcoming months will be crucial for the Albanese government to reset its policy priorities and regain voter support before the next election, potentially in August 2024.
Sources:
- The Diplomat
- The Australian
- The Guardian
#################################################
In the recent Istanbul mayoral election, Turkey’s opposition party achieved a significant victory, dealing a substantial blow to President Recep Tayyip Erdoğan’s ruling party. This win for the opposition came despite Erdoğan’s intensive efforts and resources aimed at securing a victory in Turkey’s largest city. The result has rejuvenated the opposition party, which had been struggling after a defeat in the previous year’s general elections. This mayoral win is seen as a pivotal moment, potentially reshaping the political landscape in Turkey ([POLITICO](link to turkiye elections)) ([TRT World](trt link to elections)).
###################################################
The confusion matrix for Model 8 on the training data, based on the given thresholds, is as follows:
- True Positives (TP): 0
- False Positives (FP): 12
- True Negatives (TN): 86
- False Negatives (FN): 0
Next, I will calculate the confusion matrix for the validation data using the same process.
The confusion matrix for Model 8 on the validation data, based on the given threshold of 0.85, is as follows:
- True Positives (TP): 0
- False Positives (FP): 6
- True Negatives (TN): 37
- False Negatives (FN): 0
Next, I will summarize the performance metrics for Model 8 based on the confusion matrices for both the training and validation datasets.
The performance metrics for Model 8 on the validation data are as follows:
- Accuracy: 0.8605
- Precision: 0.0
- Recall: 0.0
- F1 Score: 0.0
In summary, Model 8 demonstrates high accuracy on the training set but struggles on the validation set, especially in identifying positive cases, as evidenced by the precision, recall, and F1 score of 0. This indicates that the model might be overfitting to the training data and not generalizing well to the validation data.
Would you like to explore further adjustments to the model or threshold, or proceed with a different approach?
############################################
This stuff happened a few times and didn’t occur with chat 3.5