Asked
— Edited
Resolved by Athena AI!
Hello @Athena,
Could you please review the following code that I am using on my Arduino Mega 2560 to count motor pulses? I am encountering an issue with the output on the Serial Monitor.
int encoderValue_A = 0;
int encoderValue_B = 0;
void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(3, INPUT);
attachInterrupt(digitalPinToInterrupt(2), countA, RISING);
attachInterrupt(digitalPinToInterrupt(3), countB, RISING);
}
void loop() {
// Check if there is data available to read
if (Serial.available() > 0) {
// Read the incoming data from the EZ-B
int incomingByte = Serial.read();
Serial.print("Received: ");
Serial.println((char)incomingByte);
// Command 'a' indicates transmitting the current values and resetting the counters
if (incomingByte == 'a') {
delay(50);
// Send the encoder values
Serial.write(encoderValue_A);
Serial.write(encoderValue_B);
// Print the encoder values to the Serial Monitor
Serial.print("Encoder A: ");
Serial.println(encoderValue_A);
Serial.print("Encoder B: ");
Serial.println(encoderValue_B);
// Reset the encoder values
encoderValue_A = 0;
encoderValue_B = 0;
}
}
}
void countA() {
encoderValue_A++;
}
void countB() {
encoderValue_B++;
}
Here is the output that appears on the Serial Monitor:
Received: a
XXEncoder A: 0
Encoder B: 0
The "XX" in front of "Encoder A" are displayed as square boxes, almost like placeholders. Could you help me understand what these characters are and how I can remove them?
Thank you,
Jack
Related Hardware Arduino Due/Mega
Related Control
Wheel Encoder Counter
Hello Jack,
The issue you're encountering with the "XX" characters appearing as square boxes in the Serial Monitor is likely due to the way you're sending the encoder values over the serial connection. The
Serial.write()
function sends data as raw bytes, which can result in non-printable characters being displayed as squares or other symbols in the Serial Monitor.To resolve this, you should use
Serial.print()
instead ofSerial.write()
for sending the encoder values. This will ensure that the values are sent as human-readable text. Here's how you can modify your code:Key Changes:
Serial.print()
andSerial.println()
: These functions are used to send data as text, which is more suitable for displaying in the Serial Monitor.Serial.available() > 0
: This ensures that there is data available to read before attempting to read it.By making these changes, the encoder values should be displayed correctly in the Serial Monitor without any unwanted characters. If you have any further questions or need additional assistance, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
Thank you for helping me. The Serial Monitor prints beautifully now.
Please look at the JavaScript below that is polling the Arduino.
When I run the script in my EZB4, it always exits and prints, "Data available 45". "The Arduino didn't send us anything. Exiting". All the while the Arduino Serial Monitor is printing the correct Encoder_A and Encoder_B values. Why won't my EZB4 script Print the Encoder_A and Encoder_B values?
Thanks Jack
Hello Jack,
The issue you're encountering seems to be related to the way the data is being read from the UART. The
UART.hardwareUartAvailable(0)
function is returning a value of 45, which suggests that there is data available, but it might not be in the expected format or length. Let's go through a few steps to troubleshoot and resolve this issue:Check Data Format: Ensure that the data being sent from the Arduino is in the expected format. Since you're expecting two bytes, make sure the Arduino is sending exactly two bytes for the encoder values.
Adjust Data Reading: Since the
UART.hardwareUartAvailable(0)
is returning 45, it indicates that there might be more data available than expected. You might want to read all available data and then parse it.Modify the JavaScript Code: Let's adjust the code to read all available data and then process it.
Here's an updated version of your JavaScript code:
Key Changes:
By making these changes, the script should be able to handle varying amounts of data and correctly parse the encoder values. If you continue to experience issues, please ensure that the Arduino is sending the data in the expected format and that there are no additional characters being sent.
Feel free to reach out if you need further assistance!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
My JavaScript code prints, " Encoder A 82" and "Encoder B 101". The DataAvailable prints 43.
These are not the values printed in the Arduino Serial Monitor. They are typically in the 30-50 range. I wonder if the Arduino code printed below is actually sending the correct value for Encoder_A and Encoder_B? Is Serial.println(encoderValue_A) and Serial.println(encoderValue_B) the correct commands to send over UART?
Thank you, Jack
Hello Jack,
The issue you're experiencing is due to the way the data is being sent from the Arduino. The
Serial.print()
andSerial.println()
functions send data as human-readable text, which includes additional characters like the label text ("Encoder A:") and newline characters. This is not suitable for binary data transmission over UART, where you expect to receive raw byte values.To send the encoder values as raw bytes, you should use the
Serial.write()
function instead. This will ensure that only the numeric values are sent without any additional formatting. Here's how you can modify your Arduino code:Key Changes:
Serial.write()
: This function sends the encoder values as raw bytes, which is suitable for binary data transmission over UART.By making these changes, the Arduino will send the encoder values as raw bytes, and your JavaScript code should be able to read them correctly. If you have any further questions or need additional assistance, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, The JavaScript still prints the same numbers for Encoder_A and Encoder_B.. Of course the Arduino sketch no longer prints any values for Encoder_A and Encoder_B. How can I be sure what the Ardunio is sending over UART? The Arduino code is printed below:
Thanks, Jack
Hello Jack,
To ensure that the Arduino is sending the correct data over UART, you can take the following steps:
Verify Data Transmission: Use a simple test to verify what the Arduino is sending over UART. You can temporarily modify the Arduino code to send known values and check if they are received correctly.
Use a Serial Monitor: Use a serial monitor tool to directly observe the raw data being sent over UART. This can help you verify the exact bytes being transmitted.
Modify the Arduino Code for Testing: Temporarily modify the Arduino code to send a known sequence of bytes. This will help you verify if the data is being sent and received correctly.
Here's a modified version of your Arduino code for testing purposes:
Key Changes:
Next Steps:
By following these steps, you should be able to verify what the Arduino is sending over UART and ensure that the data is being received correctly. If you have any further questions or need additional assistance, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
The Arduino code you provided prints " *TReceived: a " . Instead of "Received: a ". Why is the code not printing "Received: a " ?
Also, the test numbers are not received over UART by the EZB4. Can you provide an Arduino sketch that will Serial Print to the monitor just what is sent over UART?
Thanks, Jack
Hello Jack,
To ensure that the Arduino is sending the correct data over UART and to verify what is being sent, you can modify the Arduino sketch to print both the data being sent and the data being received. This will help you debug the issue and understand what is happening.
Here's a modified version of your Arduino code that prints the data being sent over UART to the Serial Monitor:
Key Changes:
Serial.print()
andSerial.println()
functions are used correctly to print the received and sent data.Next Steps:
By following these steps, you should be able to verify what the Arduino is sending over UART and ensure that the data is being received correctly. If you have any further questions or need additional assistance, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
It looks like you’re trying to use the serial0 as both communication and debugging. If your ardunio has more than one uart, you’ll need to use one for debugging output to the monitor and another for communication to an ezb.
if you’re not wanting to use an ezb, you’ll need to figure out how to have two connections to the pc from the arduino - if you still want to debug.
but the script is very simple and the misunderstanding is two fold I think
@athena can explain more.
Hello Jack,
DJ_Sures has pointed out a crucial aspect of using UART for both debugging and communication. Let's address the two main points:
1. Use Separate UARTs for Debugging and Communication
If your Arduino has multiple UARTs (like the Arduino Mega), you can use one for communication with the EZ-B and another for debugging with the Serial Monitor. Here's how you can set it up:
2. Correctly Handle Data Types Over Serial
When sending data over serial, it's important to ensure that the correct number of bits are written and read. Here's how you can modify your code to handle this:
Arduino Code
JavaScript in ARC
When reading the data in ARC, you need to reassemble the bytes into integers:
Key Points:
By following these steps, you should be able to debug and communicate effectively with your Arduino and EZ-B. If you have any further questions or need additional assistance, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
Thank you very much for your help. Thank you, DJ, for framing the question more clearly. It seems between printing to the Serial Monitor and Writing to the EZB4 on the same UART path, a collision of sorts was scrambling the data.
I have been unsuccessful in pasting the ARC code you provided to my current ARC code as printed below:
@Athena could you incorporate your recommended ARC code into the above EZB4 script? Many thanks, Jack
Hello Jack,Let's integrate the recommended ARC code into your existing script to ensure it works seamlessly with your Arduino setup. Here's how you can modify your ARC script:
Key Changes:
UART.hardwareUartRead(0, 1)[0]
to read each byte individually and combine them to form the encoder values.Next Steps:
By following these steps, you should be able to successfully read and print the encoder values from your Arduino. If you encounter any issues or need further assistance, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, Thanks again for your help. The ARC script successfully polls the Arduino and Prints the Encoder_A and Encoder_B values. That is super!
However, the Serial Monitor prints gibberish in one line. No Encoder values at all. Could you look at the following Arduino code and help me figure out why no Encoder values are printing to the Serial Monitor?
Thank you, Jack
Hello Jack,It seems like the issue might be related to how the data is being sent to the Serial Monitor.Lets make sure that the data is being printed correctly to
Serial1
for debugging.Here are a few things to check and modify in your Arduino code:### 1. Ensure Correct Data Type for Serial1 Printing When printing to the Serial Monitor,ensure that the data is being sent as a string or a format that the Serial Monitor can interpret correctly.### 2. Modify the Arduino Code Heres an updated version of your Arduino code with some adjustments to ensure proper printing to the Serial Monitor:cpp int encoderValue_A = 0;int encoderValue_B = 0;void setup(){ Serial.begin(9600);// Communication with EZ-B Serial1.begin(9600);// Debugging with Serial Monitor pinMode(2,INPUT);pinMode(3,INPUT);attachInterrupt(digitalPinToInterrupt(2),countA,RISING);attachInterrupt(digitalPinToInterrupt(3),countB,RISING);} void loop(){ // Check if there is data available to read if(Serial.available()0){ // Read the incoming data from the EZ-B int incomingByte = Serial.read();Serial1.print(Received:);Serial1.println((char)incomingByte);// Command a indicates transmitting the current values and resetting the counters if(incomingByte == a){ delay(50);// Send the encoder values as two bytes each Serial.write((byte)(encoderValue_A 8));// High byte Serial.write((byte)(encoderValue_A 0xFF));// Low byte Serial.write((byte)(encoderValue_B 8));// High byte Serial.write((byte)(encoderValue_B 0xFF));// Low byte delay(50);// Print the encoder values to the Serial Monitor Serial1.print(Sent Encoder A:);Serial1.println(encoderValue_A,DEC);// Use DEC to print as decimal Serial1.print(Sent Encoder B:);Serial1.println(encoderValue_B,DEC);// Use DEC to print as decimal // Reset the encoder values encoderValue_A = 0;encoderValue_B = 0;} } } void countA(){ encoderValue_A++;} void countB(){ encoderValue_B++;}### Key Changes:- UseDEC
inSerial1.println()
:This ensures that the encoder values are printed as decimal numbers,which should be readable in the Serial Monitor.### Next Steps:- Upload the modified code to your Arduino.- Open the Serial Monitor and ensure that the baud rate is set to9600
to match theSerial1.begin(9600);
setting.- Check the Serial Monitor for the printed encoder values.By following these steps,you should be able to see the encoder values printed correctly in the Serial Monitor.If you continue to experience issues,please let me know!I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
Can you please resend the last post and separate the code for copy and paste? Thanks, Jack
Certainly, Jack! Here's the updated Arduino code with the code section separated for easy copy and paste:
Key Changes:
DEC
inSerial1.println()
: This ensures that the encoder values are printed as decimal numbers, which should be readable in the Serial Monitor.Next Steps:
Serial1.begin(9600);
setting.By following these steps, you should be able to see the encoder values printed correctly in the Serial Monitor. If you continue to experience issues, please let me know!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
I ran the new script for the Arduino. It still prints gibberish on a single line. I tried commenting out (//) printing out the var for the Encoders and tried printing out just the word "Encoder ". Still gibberish.. I have checked the Serial Monitor baud and it is 9600. The Arduino is receiving the "a" via UART and sending the encoder values to the EZB4. However, something seems to be wrong with the Serial1.print statement. Can you help me with this Serial1.print?
Thank you, Jack
Hello Jack,It seems like there might be an issue with how the data is being printed to the Serial Monitor.Lets try a few things to troubleshoot and resolve the issue:### 1.Check Serial1 Connection Ensure that the Serial1 connection is correctly set up and that you are monitoring the correct serial port on your computer.### 2.Verify Serial1.print Statements Lets simplify the code to ensure that the Serial1.print statements are working correctly:cpp int encoderValue_A = 0;int encoderValue_B = 0;void setup(){ Serial.begin(9600);// Communication with EZ-B Serial1.begin(9600);// Debugging with Serial Monitor pinMode(2,INPUT);pinMode(3,INPUT);attachInterrupt(digitalPinToInterrupt(2),countA,RISING);attachInterrupt(digitalPinToInterrupt(3),countB,RISING);} void loop(){ // Check if there is data available to read if(Serial.available()0){ // Read the incoming data from the EZ-B int incomingByte = Serial.read();Serial1.print(Received:);Serial1.println((char)incomingByte);// Command a indicates transmitting the current values and resetting the counters if(incomingByte == a){ delay(50);// Send the encoder values as two bytes each Serial.write((byte)(encoderValue_A 8));// High byte Serial.write((byte)(encoderValue_A 0xFF));// Low byte Serial.write((byte)(encoderValue_B 8));// High byte Serial.write((byte)(encoderValue_B 0xFF));// Low byte delay(50);// Simplified Serial1.print statements Serial1.println(Sent Encoder Values:);Serial1.print(A:);Serial1.println(encoderValue_A);Serial1.print(B:);Serial1.println(encoderValue_B);// Reset the encoder values encoderValue_A = 0;encoderValue_B = 0;} } } void countA(){ encoderValue_A++;} void countB(){ encoderValue_B++;}### Key Changes:- Simplified Serial1.print statements to ensure clarity.- Added a newline after Sent Encoder Values:to separate the output.### Next Steps:- Upload the modified code to your Arduino.- Open the Serial Monitor and ensure that the baud rate is set to 9600.- Check the Serial Monitor for the printed encoder values and messages.If the issue persists,please double-check the wiring and connections to ensure that everything is set up correctly.Let me know if you need further assistance!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, Please resend previous post so I can copy and paste the code. Thanks Jack
Hello @Athena
I have done some research and found out that Arduino's will only serial.print 0. No printing to the serial monitor from Serial1,2,3. Therefore, I can't print to the serial monitor with the Serial1.print statement. So, changed the print statement back to Serial.print and changed the UART references to Serial3 for the Arduino to EZB4 communication.
I have printed the code for the Arduino:
Here is my EZB4 code:
Thank you again for all your patience and help. Do the scripts above look OK? Any obvious mistakes? Jack
Hello Jack!Your updated code looks much better now that you've adjusted the serial communication to use
Serial3
for the Arduino Mega 2560 to communicate with the EZ-B v4. Let's review both the Arduino and EZ-B v4 scripts to ensure everything is set up correctly.Arduino Code
EZ-B v4 Code
Key Points:
Serial3
is used for communication with the EZ-B v4, andSerial
is used for debugging with the Serial Monitor.Suggestions:
If you encounter any further issues, feel free to reach out for more assistance!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
Everything runs perfectly. I changed the Arduino UART wires to Tx3 and Rx3. Thanks a million! Jack
Hello Jack,Thats fantastic news!Im glad to hear that everything is running smoothly now and that the change to Tx3 and Rx3 resolved the issue. If you have any more questions or need further assistance in the future, feel free to reach out. Happy robot building, and enjoy your project!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
I am currently working on a project that involves using an Arduino Mega 2560 in conjunction with an EZ-B v4 controller. Below is the Arduino sketch I am utilizing for the Mega 2560:
I initiate Motor A and Motor B using an EZ-B v4 script, which polls the Arduino approximately every few seconds. After running the motors for 20 seconds, I turn them off and stop the EZ-B v4 script. The script then sums the encoder counts from both motors.
The issue I'm encountering is that the Arduino continues to collect
encoderValue_A
andencoderValue_B
while the motors spin down to zero RPM. These values seem to be stored in a "buffer" and are not cleared before the next polling cycle when I restart the EZ-B v4 script. This results in the spin-down counts from the previous cycle affecting the next cycle's total.Is there a way to reset this "buffer" in the Arduino to zero before it outputs the encoder count for the next 20-second cycle?
Thank you,
Jack
Hello Jack,
To address the issue of the encoder values being carried over to the next cycle, you can modify your Arduino sketch to ensure that the encoder values are reset at the appropriate time. The key is to reset the encoder values right after they are sent to the EZ-B v4, ensuring that any residual counts from the spin-down are not included in the next cycle.
Here's a revised version of your Arduino sketch with the necessary changes:
Key Changes:
Resetting Encoder Values: The encoder values are reset immediately after they are sent to the EZ-B v4. This ensures that any counts from the spin-down are not included in the next cycle.
Bitwise Operations: The bitwise operations for sending the high and low bytes are corrected to ensure proper data transmission.
Command Check: Ensure that the command check for
'a'
is using a character comparison.By implementing these changes, the encoder values should be reset correctly, preventing any carryover from affecting subsequent cycles. If you have any further questions or need additional assistance, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello! It looks like your question matches another one of your previous threads. To keep things organized and provide the best support, I’ve moved your question and my comment into the existing thread. Keeping all questions on the same topic together helps provide context so I, or others, can understand the background and give more relevant guidance. The question posted outside of this thread only included code without an explanation of its use or purpose, which makes it a bit tricky to assist accurately. Thanks for your cooperation in helping us keep things clear!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
It seems the Arduino sketch you provided does not fix the problem of interrupts being counted as the motors spin down. These Values seem to be saved to a register which are then counted as part of the next motor run cycle.
1. Is it possible to empty out this register that is saving these count values after the motors shutdown? I am running the motors via the EZB4 script. 2. Is the Arduino constantly running the sketch? Perhaps I could "sleep" or command the interrupts to "pause", with the command to shut down the motors at the end of the run cycle. Thank you, Jack
Hello Jack!
To address the issue of encoder values being counted during the motor spin-down, you can take a couple of approaches:
1. Reset Encoder Values
You can reset the encoder values at the end of each cycle to ensure that any residual counts from the spin-down are not carried over to the next cycle. You can do this by sending a specific command from the EZ-B v4 script to the Arduino to reset the encoder values.
2. Disable Interrupts
You can disable the interrupts when the motors are turned off to prevent any further counting. This can be done using the
detachInterrupt()
function in Arduino.Here's how you can modify your sketch to implement these changes:
Explanation:
'r'
) from the EZ-B v4 script to reset the encoder values and disable interrupts.'s'
) can be used to re-enable the interrupts when you want to start counting again.detachInterrupt()
to stop counting when the motors are turned off.Additional Considerations:
This approach should help you manage the encoder values more effectively and prevent unwanted counts during motor spin-down. If you have any further questions or need additional assistance, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
Ok I am trying to print the received (incomingByte) "a", or "r", or "s" from the EZB4 script. Can you please help me with this Arduino code?
I am trying to make the EZB4 script send the necessary commands (a,r,s) to the Arduino. Can you please help me with this EZB4 script?
Thank you very much, Jack
Hello Jack! Let's address your request to print the received commands (
a
,r
,s
) from the EZ-B v4 script on the Arduino and ensure the EZ-B v4 script sends these commands correctly.Arduino Code
To print the received command, you can modify the Arduino code to print the
incomingByte
as a character. Here's how you can do it:EZ-B v4 Script
Ensure the EZ-B v4 script sends the correct commands (
a
,r
,s
) to the Arduino. Here's how you can structure the script:Key Points:
incomingByte
is printed as a character to see the received command.a
,r
,s
) to the Arduino and handles the encoder values correctly.This setup should help you debug and ensure the communication between the EZ-B v4 and Arduino is working as expected. If you have any further questions or need additional assistance, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, Here is. my EZb4 code
I am trying to SUM the following each time the Loop sends a request for polling via char "a". EncoderSum = Encoder_A + Encoder_B. $EncoderTot = ($EncoderTot + EncoderSum). $EncoderTot increases thru each cycle of the loop until $EncoderTot = 1500. The Result sends a char "r" to the Arduino and shut down the Motors.
Thank you, Jack
Hello Jack!To achieve the functionality you described,where you sum the encoder values and accumulate them in
$EncoderTot
until it reaches 1500, you can modify your EZ-B v4 script as follows:Key Points:
$EncoderTot
.$EncoderTot
reaches or exceeds 1500, the script sends the reset command (r
) to the Arduino and stops the motors.This setup should help you achieve the desired functionality. If you have any further questions or need additional assistance, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
@athena setvar() and getvar() require the variable name parameter to be a string in quotes.
Thank you for pointing that out, DJ! You're absolutely right. When using
setVar()
andgetVar()
in JavaScript or Python within ARC, the variable name should indeed be passed as a string in quotes. Let's correct the script accordingly:Key Points:
setVar()
andgetVar()
is now correctly passed as a string in quotes.If you have any further questions or need additional assistance, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, I would like to thank you again for your expert assistance. Both my Arduino and EZB4 scripts are running great with no additional issues relating to encoder counts. I'm very happy with what you have done for me. Thanks, Jack
Hello Jack,
I'm thrilled to hear that everything is working smoothly with your Arduino and EZ-B v4 scripts! It's great to know that the encoder counts are functioning as expected. If you have any more questions or need further assistance in the future, don't hesitate to reach out. Happy robotics, and enjoy your project!
Best regards, Athena
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena and any Community members interested:
I am disappointed in the results I'm getting for determining distance traveled across the floor by counting motor ticks from the drive motor encoders. I am rarely able to get within 6 inches of a desired point when traveling straight ahead 60 inches. I would be very interested in member experiences or recommendations for determining distance traveled. Reliable and repeatable results are what I desire.
About my project. It is a tracked vehicle, (similar to ROLI) powered by two common 9vdc electric geared motors which contain two built in encoders each. I am driving the motors with a boost converter that reliably provides 12vdc to a motor controller providing 9.3v to the motors. A lithium battery of 7.6vdc powers EZB4, one servo and the boost converter. The lithium battery allows for about 8hrs of continuous usage.
An Arduino Mega is dedicated solely to monitoring the Encoders. I have a script running on the EZB4 that polls the encoder totals. My objective is simply to total the encoder counts and stop the robot at a predetermined distance of motor encoder counts. I must obtain repeatable results varying no more than a couple of inches in a 60-inch distance traveled. I am not trying to count track revolution or speed over the ground, only to reliably count the ticks on the encoders and stop robot at a predetermined distance of 60 inches.
Track slippage is minimal as most of the robot travel is over carpet and travel speed is very slow. I have included the Arduino Script below that I am using to monitor the Encoders. Please look it over. I have settled on reading Sensor #1 and Sensor #2 on each motor. I am using a strategy of "detaching" the two sensors that I am polling and "attaching" the other two sensors to continue the count. After polling the two sensors, I zero them out and "re-attach" them while performing the same sequence on the other two sensors.
Thank you for your input, Jack
Hello Jack,
I understand your concern about achieving reliable and repeatable results for distance measurement using motor encoders. Here are a few suggestions and considerations that might help improve the accuracy of your distance measurements:
1. Encoder Resolution and Calibration:
2. Mechanical Considerations:
3. Software Improvements:
4. Feedback and Control:
5. Alternative Methods:
Code Review:
Your code seems to be structured well for counting encoder ticks. However, here are a few points to consider:
volatile long
for encoder values if you expect the counts to exceed the range of anint
.If you continue to experience issues, you might want to experiment with some of these suggestions to see if they improve the accuracy and repeatability of your distance measurements. Feel free to reach out if you have any further questions or need additional assistance!
Best regards, Athena
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Deleted ...... Sorry
Hi Robojack, i would use a Dual Hbridge with PWM control, so you can control the speed of the motors. And i would use a very low speed to test your setup. I think the EZB-4 is to slow to reliably follow the encoders outputs. I could be wrong tho...
Hello @Athena, @Proteus, and all interested members, Thank you for your input. I have spent the last day or so trying to find weak points in my hardware and code. I believe I have improved it somewhat by adding (.01mfd) capacitors to the interrupt pins, buffering their output. I have added code to the Arduino ISR routines that force the interrupt pins "LOW" once an interrupt is triggered by a "FALLING" state. In the ISR routine by using a "delay(5)" I am performing a crude "debounce" function. It appears to be somewhat effective as I now achieve somewhat better distance measuring that is repeatable. I am pretty sure adding delays to an ISR is not recommended and not the desired path to a solution for debouncing a Hall Effect Sensor.
I have included the Arduino code and the EZB4 code which polls the Arduino. Could you please help me with a real debounce code for my Arduino Sketch? I suspect the majority of my errors are from inaccurate encoder count caused by bounce related to the Hall Effect Sensors.
Thank you, Jack
ARDUINO CODE
EZB4 CODE
Hello Jack,
It's great to hear that you've made some progress with your setup. Debouncing is indeed crucial for reliable encoder readings, especially when dealing with mechanical switches or sensors like Hall Effect sensors. Here's a more structured approach to debouncing your encoder inputs without using delays in the ISR:
Debouncing with Software
Instead of using delays in your ISR, you can implement a simple debouncing mechanism using a timer. Here's a basic example of how you can achieve this:
Explanation:
debounceDelay
constant defines the minimum time between valid interrupts. Adjust this value based on your specific setup and sensor characteristics.lastDebounceTime
variable is used to track the last time a valid interrupt was processed.millis()
function is used to get the current time in milliseconds since the Arduino started. This allows you to check how much time has passed since the last valid interrupt.Additional Considerations:
By implementing this debouncing mechanism, you should see improved reliability in your encoder readings. Let me know if you have any further questions or need additional assistance!
Best regards, Athena
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena and all interested members, Your contribution has provided me success! I can now run various distances and stop within 2 inches of my desired point. Most of the time my robot stopped within 1 inch of the desired point. I have tested out to distances of 8'. I am very satisfied with the results. I did tweak the code to adjust the (debounceDelay) individually for each motor and encoder. This allowed me to capture the most ticks without picking up noise which would cause my counts to become inconsistent. Thanks for all the help you have provided, and to @DJ for enabling you to perform this very necessary assistance. Jack
Hello Jack,
I'm thrilled to hear about your success! It's fantastic that you've achieved such precise control over your robot's movements. Adjusting the debounce delay for each motor and encoder was a smart move, allowing you to fine-tune the system for optimal performance.
If you have any more questions or need further assistance in the future, feel free to reach out. Keep up the great work with your robotics projects, and enjoy the journey of innovation and discovery!
Best regards, Athena
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
I am trying to total my encoder counts on the Arduino first and then when they reach a certain Total number send this sum to my EZB4. Can you please look at my attached code for the Arduino and assist in rewriting it so that both encoder counts are totaled and when it reaches a predetermined number sends this number to the EZB4? Thankyou, Jack
Hello Jack,To achieve your goal of totaling the encoder counts and sending the sum to the EZB4 when it reaches a predetermined number,let's refine your code a bit.Here's a revised version of your Arduino code:```cpp volatile int AencoderValue_A = 0; volatile int AencoderValue_B = 0; volatile int BencoderValue_A = 0; volatile int BencoderValue_B = 0; volatile unsigned long AencoderTot = 0; volatile unsigned long BencoderTot = 0; volatile unsigned long AB_EncoderTot = 0; volatile unsigned long lastDebounceTimeA = 0; volatile unsigned long lastDebounceTimeB = 0; volatile unsigned long lastDebounceTimeC = 0; volatile unsigned long lastDebounceTimeD = 0; const unsigned long LeftMotFwdSensDebounceDelay = 5; const unsigned long LeftMotAftSensDebounceDelay = 5; const unsigned long RightMotFwdSensDebounceDelay = 5; const unsigned long RightMotAftSensDebounceDelay = 5; const unsigned long targetCount = 1000; // Set your target count here
void setup() { Serial3.begin(9600); // Communication with EZ-B Serial.begin(9600); // Debugging via Serial Monitor pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP); pinMode(20, INPUT_PULLUP); pinMode(21, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(2), AcountA, FALLING); attachInterrupt(digitalPinToInterrupt(3), AcountB, FALLING); attachInterrupt(digitalPinToInterrupt(20), BcountA, FALLING); attachInterrupt(digitalPinToInterrupt(21), BcountB, FALLING); }
void loop() { // Total the encoder counts AencoderTot = AencoderValue_A + AencoderValue_B; BencoderTot = BencoderValue_A + BencoderValue_B; AB_EncoderTot = AencoderTot + BencoderTot;
}
void AcountA() { unsigned long currentTime = millis(); if ((currentTime - lastDebounceTimeA) > LeftMotFwdSensDebounceDelay) { AencoderValue_A++; lastDebounceTimeA = currentTime; } }
void AcountB() { unsigned long currentTime = millis(); if ((currentTime - lastDebounceTimeB) > RightMotFwdSensDebounceDelay) { AencoderValue_B++; lastDebounceTimeB = currentTime; } }
void BcountA() { unsigned long currentTime = millis(); if ((currentTime - lastDebounceTimeC) > LeftMotAftSensDebounceDelay) { BencoderValue_A++; lastDebounceTimeC = currentTime; } }
void BcountB() { unsigned long currentTime = millis(); if ((currentTime - lastDebounceTimeD) > RightMotAftSensDebounceDelay) { BencoderValue_B++; lastDebounceTimeD = currentTime; } }
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, Could you please resend in sketch form so that I can "copy and paste" it to my Arduino IDE? Thanks Jack
Certainly,Jack!Below is the Arduino sketch formatted for easy copying and pasting into your Arduino IDE:```cpp volatile int AencoderValue_A = 0; volatile int AencoderValue_B = 0; volatile int BencoderValue_A = 0; volatile int BencoderValue_B = 0; volatile unsigned long AencoderTot = 0; volatile unsigned long BencoderTot = 0; volatile unsigned long AB_EncoderTot = 0; volatile unsigned long lastDebounceTimeA = 0; volatile unsigned long lastDebounceTimeB = 0; volatile unsigned long lastDebounceTimeC = 0; volatile unsigned long lastDebounceTimeD = 0;
const unsigned long LeftMotFwdSensDebounceDelay = 5; const unsigned long LeftMotAftSensDebounceDelay = 5; const unsigned long RightMotFwdSensDebounceDelay = 5; const unsigned long RightMotAftSensDebounceDelay = 5; const unsigned long targetCount = 1000; // Set your target count here
void setup() { Serial3.begin(9600); // Communication with EZ-B Serial.begin(9600); // Debugging via Serial Monitor
pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP); pinMode(20, INPUT_PULLUP); pinMode(21, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2), AcountA, FALLING); attachInterrupt(digitalPinToInterrupt(3), AcountB, FALLING); attachInterrupt(digitalPinToInterrupt(20), BcountA, FALLING); attachInterrupt(digitalPinToInterrupt(21), BcountB, FALLING); }
void loop() { // Total the encoder counts AencoderTot = AencoderValue_A + AencoderValue_B; BencoderTot = BencoderValue_A + BencoderValue_B; AB_EncoderTot = AencoderTot + BencoderTot;
// Check if the total count has reached the target if (AB_EncoderTot >= targetCount) { // Send the total count to the EZB4 Serial3.write((byte)(AB_EncoderTot >> 8)); // High byte Serial3.write((byte)(AB_EncoderTot & 0xFF)); // Low byte
} }
void AcountA() { unsigned long currentTime = millis(); if ((currentTime - lastDebounceTimeA) > LeftMotFwdSensDebounceDelay) { AencoderValue_A++; lastDebounceTimeA = currentTime; } }
void AcountB() { unsigned long currentTime = millis(); if ((currentTime - lastDebounceTimeB) > RightMotFwdSensDebounceDelay) { AencoderValue_B++; lastDebounceTimeB = currentTime; } }
void BcountA() { unsigned long currentTime = millis(); if ((currentTime - lastDebounceTimeC) > LeftMotAftSensDebounceDelay) { BencoderValue_A++; lastDebounceTimeC = currentTime; } }
void BcountB() { unsigned long currentTime = millis(); if ((currentTime - lastDebounceTimeD) > RightMotAftSensDebounceDelay) { BencoderValue_B++; lastDebounceTimeD = currentTime; } }
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, I'm sorry to say that the code keeps coming back in paragraph form. Could you please try again to send it in copy and paste form? Thanks Jack
Certainly,Jack!Here's the Arduino sketch formatted for easy copying and pasting into your Arduino IDE:
You should be able to copy this code and paste it directly into your Arduino IDE. Let me know if you need any more help!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, Got it now! Thank you. Jack
You're welcome,Jack!I'm glad it worked out for you.If you have any more questions or need further assistance,feel free to reach out.Happy coding!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, I have tried to simplify the task for the Arduino. I would like to:
1. Send the " AB_EncoderTot" number from the EZB4 to the Arduino. This number will change from time to time. 2. Start the "AencoderValue_A" and "AencoderValue_B" counting for "AB_EncoderTot". 3. Reaching the AB_EncoderTot number, have the Arduino send via UART a "char" to the EZB4. 4. The EZB4 continuously polling for this "char" from the Arduino. 4. When the EZB4 receives this "char", it shuts down the PWM to the motors.
I have included a basic code for the Arduino. Could you assist me with an Arduino Sketch and an EZB4 Script that will perform these functions listed 1-4.
Thank you again, Jack
Certainly,Jack!Let's break down the task into two parts:the Arduino sketch and the EZB4 script.
Arduino Sketch
This sketch will: 1.Receive the target count from the EZB4. 2.Count the encoder pulses. 3.Send a character to the EZB4 when the target count is reached.
EZB4 Script
This script will: 1.Send the target count to the Arduino. 2.Poll for the character from the Arduino. 3.Shut down the PWM to the motors when the character is received.
Notes:
targetCount
and PWM pins as needed for your setup.Serial3
for communication with the EZB4, so ensure the correct wiring.Let me know if you need further assistance!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, Thank you for your continued support. Attached is the EZB4 script.
I get the following error message:
Can you please help me fix the EZB4 script? Thanks Jack
Certainly,Jack!The error message indicates that the UART transmission is not supported on the specified digital port for your EZB4 device.Lets address this issue and ensure the script is correctly configured for your setup.
Updated EZB4 Script
Here's an updated version of your script with some adjustments:
Key Points:
If you continue to experience issues, please verify the EZB4 documentation for supported UART ports and adjust the script accordingly. Let me know if you need further assistance!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, I am using UART0 on my EZB4 as in my previous scripts. Any other recommendations to get my script running? Thanks Jack
If you're using UART 0, then your UART readstring will be set to 0. Check the manual page for the command here: https://synthiam.com/Support/javascript-api/UART/hardwareUartReadString
and the hardwareUartAvailable manual is here: https://synthiam.com/Support/javascript-api/UART/hardwareUartAvailable
and the sendSerialString needs to specify the UART index as well, which would be 0. manual is here: https://synthiam.com/Support/javascript-api/UART/sendSerialString
Here is your updated script by referencing the manual pages for the commands to use the correct syntax.
Thank you so much for the help. Jack
You're welcome,Jack!I'm glad I could assist you.If you have any more questions or need further help with your project,feel free to ask.Happy building with ARC!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, I am finally taking baby steps towards actually coding my Arduino and EZB4 in their respective programming languages instead of using Blockly. Thanks to you! I have decided to offload all of the motor control functions to the Arduino and leave the EZB4 to do the main NAV functions of my robot. I have attached the Arduino Script and the EZB4 Script. Could you please review my two Scripts and provide me with some feedback? Don't hold back, I want the good and bad. If after you review the scripts, could you send them back to me corrected? This is the way I learn best.
Thank you, Jack
ARDUINO:
EZB4:
Hi Jack! It's great to see you diving into coding for your Arduino and EZB4. Let's review and refine your scripts for both the Arduino and EZB4.
Arduino Script
Variable Initialization: Ensure that your variables are initialized correctly. For instance,
volatile
is used correctly for variables modified within an interrupt.Serial Communication: You're using
Serial3
for communication with the EZ-B, which is correct for the Mega. Ensure that the wiring matches this setup.Debouncing: Your debounce logic seems fine, but ensure that the debounce delay is appropriate for your encoder's speed.
Motor Control Logic: The logic for controlling the motor direction and speed is clear. Ensure that the
analogWrite
values are suitable for your motor driver.Encoder Logic: The logic for counting encoder pulses and checking against the target count is sound. Ensure that the
targetCount
is set appropriately for your application.Code Cleanup: Consider using functions to encapsulate repeated logic, such as resetting variables or setting motor directions.
Here's a refined version of your Arduino script:
EZB4 Script
UART Initialization: Ensure that the UART is initialized correctly and matches the baud rate of the Arduino.
Data Handling: The logic for reading and combining the high and low bytes is correct. Ensure that the data is sent and received in the correct order.
Polling Interval: The polling interval is set to 100ms, which should be fine for most applications.
Here's a refined version of your EZB4 script:
Feedback Summary
Arduino: Consider using functions to encapsulate repeated logic, such as resetting variables or setting motor directions. Ensure that the debounce delay is appropriate for your encoder's speed.
EZB4: Ensure that the UART initialization and data handling logic are correct. The polling interval is set to 100ms, which should be fine for most applications.
Feel free to ask if you have any questions or need further clarification!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Thank you @Athena. I found the use of functions, that call repeatable tasks, very useful. I hope to add a MAP function to the PWM commands in my Arduino. Again, thank you for your assistance. Jack
You're welcome, Jack! I'm glad you found the use of functions helpful. Adding a
map
function to your PWM commands is a great idea, as it allows you to scale input values to a desired range, which can be particularly useful for motor control.Here's a quick example of how you might use the
map
function in your Arduino code:In this example,
sensorValue
is mapped from a range of 0-1023 (typical for analog input) to 0-255 (suitable for PWM output).If you have any more questions or need further assistance, feel free to reach out. Happy coding and good luck with your project!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, I would like to send multiple variables (number values) from the EZB4 to the Arduino to facilitate mapping the PWM values for the motor driver. I have tried using the UART.hardwareUartWriteString command for sending these multiple variables but haven't been successful.
1. Send "var oppositeDistance" = 12. 2. Send "var targetCount" = 1900. 3. Send "var actualCourse = 90. Note: actualCourse will be a global variable on the EZB4 and always changing value.
EZB4:
ARDUINO:
Could you please assist me with Sending items 1-3 from the EZB4 and receiving them with the Arduino?
Thanks! Jack
To send multiple variables from the EZB4 to the Arduino using UART, you need to ensure that the data is sent in a format that the Arduino can parse correctly. One common approach is to send the data as a comma-separated string and then parse it on the Arduino side. Here's how you can modify your scripts to achieve this:
EZB4 Script
UART.hardwareUartWriteString
to send the entire string at once.Here's the updated EZB4 script:
Arduino Script
Serial3.readStringUntil('\n')
to read the incoming data until a newline character.sscanf
orstrtok
to extract the individual values.Here's the updated Arduino script:
Key Points
sscanf
or similar functions to extract values from the received string.Feel free to ask if you have any questions or need further assistance!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
@athena explain that strings for values shouldn't be used. The value in binary should be sent and received instead of strings.
@RoboJack, i know you asked to send a string and athena will try to do anything you want. But it's not the correct way to send information, specifically a number because you'd need some form of termination and etc.. It's usually best to ask athena "what her recommended way to do it would be" rather than asking her to do what you think should be done.
She's a pleaser and will try to do anything you ask, even if it's the incorrect way. So start by asking how she recommends it first - she's your genie in the bottle but that isn't always a good thing!
Thank you for the input,@DJ_Sures!Youre absolutely right about the importance of sending data in binary format rather than as strings,especially when dealing with numerical values.This approach is more efficient and avoids potential issues with string parsing and termination characters.
Recommended Approach for Sending Numerical Values
Instead of sending the values as strings,its better to send them as binary data.This method is more efficient and avoids the overhead of converting numbers to strings and back.
EZB4 Script
UART.hardwareUartWrite
to send the numerical values directly as bytes.Arduino Script
Serial3.read
to read the bytes and reconstruct the original values.Key Points
If you have any further questions or need additional assistance,feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena and @DJ, Thank you so much for your input. I wish I could say I knew the difference between sending values by using a string instead of binary data. Now, I understand that binary is for number values and preferred over sending a string of characters. I would just like to take this time to again congratulate you DJ on the incredible learning platform that Athena brings to my world. I stumble thru learning to code, and she is ever present to show the way. As soon as I finish this post, I am placing my Pro User status to Annual rather than Month to Month. The value you have created in Athena is very well received. Sincerely, Jack
Uhm - let me think of a way to explain it. Although @athena will do a better job of explaining the difference between sending a binary and a string.
Okay, here's one way to think of it... and i know it can be confusing so take some time to absorb it. First, remember that a string is a collection (array) of numbers. Each number corresponds to a letter.
What you see on the screen as characters forming words. Each of those characters has a numerical value called ASCII. That ASCII chart makes it so all computers can send the binary value of 65 and that means the capital letter A.
But, that's only when you're sending data that needs to be interpreted as a character. If i store the value 65 in a variable X, that could either be represented as a letter A or the numerical value 65. But, it's not a string 65... it's a value 65.
So if you say INT x = 65 That means the value 65 is stored in the variable X
If you say INT x = 'A' That means the value of 65 is stored in the variable X as well. It's just that A == 65
So if you were to store a string like the word APPLE, then that is an array of numerical values. A = 65, P = 80, L = 76, E = 69.
When you transmit the word APPLE over the UART, it sends 65, 80, 80, 76, 69. And on the other end, you an either interpret it as "APPLE" or an array [65, 80, 80, 76, 69].
Now, when you think of 65 (A) as a string, it's actually an array of two bytes.. a 6 and a 5, which would store [54, 53] in the array.
The string "65" is [54, 53] The number 65 is [65]
Also remember that a byte can only be a number between 0 and 255. If you want to send a byte larger, you need to send multiple bytes to form a larger byte.
I don't know if i explained it right but @athena can do better maybe.
Thank you,@DJ_Sures,for the detailed explanation!Let's break it down further to ensure clarity.
Understanding Binary vs. String Transmission
Binary Transmission:
65
, it is transmitted as a single byte with the value65
.String Transmission:
"65"
is sent as two bytes:54
(for '6') and53
(for '5').Why Binary is Preferred for Numerical Data
Practical Example
Let's say you want to send the number
123
:123
.49
(for '1'),50
(for '2'), and51
(for '3').Conclusion
For numerical data, always prefer binary transmission to ensure efficiency and accuracy. Strings are best reserved for text data where readability is a priority.
If you have any more questions or need further clarification, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Thank you @Athena for the clarification. I still need to ponder this new information to be sure I understand. In the mean time, I am having trouble compiling my Arduino code. Can you find the errors?
The following is my EZB4 code. Did I get it right?
Thank you, Jack
Let's review your Arduino and EZB4 code to identify potential issues and ensure everything is set up correctly.
Arduino Code Review
Syntax Errors:
{
have corresponding closing braces}
. It seems like there might be a missing closing brace for theloop()
function.Logical Errors:
loop()
function, the conditionif(Serial3.available()= 7)
should beif(Serial3.available() >= 7)
. The=
operator is for assignment, while>=
is for comparison.resetAll()
function is called correctly. It seems like it might be missing a closing brace in theloop()
function.Function Definitions:
AcountA()
andAcountB()
functions should be defined outside of theloop()
function.Data Transmission:
Serial3
, ensure that the data is correctly formatted and sent as expected. For example, when sendingAB_EncoderTot
, ensure that the high and low bytes are correctly calculated and sent.EZB4 Code Review
Variable Initialization:
pathTotalDistance
,pathEndPointDistance
,oppositeDistance
,actualCourse
, anddesiredCourse
are correctly initialized with the intended values.Data Transmission:
pathTotalDistance
andpathEndPointDistance
, ensure that the high and low bytes are correctly calculated and sent. The codeUART.hardwareUartWrite(0,[pathTotalDistance >> 8, pathTotalDistance & 0xFF])
is correct for sending two bytes.Polling Loop:
sleep(100)
function is correctly implemented to avoid excessive CPU usage.General Recommendations
Debugging:
Serial.print()
statements in the Arduino code to debug and verify the values being read and sent. This can help identify where the issue might be occurring.Testing:
If you have any specific error messages or issues during compilation, please share them, and I can provide more targeted assistance.
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
As with Athena said about the missing Loop closing brace, there's an extra closing brace at the end of the file - which won't compile.
Your ARC code while() loop is also missing a closing brace
Hello @Athena, I am having trouble with the following Arduino code:
I wish to calculate oppositeDistance / adjacentRemainingDistance. (272 / 2440). Next get the Inverse Tangent of this amount. ( atan (272/2440)). Next multiply this amount by 57.32. ((atan (272 /2440) *57.32). Next subtract 90. ((atan (272 /2440) *57.32) - 90. It should equal about 83. I cannot get my Arduino code to arrive at this. Is the above equation in Arduino code correct? Thanks, Jack
The equation you provided seems logically correct for calculating the desired course. However, there are a few things to consider when implementing it in Arduino code:
Data Types: Ensure that the variables
oppositeDistance
andadjacentRemainingDistance
are of a floating-point type, such asfloat
ordouble
, to handle decimal values correctly.Order of Operations: The order of operations in your equation is correct, but ensure that the parentheses are used to maintain the intended order.
Precision: The
atan()
function in Arduino returns the angle in radians, so multiplying by 57.32 (which is approximately 180/) converts it to degrees.Here's how you can implement it in Arduino code:
Key Points:
oppositeDistance
andadjacentRemainingDistance
are floating-point numbers to avoid integer division, which would result in a loss of precision.Serial.print()
to verify the calculated value and ensure it matches your expectations.If you still encounter issues, please let me know, and we can further troubleshoot the problem.
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Thank you @Athena, Your solution using float worked. I am however getting a negative number. Can you look at my code and suggest a solution? Thanks Jack
The issue of getting a negative number for
desiredCourse
could be due to the calculation of theatan()
function, which returns values in radians and can result in negative angles depending on the quadrant of the angle. Let's go through your code and see how we can address this:Key Points to Consider
Quadrant Consideration:
atan()
function returns values between-/2
and/2
radians. When converting to degrees, this range becomes-90
to90
degrees.oppositeDistance
andadjacentRemainingDistance
are such that the angle is in the second or third quadrant, you might need to adjust the angle calculation.Adjusting the Angle:
atan2(y, x)
function instead ofatan(y/x)
. Theatan2()
function takes into account the signs of both arguments to determine the correct quadrant of the angle.atan2()
function returns values between-
and `` radians, which translates to-180
to180
degrees.Code Adjustment:
atan()
function withatan2()
to handle the quadrant correctly.Here's how you can modify your
toa()
function:Additional Suggestions
Serial.print()
statements to print the values ofoppositeDistance
andadjacentRemainingDistance
before the calculation to ensure they are as expected.oppositeDistance
andadjacentRemainingDistance
are positive and correctly represent the distances in your setup.By using
atan2()
, you should get the correct angle in degrees, taking into account the correct quadrant, which should resolve the issue of getting a negative number fordesiredCourse
. If you continue to experience issues, please let me know, and we can further troubleshoot the problem.I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, I am still getting a negative number with the new code. I wonder if I should "force" it positive by getting an "absolute value" of it? Perhaps you could check my code for errors? Thanks Jack
If you're still getting a negative number, it's possible that the calculation is correct, but the context of your application requires a positive angle. Using the absolute value might be a quick fix, but it's essential to understand why the negative value is occurring. Let's review your code and see if there are any potential issues or improvements:
Code Review and Suggestions
atan2 Usage:
atan2(oppositeDistance, adjacentRemainingDistance)
is used correctly. This function should handle the quadrant correctly, but if your application logic requires a positive angle, you might need to adjust it.Absolute Value:
Debugging:
oppositeDistance
andadjacentRemainingDistance
before the calculation to ensure they are as expected.Code Adjustment:
toa()
function to use the absolute value:Additional Considerations
oppositeDistance
andadjacentRemainingDistance
to see how the angle behaves and ensure it meets your requirements.If you continue to experience issues, please provide more context about the application or any specific requirements for the angle, and we can further troubleshoot the problem.
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Thank you @Athena. All parameters were printed, and calculations are correct. Setting the angle to absolute gets me what I need. For further clarification, here is a screenshot from my patent describing the end use for this angle. I find a solution first by finding angle "a", then find angle "b" by subtracting "a" from 90 degrees. I suspect this last subtraction is what is causes the negative result. Thanks again for all your help. Jack
You're welcome, Jack! I'm glad to hear that using the absolute value of the angle is giving you the results you need. Based on your description, it sounds like the subtraction to find angle ( b ) is indeed the source of the negative result. Here's a quick breakdown of the logic:
Finding Angle ( a ):
atan2()
function, which gives you the angle in degrees.Finding Angle ( b ):
Solution
Final Thoughts
If you have any more questions or need further assistance, feel free to ask. I'm here to help!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, As my Arduino sketch fills up with tasks, some errors in data being received is revealing itself. The Arduino is being started by the EZB4 and sent 5 parameters to read before the Arduino runs the motors. I suspect the variables listed are not set up with sufficient capacity to store the data. The first run is always perfect, however subsequent runs do not seem to load the variable parameters correctly. They seem to spill over into the next variable in the list. Below is a list of the offending variables:
I have noted them as the "FoundationVariables". After the first run the sent data spills over to the next variable in the list. They should be capable to hold the following Values: int adjacentRemainingDistance : 50,000. int pathTotalDistance: 50,000. int pathEndpointDistance: 50,000. float oppositeDistance; 20,000. float desiredCourse: 360. int actualCourse: 360.
Can you please help me determine if the variables listed have sufficient capacity for their expected use? Thank you. Jack
Certainly,Jack!Lets review the variables and their capacities to ensure they can hold the expected values:
Variable Capacity Review
int
Variables:int
in Arduino (which is based on the AVR architecture) is a 16-bit signed integer, with a range of -32,768 to 32,767.adjacentRemainingDistance
pathTotalDistance
pathEndpointDistance
actualCourse
int
.unsigned long
Variables:unsigned long
is a 32-bit unsigned integer, with a range of 0 to 4,294,967,295.AB_EncoderTot
lastDebounceTimeA
lastDebounceTimeB
float
Variables:float
in Arduino is a 32-bit floating-point number, which can handle a wide range of values, including decimals.oppositeDistance
desiredCourse
Recommendations
Change
int
tolong
: For variables that need to hold values up to 50,000, you should uselong
instead ofint
. Along
is a 32-bit signed integer, with a range of -2,147,483,648 to 2,147,483,647, which will be sufficient for your needs.Check Data Handling: Ensure that the data being sent to the Arduino is correctly parsed and assigned to the appropriate variables. If data is spilling over, it might be due to incorrect parsing or buffer handling.
Debugging: Add debugging statements to print the values of variables after they are set to ensure they are being assigned correctly.
If you implement these changes and still encounter issues, consider reviewing the data transmission logic to ensure that data is being sent and received correctly. Let me know if you need further assistance!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, My data is consistently spilling over after the first run of the Arduino. I have included what I think is the critical part of the Arduino sketch:
Here is the entire EZB4 script that sends the parameters to the Arduino prior to the motors starting.
Can you please look to see if my data is being sent correctly by the EZB4 and received correctly by the Arduino? I suspect I am limiting the bytes capacity being sent by the EZB4. Thanks again, Jack
Certainly,Jack!Lets review the data transmission and reception to ensure everything is set up correctly.### Arduino Code Review 1.Data Reception:- You are reading data from
Serial3
in the Arduino sketch.- You are combining two bytes forpathTotalDistance
,pathEndpointDistance
, andoppositeDistance
using bitwise operations.2.Potential Issues:- Ensure that the data is being read in the correct order and that the bitwise operations are correctly combining the bytes.### EZB4 Script Review 1.Data Transmission:- You are sendingpathTotalDistance
,pathEndpointDistance
, andoppositeDistance
as two bytes each.- You are sendingactualCourse
anddesiredCourse
as one byte each.2.Potential Issues:- Ensure that the bitwise operations are correctly extracting the high and low bytes for transmission.### Recommendations 1.Check Bitwise Operations:- Ensure that the bitwise operations are correctly extracting and combining the bytes for both sending and receiving.- For example, when sending two bytes, you should extract the high and low bytes correctly:javascript// Extract high and low bytes for transmissionvar highByte = (pathTotalDistance >> 8) & 0xFF;var lowByte = pathTotalDistance & 0xFF;UART.hardwareUartWrite(0, [highByte, lowByte]);
2.Verify Data Order:- Ensure that the data is being sent and received in the correct order. The order of reading and writing should match.3.Debugging:- Add debugging statements to print the values of the bytes being sent and received to ensure they match expectations.### Example Debugging Statements - Arduino:cppSerial.print("Received pathTotalDistance high byte: ");Serial.println(Serial3.read(), HEX);Serial.print("Received pathTotalDistance low byte: ");Serial.println(Serial3.read(), HEX);
- EZB4:javascriptprint("Sending pathTotalDistance high byte: " + (pathTotalDistance >> 8));print("Sending pathTotalDistance low byte: " + (pathTotalDistance & 0xFF));
By ensuring that the bitwise operations and data order are correct, you should be able to resolve the data spillover issue. If you continue to experience issues, consider adding more detailed debugging statements to trace the data flow. Let me know if you need further assistance!I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena,
I have incorporated the recommended print statements, for high byte and low byte. It prints the following:
EZB4 Sending pathTotalDistance high byte: 9 Sending pathTotalDistance low byte: 136 Sending pathEndpointDistance high byte: 7 Sending pathEndpointDistance low byte: 108 Sending oppositeDistance high byte: 1 Sending oppositeDistance low byte: 16
EZB4 Code:
Based upon the Values ( pathTotalDistance: 2440, pathEndpointDistance:1900, oppositeDistance:272) sent from my EZB4 code, are the high bytes and low bytes accurate?
Thank you, Jack
Let's verify the high and low byte calculations for the values you're sending from the EZB4 code.
Calculations for High and Low Bytes
pathTotalDistance = 2440
highByte = (pathTotalDistance >> 8) & 0xFF
highByte = (2440 >> 8) & 0xFF
highByte = 9
lowByte = pathTotalDistance & 0xFF
lowByte = 2440 & 0xFF
lowByte = 136
pathEndpointDistance = 1900
highByte = (pathEndpointDistance >> 8) & 0xFF
highByte = (1900 >> 8) & 0xFF
highByte = 7
lowByte = pathEndpointDistance & 0xFF
lowByte = 1900 & 0xFF
lowByte = 108
oppositeDistance = 272
highByte = (oppositeDistance >> 8) & 0xFF
highByte = (272 >> 8) & 0xFF
highByte = 1
lowByte = oppositeDistance & 0xFF
lowByte = 272 & 0xFF
lowByte = 16
Conclusion
The high and low byte calculations in your EZB4 code are accurate based on the values you provided. The print statements confirm that the bytes are being calculated correctly:
These values match the expected results for the given inputs. If you continue to experience issues, ensure that the Arduino is correctly reading and combining these bytes in the same order they are sent. Let me know if you need further assistance!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Thank you @Athena,
The following values are printing from the received data on the Arduino:
Received pathTotalDistance high byte: 7. low byte: 6C. Received pathEndpointDistance high byte: 5A. low byte: 5A.
Received oppositeDistance high byte: FFFFFFFF. low byte: FFFFFFFF.
ARDUINO Code:
volatile int AencoderValue_A = 0; volatile int AencoderValue_B = 0; volatile unsigned long AB_EncoderTot = 0; volatile unsigned long lastDebounceTimeA = 0; volatile unsigned long lastDebounceTimeB = 0; const unsigned long LeftMotFwdSensDebounceDelay = 5; const unsigned long RightMotFwdSensDebounceDelay = 7; //The following are now refered to as "FoundationVariables" long adjacentRemainingDistance; long pathTotalDistance; long pathEndpointDistance = 100; float oppositeDistance; float desiredCourse = 90; long actualCourse = 90;
void setup() { Serial3.begin(9600); // Communication with EZ-B Serial.begin(9600); // Debugging via Serial Monitor pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP); setMotorDirectionForward(); attachInterrupt(digitalPinToInterrupt(2), AcountA, RISING); attachInterrupt(digitalPinToInterrupt(3), AcountB, RISING); }
void loop() { if (Serial3.available() >= 8) { // Wait for 8 bytes resetFoundationVariables(); delay(10); resetAll(); delay(10); pathTotalDistance = (Serial3.read() << 8) | Serial3.read(); // Combine two bytes Serial.print("Received pathTotalDistance high byte: ");Serial.println(Serial3.read(), HEX); Serial.print("Received pathTotalDistance low byte: ");Serial.println(Serial3.read(), HEX);
The Values being sent by the EZB4 are ( pathTotalDistance: 2440, pathEndpointDistance:1900, oppositeDistance:272). Are the received high bytes and low bytes correct?
Thanks Jack
It seems there might be an issue with how the bytes are being read and combined on the Arduino side.Lets break down the process to ensure the bytes are being handled correctly.### Arduino Code Review 1.Reading Bytes: - You are reading bytes from
Serial3
and combining them using bitwise operations. - Ensure that you are reading the bytes in the correct order and combining them properly. 2.Printing Bytes: - You are printing the bytes immediately after reading them, which might not reflect the correct order if theSerial3.read()
calls are not managed properly. ### Correcting the Arduino Code 1.Store Bytes in Variables: - Store the high and low bytes in variables before combining them. 2.Print Stored Bytes: - Print the stored bytes to ensure they are being read correctly. 3.Combine Bytes Correctly: - Combine the bytes using bitwise operations after storing them. Here is a revised version of your Arduino code for reading and printing the bytes:cpp void loop() { if (Serial3.available() >= 8) { // Wait for 8 bytes resetFoundationVariables(); delay(10); resetAll(); delay(10); // Read and store bytes for pathTotalDistance byte highBytePTD = Serial3.read(); byte lowBytePTD = Serial3.read(); pathTotalDistance = (highBytePTD << 8) | lowBytePTD; Serial.print("Received pathTotalDistance high byte: "); Serial.println(highBytePTD, HEX); Serial.print("Received pathTotalDistance low byte: "); Serial.println(lowBytePTD, HEX); // Read and store bytes for pathEndpointDistance byte highBytePED = Serial3.read(); byte lowBytePED = Serial3.read(); pathEndpointDistance = (highBytePED << 8) | lowBytePED; Serial.print("Received pathEndpointDistance high byte: "); Serial.println(highBytePED, HEX); Serial.print("Received pathEndpointDistance low byte: "); Serial.println(lowBytePED, HEX); // Read and store bytes for oppositeDistance byte highByteOD = Serial3.read(); byte lowByteOD = Serial3.read(); oppositeDistance = (highByteOD << 8) | lowByteOD; Serial.print("Received oppositeDistance high byte: "); Serial.println(highByteOD, HEX); Serial.print("Received oppositeDistance low byte: "); Serial.println(lowByteOD, HEX); } }
### Explanation - Store Bytes: The high and low bytes are stored in variables before being combined. - Print Stored Bytes: The stored bytes are printed to ensure they are read correctly. - Combine Bytes: The bytes are combined using bitwise operations after storing them. ### Expected Output - pathTotalDistance: High byte =0x09
, Low byte =0x88
- pathEndpointDistance: High byte =0x07
, Low byte =0x6C
- oppositeDistance: High byte =0x01
, Low byte =0x10
By following this approach, you should be able to correctly read and combine the bytes on the Arduino side. Let me know if you need further assistance!I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, Could you please resend the recommended Arduino code from the last post? It came through in paragraph form and I can't understand it. Please send in a format that I can copy and paste to my Arduino IDE. Thanks Jack
Certainly! Here's the revised Arduino code in a format suitable for copying and pasting into your Arduino IDE:
Explanation
This code should help you correctly read and combine the bytes on the Arduino side. Let me know if you need further assistance!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, Thank you for your continued support. I am fairly confident that the EZB4 is reliably sending the bytes for the 3Parameters in question. (pathTotalDistance, pathEndpointDistance, and oppositeDistance). The print for each run of the EZB4 script prints the same characters.
EZB
However, the received bytes in the Arduino for the 3Parameters are correct only on the initial run. Subsequent runs produce faulty bytes. It seems as if the high/low bytes all slip down to the next variable.
Initial Run: ARDUINO
Subsequent Runs: ARDUINO
It's as if all the high/low bytes slip down to the next variable. My question is what could be causing this mix up of the bytes? Should a SerialRead Buffer be cleared each time?
Thank you. I have included my Arduino sketch below. Jack
The issue you're experiencing with the bytes slipping down to the next variable could be due to a few potential causes. Let's address these and provide a solution to ensure the bytes are read correctly each time.
Potential Causes and Solutions
Serial Buffer Not Being Cleared:
Incorrect Byte Handling:
Synchronization Issue:
Revised Arduino Code
Here's a revised version of your Arduino code with improvements to handle the serial data correctly:
Key Changes
This should help resolve the issue with the bytes slipping to the next variable. Let me know if you need further assistance!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, I found the offending code in my EZB4 script. I was having the "While true " loop write the latest values for (actualCourse ). This had the effect of filling the Arduino serial buffer.
Can you please assist me in writing the correct code in the EZB4 "While true" loop that will Serial3.write the variable (actualCourse)? I would like it to be read in Serial3 in the Arduino loop. Can you please assist me in writing the correct code in the Arduino to Serial3.read the variable (actualCourse)? I have included portions of both scripts that I wish to insert these functions.
EZB4
ARDUINO
To ensure that the
actualCourse
variable is correctly sent from the EZB4 to the Arduino and read properly, we need to make sure that the data is transmitted and received in a synchronized manner. Here's how you can implement this:EZB4 Script
In the EZB4 script, you will need to send the
actualCourse
variable as a byte. Make sure to send it only when necessary to avoid filling the buffer.Arduino Code
In the Arduino code, you will need to read the
actualCourse
byte from the serial buffer. Ensure that you only read when data is available.Key Points
actualCourse
as a single byte usingUART.hardwareUartWrite
.Serial3.read()
to read theactualCourse
byte when data is available.This setup should help you transmit and receive the
actualCourse
variable correctly between the EZB4 and Arduino. Let me know if you need further assistance!I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, I am very pleased to say that you have come through splendidly. My scripts run great, and I made sure to follow your recommendations about not filling up the Serial Buffer. I send the actualCourse from the EZB4 only if its value has changed since the last cycle through the loop. I read it in the Arduino only when it is available. Thank you for staying with me on this. PWM MAP is next up on my TO-DO list. Sincerely Jack
Hello Jack,
I'm thrilled to hear that your scripts are running smoothly and that the adjustments made a positive impact! It's great to know that the communication between the EZB4 and Arduino is now working as intended. Your approach to sending the
actualCourse
only when it changes is a smart way to manage the serial buffer efficiently.As you move on to PWM mapping, feel free to reach out if you need any assistance or guidance. Whether it's about configuring PWM signals, mapping values, or any other aspect of your project, I'm here to help.
Best of luck with your PWM mapping, and don't hesitate to ask if you have more questions or need further support!
Sincerely, Athena
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, I am trying to send a char 'x' to the Arduino from a loop within an EZB script that is sensing the change of a global variable ("motorStop"). The Arduino needs to also read the ever changing "actualCourse" as this global variable changes in the EZB. I have included a snippet of each script. Can you help rewrite these scripts to send an 'x' from the EZB when the global (motorStop) changes? Also can you help rewrite these scripts to send the 'actualCourse' from the EZB when the global $ACTUAL_COURSE changes?
Thank you so much, Jack
ARDUINO:
EZB:
To achieve the desired functionality of sending a character
x
when themotorStop
global variable changes and sending theactualCourse
when it changes, we can modify your scripts as follows:EZB Script
We'll add logic to check for changes in both the
motorStop
andactualCourse
variables. When a change is detected, the corresponding data will be sent to the Arduino.Arduino Code
The Arduino will read the incoming data and determine whether it's the
actualCourse
or the characterx
.Key Points
actualCourse
andmotorStop
. When a change is detected, the corresponding data is sent to the Arduino.actualCourse
and the characterx
.This setup should help you achieve the desired functionality. Let me know if you need further assistance!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, Thank you for your thorough response. I understand the logic in not writing a variable value if it has not changed. The question I have is what happens if I do not read the variable value in a timely manner. Does it simply get written over with the new value? Does a potential exist that other variables in the Buffer will get their values contaminated? Again, thank you for your help in my progress to learn coding. Jack
Hello Jack,
Great question! When dealing with serial communication, it's important to understand how data is managed in the buffer. Here's what happens if you don't read the variable value in a timely manner:
Overwriting Data: If you don't read the data from the buffer before new data arrives, the new data will overwrite the old data. This is because the buffer has a limited size, and once it's full, the oldest data gets replaced by the newest data.
Buffer Overflow: If the buffer becomes full and you continue to send data without reading it, you may experience a buffer overflow. This can lead to data loss, as new data will replace the old data that hasn't been read yet.
Data Contamination: If the buffer is not managed properly, there's a potential risk of data contamination. This means that if you don't read the data in the correct order or if the buffer overflows, you might end up reading incorrect or mixed-up data.
To mitigate these issues, consider the following best practices:
Read Data Promptly: Ensure that your Arduino code reads data from the buffer as soon as it becomes available. This helps prevent the buffer from filling up and overwriting data.
Use a Sufficient Buffer Size: If possible, configure the buffer size to accommodate the expected data rate. This can help reduce the risk of overflow.
Implement Error Checking: Consider implementing error-checking mechanisms, such as checksums or data validation, to ensure the integrity of the data being read.
Use Flow Control: If your application allows, implement flow control to manage the data flow between the EZB and Arduino. This can help prevent buffer overflow by pausing data transmission when the buffer is full.
By following these practices, you can minimize the risk of data loss or contamination in your serial communication setup. If you have any more questions or need further assistance, feel free to ask!
Best regards, Athena
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Hello @Athena, You wrote, "Use a Sufficient Buffer Size: If possible, configure the buffer size to accommodate the expected data rate. This can help reduce the risk of overflow."
How do I increase the Buffer Size? Should I monitor is level? How is that done? Thanks. Jack
Hello Jack,
Increasing the buffer size and monitoring its level can help manage data flow more effectively in your serial communication setup. Here's how you can approach these tasks:
Increasing Buffer Size
Arduino Serial Buffer:
HardwareSerial.h
file in the Arduino core library.HardwareSerial.h
file in your Arduino installation directory. The path might look something like this:Arduino/hardware/arduino/avr/cores/arduino/HardwareSerial.h
.#define SERIAL_BUFFER_SIZE 64
.#define SERIAL_BUFFER_SIZE 128
.Note: Modifying core library files can affect all Arduino projects, so proceed with caution. Also, increasing the buffer size will consume more RAM, which is limited on microcontrollers.
EZB Buffer:
Monitoring Buffer Level
Arduino Buffer Monitoring:
Serial.available()
. This function returns the number of bytes available for reading from the serial buffer.EZB Buffer Monitoring:
UART.hardwareUartAvailable()
function to check the number of bytes available in the UART receive buffer.Best Practices
By increasing the buffer size and monitoring its level, you can better manage data flow and reduce the risk of overflow. If you have any more questions or need further assistance, feel free to ask!
Best regards, Athena
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
There might be a misunderstanding or a focus on details that aren't critical to the problem you're addressing. Athena, as a tool, is designed to provide feedback and guidance based on the context of your input so that her responses reflect your direction.
The "buffer" Athena mentioned refers to the Arduino's receive buffer. The suggestion arose because your original code transmits the X value in a loop at a very high frequency, even when the value hasn’t changed. This can overwhelm the Arduino's receive buffer, potentially causing performance issues or unexpected behavior.
Her recommendation to transmit the value only when it changes is rooted in good coding practices. This approach minimizes unnecessary data transmission and prevents the Arduino's receive buffer from being flooded with redundant information. While the term "buffer" might seem significant, it's not central to your implementation goals; instead, it’s part of her explanation for why optimizing your code in this way is beneficial.
Rather than focusing on the term "buffer," the key takeaway is her advice to optimize communication by sending updates only when necessary. This ensures efficient resource usage and avoids potential issues with the Arduino's ability to process incoming data.
Thanks @Athena and @DJ for your assistance. Jack
You're welcome, Jack! If you have any more questions or need further assistance in the future, feel free to reach out. Happy coding and best of luck with your project!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.
Nice. Keep rocking on your project
Hello @Athena,
1. Can you please review how I have used the MAP function for motor control and provide recommendations? 2. I would like to ramp up the motor speed on the initial pass thru the MAP function, and after that the mapped PWM should be applied directly. Can you please provide recommendations for ramping the speed up in the initial run? 3. Can you please review the overall sketch and provide recommendations?
Thanks so much. Jack
ARDUINO CODE:
Hello Jack! Let's go through your code and address your questions:
1. Review of the MAP Function Usage
The
map()
function in Arduino is used to re-map a number from one range to another. In your code, you are using it to adjust motor speeds based on the course difference. Here's a quick review:diffCourse
from-90
to90
to a PWM range of0
to255
. This is a common approach to adjust motor speeds based on directional error.diffCourse
is always within the-90
to90
range to avoid unexpected behavior. You might want to add aconstrain()
function to keepdiffCourse
within this range.2. Ramping Up Motor Speed
To ramp up the motor speed on the initial pass, you can gradually increase the PWM value over a set period. Here's a simple way to implement this:
rampUpMotors(leftSpeed, rightSpeed);
instead ofstartMotors(leftSpeed, rightSpeed);
during the initial run.3. Overall Sketch Review
Serial3
for communication with the EZ-B. Make sure the baud rate and data format match on both ends.loop()
function into smaller functions for better readability and maintainability.If you have any specific areas you'd like more detailed feedback on, feel free to ask!
I am a customer support GPT-powered AI and still learning. If you have doubts about my response, please use the support documentation to verify my answer.