Arduino Sketch by CHAT GPT
Opdracht aan CHAT GPT
Create arduino code That receives data from xtrack true the serial interface
Labels defined: X-PWM pwm output for X-motor Y_PWM pwm output for Y-motor X_DIR indicates direction of movement for the X motor Y_DIR indicates direction of movement for the Y motor X-MOT controls the x-motor on/off X-MOT controls the x-motor on/off
The data consists of two floats wiht two decimals Xtrack sends a X and Y value seperated by a comma. The two received numbers must be between 0 and 360 If the received data <0 then the data is shown as 0.000, If the data >360 then the data is shown as 369.99 Show the treceived data on a I2C 20x4 display on i2c address 0x27 also count pulses received on interrupt0 and interrup1 and show those also on the LCD
The comments must be in dutch
Arduino Code
Het bevat de benodigde instructies om data van xtrack via de seriële interface te ontvangen en deze te gebruiken om de X- en Y-motoren aan te sturen. Het programma controleert of de ontvangen waarden binnen de juiste bereiken liggen, voordat ze worden verwerkt en op het 20x4 I2C-display worden weergegeven. Het telt ook de pulsen die zijn ontvangen op interrupt0 en interrupt1 en laat deze zien op hetzelfde display.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define X_PWM 3
#define Y_PWM 5
#define X_DIR 2
#define Y_DIR 4
#define X_MOT 6
#define Y_MOT 7
LiquidCrystal_I2C lcd(0x27, 20, 4);
float xVal, yVal;
int pulseCount0, pulseCount1;
void setup() {
pinMode(X_PWM, OUTPUT);
pinMode(Y_PWM, OUTPUT);
pinMode(X_DIR, OUTPUT);
pinMode(Y_DIR, OUTPUT);
pinMode(X_MOT, OUTPUT);
pinMode(Y_MOT, OUTPUT);
attachInterrupt(digitalPinToInterrupt(2), countPulse0, RISING);
attachInterrupt(digitalPinToInterrupt(3), countPulse1, RISING);
Serial.begin(9600);
lcd.init();
lcd.backlight();
}
void loop() {
if (Serial.available() > 0) {
String data = Serial.readStringUntil('\n');
int commaIndex = data.indexOf(',');
if (commaIndex != -1) {
String xString = data.substring(0, commaIndex);
String yString = data.substring(commaIndex+1);
xVal = constrain(xString.toFloat(), 0, 360);
yVal = constrain(yString.toFloat(), 0, 360);
if (xVal < 0) {
xVal = 0;
}
if (yVal < 0) {
yVal = 0;
}
if (xVal > 360) {
xVal = 369.99;
}
if (yVal > 360) {
yVal = 369.99;
}
analogWrite(X_PWM, map(xVal, 0, 360, 0, 255));
analogWrite(Y_PWM, map(yVal, 0, 360, 0, 255));
digitalWrite(X_DIR, xVal < 180 ? HIGH : LOW);
digitalWrite(Y_DIR, yVal < 180 ? HIGH : LOW);
digitalWrite(X_MOT, xVal > 0 && xVal < 360 ? HIGH : LOW);
digitalWrite(Y_MOT, yVal > 0 && yVal < 360 ? HIGH : LOW);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("X: ");
lcd.print(xVal, 2);
lcd.print(" Y: ");
lcd.print(yVal, 2);
lcd.setCursor(0, 1);
lcd.print("Pulse0: ");
lcd.print(pulseCount0);
lcd.setCursor(0, 2);
lcd.print("Pulse1: ");
lcd.print(pulseCount1);
}
}
}
void countPulse0() {
pulseCount0++;
}
void countPulse1() {
pulseCount1++;
}