|
想用两个uno分别做上位机和下位机,中间用串口通讯,TX RX 交叉连接,。上位机五个电位器对应控制下位机上的五个舵机角度。自己捣鼓了几天始终没能成功,主要问题应该是上下位机之间的通讯没弄好,现求高人指点 通讯用什么思路才能实现效果。现附上下位机程序求指点。
上位机程序:
//串口通讯 主机程序
#include<DFRobot_LiquidCrystal_I2C.h>
String comdata = "";
DFRobot_LiquidCrystal_I2C lcd1602;
inta1=80;
inta2=55;
inta3=160;
inta4=107;
inttest=45;
const int a1Pin=A0;
const int a2Pin=A1;
const int a3Pin=A2;
const int a4Pin=A3;
void setup() {
Serial.begin(9600);
lcd1602.begin(0x27);
lcd1602.printLine(uint32_t(1), "hello ");
delay(1000);
}
void loop() {
lcd1602.clear();
a1=analogRead(a1Pin);
// a2=analogRead(a2Pin);
// a3=analogRead(a3Pin);
// a4=analogRead(a4Pin);
a1=map(a1,0,1023,0,180);
// a2=map(a2,0,1023,0,180);
// a3=map(a3,0,1023,0,180);
// a4=map(a4,0,1023,0,180);
String a = String(a1);
// String b = String(a2);
// String c = String(a3);
// String d = String(a4);
//comdata = a+","+b+","+c+","+d;
//comdata = a;
//for(int i = 0;i <sizeof(comdata);i++){
// Serial.print(comdata[i]);
// Serial.write(comdata[i]);
// }
//lcd1602.printLine(uint32_t(1),a);
Serial.println(test);
//Serial.write(5);
comdata = String("");
delay(100);
Serial.flush ();
for(int i = 0;i <3;i++){
digitalWrite(13,HIGH);
delay(50);
digitalWrite(13,LOW);
delay(50);
}
}
下位机程序:
#include<DFRobot_LiquidCrystal_I2C.h>
#include <Servo.h>
#define numdata_length 1
String comdata = "";
int numdata[numdata_length] = {0};
int flag = 0;
DFRobot_LiquidCrystal_I2C lcd1602;
Servo myservo1;
Servo myservo2;
Servo myservo3;
Servo myservo4;
//*********************************************
void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
lcd1602.begin(0x27);
lcd1602.printLine(uint32_t(1), "hello ");
myservo1.attach(8);
myservo2.attach(9);
myservo3.attach(10);
myservo4.attach(11);
myservo1.write(30);
myservo2.write(30);
myservo3.write(30);
myservo4.write(30);
delay(1000);
myservo1.write(90);
myservo2.write(90);
myservo3.write(90);
myservo4.write(90);
}
//*********************************************
// 33,120,8,255 100,100,100,100
void loop() {
lcd1602.clear();
//lcd1602.printLine(uint32_t(1), "123");
//lcd1602.printLine(uint32_t(2), "456");
intj = 0;
while (Serial.available() > 0)
{
delay(100);
comdata += char(Serial.read());
delay(2);
flag = 1;
}
//如果接收到数据则执行comdata分析操作,否则什么都不做
if(flag == 1) {
for(int i = 0; i < comdata.length() ;i++){
if(comdata[i] == ','){
j++;
}
else{
numdata[j] = numdata[j] * 10 + (comdata[i] - '0');
}
}
lcd1602.printLine(uint32_t(1),numdata[0]);
delay(100);
myservo1.write(numdata[0]);
// myservo2.write(numdata[1]);
// myservo3.write(numdata[2]);
// myservo4.write(numdata[3]);
Serial.println(numdata[0]);
//Serial.println(numdata[1]);
//Serial.println(numdata[2]);
//Serial.println(numdata[3]);
for(int i = 0;i <3;i++){
digitalWrite(13,HIGH);
delay(50);
digitalWrite(13,LOW);
delay(50);
}
comdata= String("");
// for(int i = 0; i < numdata_length;i++){
// numdata[i] = 0;
// }
flag = 0;
}
Serial.flush ();
delay(100);
}
|
|