2 way communication c#

i'm wanting to send data from an ultra sonic sensor and an accelerometer from arduino to a c# project and send servo data from c# project to arduino to set servo position.

I've tried a few things but it got to be a bit of a mess and ended up crashing. have not got me head around sending servo data at all. sending distance data worked ok all on its own but when I tried sending data back to the arduino board it screws up.

Could some please explain a simple process to perform this. Can we not send and receive data in the same loop?

Can we not send and receive data in the same loop?

Well, I can. I can't tell about your capabilities, or code, since you failed to post any.

Jaychad:
Could some please explain a simple process to perform this.

The fundamental thing you need to decide is how the sending of messages will be controlled i.e. what events will cause messages to be sent - will each side send at regular intervals, or only in response to messages from the other side, or in response to events detected locally, or what?

Then you need to decide what your messages will contain and how they will be encoded. I recommend using an ASCII (textual) encoding scheme unless you have some compelling reason not to. Comma Separated Variable encoding works well for a wide range of applications.

Then you need to design the message sending and receiving mechanisms on each side. These will typically be similar and just consist of code to receive bytes and buffer them to form complete messages, and buffer and send the outgoing messages.

Then you need to design the code to validate and parse the incoming messages and format the outgoing messages. Output formatting it typically very simple - parsing received messages is typically much harder. There are various standard functions in the standard 'C' runtime library which can be used to separate a string into tokens, find specific characters or patterns in a string, and convert strings to numbers.

All messages from both sides are sent at regular intervals being a few times a second. c# program was supposed to send the data servo1,servo2,servo3 etc but instead of saying servo, declaring the required position.

The same for messages from arduino

c#

mainloop ( ) {
string data = _port.ReadLine ();
trgt.position = new Vector3 (0, 0, (float)((float.Parse (data) / 58.2) / 100));

int limbAngle =(Int32)(ServoLimbs[0].hingeJoint.angle);

_port.Write (limbAngle.ToString ());
}

that's what the c# code was supposed to be like

#include <Servo.h>

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

Servo elbowservo;  // create servo object to control a servo 
Servo shoulderservo;

int maximumRange = 400; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
  Serial.begin (9600);

  elbowservo.attach(2);  // attaches the servo on pin 9 to the servo object 
  shoulderservo.attach(3);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}
int lastDistance=-1;
char inChar; // Where to store the character read
byte index = 0; // Index into array; where to store the character
char inData[20]; 
void loop() {
  /* The following trigPin/echoPin cycle is used to determine the
   distance of the nearest object by bouncing soundwaves off of it. */

  //digitalRead 

  //shoulderservo.write(180);              // in steps of 1 degree 
  //elbowservo.write(180);              // tell servo to go to position in variable 'pos' 
  int incomingByte = 0;
  if (Serial.available() > 0) {
    // read the incoming byte:
    while(Serial.available() > 0) // Don't read unless
      // there you know there is data
    {
      if(index < 19) // One less than the size of the array
      {
        inChar = Serial.read(); // Read a character
        inData[index] = inChar; // Store it
        index++; // Increment where to write next
        inData[index] = '\0'; // Null terminate the string
      }
    }

    shoulderservo.write(ma int(inData));
    // say what you got:
    // Serial.print("I received: ");
    // Serial.println(incomingByte, DEC);
  }



  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2); 

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); 

  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);

  //Calculate the distance (in cm) based on the speed of sound.
  distance = duration;
  Serial.flush();
  if(lastDistance != distance)
  {
   
    Serial.println(distance);
    digitalWrite(LEDPin, LOW); 
    //}
    lastDistance == distance;
  }

  //Delay 50ms before next reading.
  delay(50);
}

That's the arduino.

I'm not very good at this I know. I'm trying to learn as I go. This doesn't include the accelerometer as it only just arrived. its an MMA7455 accelerometer

Moderator edit: Code tags. { sob }

shoulderservo.write(ma int(inData));

I don't think this will even compile. You can't CAST inData to an int. You need to CONVERT inData to an int, using atoi().

    lastDistance == distance;

A useless equality comparison.

Sorry everybody and Mr Moderator sir. I'm not a regular former.

Lets just start a fresh. Can someone demonstrate to me how this should be done. forget what I've done.

show me the correct c# send servo code and arduino receive code please. I can learn from there. I think

Jaychad:
show me the correct c# send servo code and arduino receive code please. I can learn from there. I think

Two questions:

When is our homework assignment due?
Is this going to be on the final?

funny. Its starting to feel like home work so thanks for that.

Not home work. I'm a stressed out 30 year old father of 7 starting a new project. I've done basic unity code and web design before. Just not the kind of thing where i'm using or creating external devices or microcontroller.

I always believed a forum was a place where one could learn not have fun poked at you but hey. I know i'm crap at this.

Jaychad:
I always believed a forum was a place where one could learn

It is, that's why PaulS posted constructive criticism on your code. Instead of trying to learn from what he pointed out, you shut down and just asked for the answer (working code), hence the comment about our homework assignment.

demonstrative, not working. But I get your point.

if(lastDistance != distance)
  {
   
    Serial.println(distance);
    digitalWrite(LEDPin, LOW); 
    //}
    lastDistance == distance;
  }

is what it was not

if(lastDistance == distance)
  {
   
    Serial.println(distance);
    digitalWrite(LEDPin, LOW); 
    //}
    lastDistance == distance;
  }

So it only sends the data when its different because my other code was dragging. This speeded it up quite a lot.

it was received by c#

string data = _port.ReadLine ();
trgt.position = new Vector3 (0, 0, (float)((float.Parse (data) / 58.2) / 100));

That works fine

the next c#:

int limbAngle =(Int32)(ServoLimbs[0].hingeJoint.angle);
			
_port.Write (limbAngle.ToString ());

its all in the same loop.

sends the data for the position to arduino here. I just don't know how to receive it. I get what was said before, I just don't know how to implement it. I'll grant you, I am a little distracted because of arguing children but that never changes at any time of day :drooling_face:

any way, at the _port.Write, my c# halts and doesn't continue.

I removed the sending of distance to the c# and removed the code to receive it to test it out. It stopped halting, but it wouldn't set the position of the servo. I get what was said about that, just showing me what I should do instead would be great.

I'll just go ahead and and rephrase what was already pointed out.

lastDistance == distance;

The comparison (==) and assignment (=) operator are not interchangeable.

shoulderservo.write(ma int(inData));

That is not how you convert an string (null-terminated array of chars) to an int. You need to use atoi().

I get what was said about that, just showing me what I should do instead would be great.

I though you were here to learn, not just get the answer?

shoulderservo.write(ma int(inData));

In some of the c# I've done you can do that. Think I just assumed it would work with this too.

Thanks for your pointers. I am here to learn an I have. Sometimes to learn you need to be told. That knowledge then can be interchanged later that's all. you sound quite annoyed. I guess i'm just used to other places helping by giving a bit of an answer. The pointers on technique helps a lot. But sometimes letting another person know how to do something by sharing a command works too. It's how we advance. it's not just an answer I was wanting, it was reasons behind the answer. which you all did.

When I said we'll just start a fresh, I meant from where I was cos I know it was worth crap.

Don't know why, but earlier i'd actually not seen the

atoi()

suggested. Don't know how I did. Just re read it now. get why people may have been a little annoyed.

Thanks guys