我一直在用C#阅读关于图像处理数据的文章。我需要发送到Arduino对象坐标。我用下面写的代码发送了关于x坐标的数据,但是我仍然不能发送y坐标,因为我不知道Arduino如何将x坐标和y坐标分开。是否有从两个不同的通道发送数据的方法?
if (serialok == true) {
int second =0;
int offset=300;
second = offset - Math.Abs(objectX);
map =(float) 0.85 * second;
buffer[0] = (byte)Math.Abs((int)map);
serialPort1.Write(buffer, 0, 1);这就是我从Arduino读取上述代码的方式。
if(Serial.available()>0) {
inbyte=Serial.read();
}
servo1.write(map(inbyte,0,255,0,180));
delay(15);对不起我的英语。
发布于 2018-04-30 13:50:27
执行部分的解决方案。
将数据合并为c#中的字符串,发送该sting值串行端口1,并在arduino上进行解析。
#include <Servo.h>
Servo servo1;
Servo servo2;
const byte numChars = 32;
char receivedChars[numChars];
char tempChars[numChars]; // temporary array for use when parsing
// variables to hold the parsed data
char messageFromPC[numChars] = {0};
int integerFromPC = 0;
float floatFromPC = 0.0;
boolean newData = false;
//============
void setup() {
Serial.begin(9600);
servo1.attach(2);
servo2.attach(4);
}
//============
void loop() {
recvWithStartEndMarkers();
if (newData == true) {
strcpy(tempChars, receivedChars);
// this temporary copy is necessary to protect the original data
// because strtok() used in parseData() replaces the commas with \0
parseData();
showParsedData();
newData = false;
}
}
//============
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
//============
void parseData() { // split the data into its parts
char * strtokIndx; // this is used by strtok() as an index
strtokIndx = strtok(tempChars,","); // get the first part - the string
strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC
strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
integerFromPC = atoi(strtokIndx); // convert this part to an integer
servo1.write(map(integerFromPC, 0, 255, 0, 180));
strtokIndx = strtok(NULL, ",");
floatFromPC = atoi(strtokIndx); // convert this part to a float
servo2.write(map(floatFromPC, 0, 255, 0, 180));
}
//============
void showParsedData() {
}https://stackoverflow.com/questions/47580483
复制相似问题