Communication between arduino and pc through serial

1. serial

There is an example of communicating with arduino by using python, this program can be utilized to transfer multiple data in the form of string type.
PC:

from time import sleep
import serial
ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1)
ser.reset_input_buffer()
sleep(1)
while True:
	data = ""
	if ser.inWaiting()>0:
		data = ser.readline()
		ser.flushInput()
	sleep(0.01)
	#separate the data by adding "="
	ser.write((str(cmd1)+"="+str(cmd2)+"="\
            +str(cmd3)+"="+str(cmd4)+"="\
            +str(cmd5)+"="+str(cmd6)+"="\
            +str(cmd7)+"="+str(cmd8)+"A\n").encode('utf-8'))

Arduino:

void readSerialPort() {
  msg = "";
  if (Serial.available()) {
    delay(10);
    while (Serial.available() > 0) {
      msg += (char)Serial.read();
    }
    Serial.flush();
  }
}

String msg="";
String data="";

void loop() {
	if (Serial.available()){
	  readSerialPort();
	  data = msg; //store the data
	  int i = 0;
	  int index = 1;
	  String msg1(""),msg2(""),msg3(""),msg4(""),msg5(""),msg6(""),msg7(""),msg8("");
	  while(data[i] != 'A'){
	    if(data[i] == '='){
	      index++;
	      i++;
	      continue;
	    }
	    //obtain the data from serial string
	    if(index == 1) msg1 += data[i];
	    if(index == 2) msg2 += data[i];
	    if(index == 3) msg3 += data[i];
	    if(index == 4) msg4 += data[i];
	    if(index == 5) msg5 += data[i];
	    if(index == 6) msg6 += data[i];
	    if(index == 7) msg7 += data[i];
	    if(index == 8) msg8 += data[i];
	    i++;
	  }
	  //Your code here, you can use toFloat() to change the data's form.
	  //-----
	}
}

2. rosserial

Additionally, we can use ros to realize the communication.

Arduino:

#include 
ros::NodeHandle node_handle;
sensor_msgs::JointState msg;
ros::Publisher pub("joystick", &msg);

char* id = "/joint";
char *a[] = {"FL", "FR", "BR", "BL","BA","BC","BV"};

void setup(){
  node_handle.getHardware()->setBaud(57600);
  node_handle.initNode();
  node_handle.advertise(pub);
  //define the msg, the header and the data'length have to be designated with respect to JointState
  msg.header.frame_id = id;
  msg.name_length = 7;
  msg.position_length = 7;
  msg.name= a;
  msg.position = pos;
}

void loop() {
	//TODO: Your code here, obtain the command from sensors such as joystick.
  msg.position[0] = x_; 
  msg.position[1] = y_; 
  msg.position[2] = z_; 
  msg.position[3] = rx_; 
  msg.position[4] = ry_;
  msg.position[5] = rz_; 
  msg.position[6] = h_;
  // msg.header.stamp = ros::Time::now();
  pub.publish( &msg );
  node_handle.spinOnce();
  delay(50);  
}

run the topic :

rosrun rosserial_arduino serial_node.py /dev/ttyACM0

你可能感兴趣的:(remote,control,arduino,joystick)