Skip to content

Instantly share code, notes, and snippets.

@hunandy14
Last active April 12, 2016 10:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hunandy14/8ca4066e16b188967b15d3010fb44d67 to your computer and use it in GitHub Desktop.
Save hunandy14/8ca4066e16b188967b15d3010fb44d67 to your computer and use it in GitHub Desktop.
兩台arduino,互相控制
#include <SoftwareSerial.h>
#include <Wire.h>
#include <Timer.h>
#define BTTX 2
#define BTRX 3
#define Led 13
#define ArduinoID 1
SoftwareSerial I2CBT(BTTX,BTRX);
char str[128]="";
void Init88(char str[128]);
Timer T1;
/*================================================*/
void setup(){
Serial.begin(9600);
I2CBT.begin(38400);
Serial.println("Welcom");
I2CBT.println("Welcom");
pinMode(Led, OUTPUT);
}
/*================================================*/
int Init_F=0,count=0;//88輸入完 /第幾次
int data[3];
int FinF=0; //三次輸入完
void loop(){
T1.update();
ScanSerialStr();
ScanI2cStr();
}
/*================================================*/
// 讀取次數(第幾次輸入資料)
void start(){
// Serial.println(count);
if (count==1){
data[0]=atoi(str);
Serial.println("Input times");
}
if (count==2){
data[1]=atoi(str);
Serial.println("Input second");
}
if (count==3){
data[2]=atoi(str);
count=0;
FinF=1;
Init_F=0;
}
Run();
}
// 讀取完畢之後執行
void Run(){
if (FinF==1){
FinF=0;
Serial.println("Led Run");
Serial.print("Input Data = ");
Serial.print(data[0]);
Serial.print(", ");
Serial.print(data[1]);
Serial.print(", ");
Serial.println(data[2]);
if (data[0]==ArduinoID)
T1.oscillate(Led, data[2], LOW, data[1]);
}
}
/*================================================*/
// 自定義Uart收到的
void ScanI2cStr(){
if(I2CBT.available()) {
int strnum=0;
memset( str, 0, strlen(str) );
while (I2CBT.available() > 0){
str[strnum++] = I2CBT.read();
delay(3);
}
Serial.print("I2CGet:");
Serial.println(str);
// I2CBT.print("I2CGet:");
// I2CBT.println(str);
count++;
Init88(str);
if (Init_F == 1){
start();
}
}
}
// ArudinoRxTx(USB) 收到的
void ScanSerialStr(){
if(Serial.available()) {
int strnum=0;
memset( str, 0, strlen(str) );
while (Serial.available() > 0){
str[strnum++] = Serial.read();
delay(3);
} str[strnum] = '\0';
// Serial.print("ScanSerialGet:");
// Serial.println(str);
// I2CBT.print("ScanSerialGet:");
I2CBT.print(str);
count++;
Init88(str);
if (Init_F == 1){
start();
}
}
}
// 收到之後判斷字串
void Init88(char str[128]){
// Serial.println("88");
if(strcmp(str,"88") == 0){
Init_F=1;
count=0;
Serial.println("Arduino is active.");
Serial.println("Input ID");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment