Serial issues when sending from arduino
in
Integration and Hardware
•
1 year ago
I had serial working until I tried adding a header. I want to be able to send a header incase I want to send other serial data or upgrade the board--sending header seems like a good practice, however I don't know what I broke. Been at it for few hours.
from what I understand arduino sends data as ASCII string if you use .print() so I use the following to send data from arduino:
- int IRpin = 1;
- void setup() {
- Serial.begin(9600);
- }
- void loop() {
- float volts = analogRead(IRpin)*0.0048828125;
- float distance = 65*pow(volts, -1.10);
- //map float to an int
- int i = (int) distance;
- Serial.print("Data,");
- Serial.print(i);
- Serial.print("\n");
- delay(100);
- }
easy enough. I can monitor this and it seems to be sending perfectly.
However in processing I then use parseInt to change it from ASCII string to an int so I can check against conditionals (I probably have no idea what I am talking about and this could be totally off, I am very used to JS and using var so string and int mean the same to me):
- int posX;
- int lastVal = 1000;
- int currentVal;
- void serialEvent(Serial p) {
- String message = myPort.readStringUntil('\n'); // read serial data
- if(message != null) {
- String [] data = message.split(","); // Split the comma-separated message
- println(data);
- if ( data[0].equals("Data")){
- if( data.length > 1 ){
- try {
- posX = Integer.parseInt(data[1]);
- println("parse worked");
- if(posX > 100) {
- scrollMe = 0;
- println("scroll me is 0");
- }
- if(posX < 100){
- if(posX > lastVal){
- scrollMe = scrollMe - 1;
- println("scroll me is -1");
- }
- if(posX < lastVal){
- scrollMe = scrollMe + 1;
- println("scroll me is 1");
- }
- }
- lastVal = posX;
- }
- catch (Throwable t) {
- print("error"); // parse error
- //print(message);
- }
- }
- }
- }
- println("====");
- }
what's stranger still (and super annoying for debugging) is that it seems to only read the serial connection once in a while, that might have to do with the readStringUntil, however I am not sure.
1