這篇文章一定要寫出來,實在不想每次調試arduino和processing串口通訊的時候都要測試半個小時了。。。

首先,這篇文章主要是討論processing和arduino之間串口通訊的。不解釋,做過arduino+processing的一定都遇到過這樣的問題,arduino/processing想要給對方發送數據,或者從對方接收到數據,各種函數不知道要怎么寫。。

先列一下二者串口的函數。。

processing

讀取

read()
readChar()
readBytes()
readBytesUntil()
readString()
readStringUntil()

寫入

write()

arduino

讀取

read()
readBytes()
readBytesUntil()
readString()
readStringUntil()

寫入

print()
println()
write()

下面根據使用場景列一下代碼

arduino給processing發送一個0-255的數字

arduino:

serial.write();

processing:

serial.read();

arduino給processing發送一個字符

processing

     import processing.serial.*;

Serial myPort;  // Create object from Serial class
int val;      // Data received from the serial port

void setup() 
{
size(200, 200);
// I know that the first port in the serial list on my mac
// is always my  FTDI adaptor, so I open Serial.list()[0].
// On Windows machines, this generally opens COM1.
// Open whatever port is the one you're using.
String portName = Serial.list()[1];
myPort = new Serial(this, portName, 9600);
}

void draw()
{
if ( myPort.available() > 0) {  // If data is available,
val = myPort.read();         // read it and store it in val
print(val);
}



}


void keyPressed(){

int i = 2;

myPort.write('2');
delay(100);

}

arduino

// Wiring/Arduino code:
// Read data from the serial and turn ON or OFF a light depending on the value

int val; // Data received from the serial port
int ledPin = 13; // Set the pin to digital I/O 4

void setup() {
Serial.begin(9600); // Start serial communication at 9600 bps
}

void loop() {
if (Serial.available()) { // If data is available to read,
val = Serial.read(); // read it and store it in val
if(val == '2'){
Serial.write('0');

}else
Serial.print(val);
}
}

arduino給processing發送一個大于255的數字

arduino

processing

Serial.println(number);

processing

String inString = myPort.readStringUntil('\n');
inString = inString.trim();
int number = int(inString);

arduino 連接串口攝像頭,獲取照片信息,然后通過串口發送給processing

arduino

//  File SerialCamera_DemoCode_CJ-OV528.ino
//  8/8/2013 Jack Shao
//  Demo code for using seeeduino or Arduino board to cature jpg format
//  picture from seeed serial camera and save it into sd card. Push the
//  button to take the a picture .
//  For more details about the product please check http://www.seeedstudio.com/depot/

#include <SPI.h>
#include <arduino.h>
#include <SD.h>

#define PIC_PKT_LEN    128                  //data length of each read, dont set this too big because ram is limited
#define PIC_FMT_VGA    7
#define PIC_FMT_CIF    5
#define PIC_FMT_OCIF   3
#define CAM_ADDR       0
#define CAM_SERIAL     Serial1

#define PIC_FMT        PIC_FMT_VGA

File myFile;

const byte cameraAddr = (CAM_ADDR << 5);  // addr
unsigned long picTotalLen = 0;            // picture length


/*********************************************************************/
void setup()
{
    Serial.begin(115200);
    CAM_SERIAL.begin(115200);
    // Serial.println("Initializing SD card....");
    pinMode(10,OUTPUT);          // CS pin of SD Card Shield

    if (!SD.begin(10)) 
    {
        // Serial.print("sd init failed");
        return;
    }
    // Serial.println("sd init done.");
    initialize();
}
/*********************************************************************/
void loop()
{

  if (Serial.available()) { // If data is available to read,
  int val = Serial.read(); // read it and store it in val
  if(val == '2'){



          preCapture();
          Capture();
          GetData();
          sendData();
 
   }
   }     
    
}
/*********************************************************************/
void clearRxBuf()
{
    while (CAM_SERIAL.available())
    {
        CAM_SERIAL.read();
    }
}
/*********************************************************************/
void sendCmd(char cmd[], int cmd_len)
{
    for (char i = 0; i < cmd_len; i++) CAM_SERIAL.print(cmd[i]);
}
/*********************************************************************/
void initialize()
{
    char cmd[] = {0xaa,0x0d|cameraAddr,0x00,0x00,0x00,0x00} ;
    unsigned char resp[6];

    CAM_SERIAL.setTimeout(500);
    while (1)
    {
        //clearRxBuf();
        sendCmd(cmd,6);
        if (CAM_SERIAL.readBytes((char *)resp, 6) != 6)
        {
            continue;
        }
        if (resp[0] == 0xaa && resp[1] == (0x0e | cameraAddr) && resp[2] == 0x0d && resp[4] == 0 && resp[5] == 0)
        {
            if (CAM_SERIAL.readBytes((char *)resp, 6) != 6) continue;
            if (resp[0] == 0xaa && resp[1] == (0x0d | cameraAddr) && resp[2] == 0 && resp[3] == 0 && resp[4] == 0 && resp[5] == 0) break;
        }
    }
    cmd[1] = 0x0e | cameraAddr;
    cmd[2] = 0x0d;
    sendCmd(cmd, 6);
    // Serial.println("\nCamera initialization done.");
}
/*********************************************************************/
void preCapture()
{
    char cmd[] = { 0xaa, 0x01 | cameraAddr, 0x00, 0x07, 0x00, PIC_FMT };
    unsigned char resp[6];

    CAM_SERIAL.setTimeout(100);
    while (1)
    {
        clearRxBuf();
        sendCmd(cmd, 6);
        if (CAM_SERIAL.readBytes((char *)resp, 6) != 6) continue;
        if (resp[0] == 0xaa && resp[1] == (0x0e | cameraAddr) && resp[2] == 0x01 && resp[4] == 0 && resp[5] == 0) break;
    }
}
void Capture()
{
    char cmd[] = { 0xaa, 0x06 | cameraAddr, 0x08, PIC_PKT_LEN & 0xff, (PIC_PKT_LEN>>8) & 0xff ,0};
    unsigned char resp[6];

    CAM_SERIAL.setTimeout(100);
    while (1)
    {
        clearRxBuf();
        sendCmd(cmd, 6);
        if (CAM_SERIAL.readBytes((char *)resp, 6) != 6) continue;
        if (resp[0] == 0xaa && resp[1] == (0x0e | cameraAddr) && resp[2] == 0x06 && resp[4] == 0 && resp[5] == 0) break;
    }
    cmd[1] = 0x05 | cameraAddr;
    cmd[2] = 0;
    cmd[3] = 0;
    cmd[4] = 0;
    cmd[5] = 0;
    while (1)
    {
        clearRxBuf();
        sendCmd(cmd, 6);
        if (CAM_SERIAL.readBytes((char *)resp, 6) != 6) continue;
        if (resp[0] == 0xaa && resp[1] == (0x0e | cameraAddr) && resp[2] == 0x05 && resp[4] == 0 && resp[5] == 0) break;
    }
    cmd[1] = 0x04 | cameraAddr;
    cmd[2] = 0x1;
    while (1)
    {
        clearRxBuf();
        sendCmd(cmd, 6);
        if (CAM_SERIAL.readBytes((char *)resp, 6) != 6) continue;
        if (resp[0] == 0xaa && resp[1] == (0x0e | cameraAddr) && resp[2] == 0x04 && resp[4] == 0 && resp[5] == 0)
        {
            CAM_SERIAL.setTimeout(1000);
            if (CAM_SERIAL.readBytes((char *)resp, 6) != 6)
            {
                continue;
            }
            if (resp[0] == 0xaa && resp[1] == (0x0a | cameraAddr) && resp[2] == 0x01)
            {
                picTotalLen = (resp[3]) | (resp[4] << 8) | (resp[5] << 16);
                // Serial.print("picTotalLen:");
                Serial.println(picTotalLen);
                break;
            }
        }
    }

}
/*********************************************************************/
void GetData()
{
    unsigned int pktCnt = (picTotalLen) / (PIC_PKT_LEN - 6);
    if ((picTotalLen % (PIC_PKT_LEN-6)) != 0) pktCnt += 1;

    char cmd[] = { 0xaa, 0x0e | cameraAddr, 0x00, 0x00, 0x00, 0x00 };
    unsigned char pkt[PIC_PKT_LEN];

    char picName[] = "pic.jpg";

    if (SD.exists(picName))
    {
        SD.remove(picName);
    }

    myFile = SD.open(picName, FILE_WRITE);
    if(!myFile){
        // CAM_SERIAL.println("myFile open fail...");
    }
    else{
        CAM_SERIAL.setTimeout(1000);
        for (unsigned int i = 0; i < pktCnt; i++)
        {
            cmd[4] = i & 0xff;
            cmd[5] = (i >> 8) & 0xff;

            int retry_cnt = 0;
            retry:
            delay(10);
            clearRxBuf();
            sendCmd(cmd, 6);
            uint16_t cnt = CAM_SERIAL.readBytes((char *)pkt, PIC_PKT_LEN);

            unsigned char sum = 0;
            for (int y = 0; y < cnt - 2; y++)
            {
                sum += pkt[y];
            }
            if (sum != pkt[cnt-2])
            {
                if (++retry_cnt < 100) goto retry;
                else break;
            }

            myFile.write((const uint8_t *)&pkt[4], cnt-6);
            //if (cnt != PIC_PKT_LEN) break;
        }
        cmd[4] = 0xf0;
        cmd[5] = 0xf0;
        sendCmd(cmd, 6);
    }
    myFile.close();
}




void sendData(){
    File photoFile = SD.open("pic.jpg");   
    
    if (photoFile) {   
        while (photoFile.position() < photoFile.size()) {   
    
      Serial.write(photoFile.read());   
        }

    }else{
      Serial.println("open photoFile failed");
    }   
    
     photoFile.close();   



}    

processing

    import processing.serial.*;  

    Serial myPort;  
    OutputStream output;  


    int flag = 0;
    int count = -1;

    String inString = "0";
    int pic_number;


    PImage img;


    void setup() {  

        size(800, 600);  

        //println( Serial.list() );  
        myPort = new Serial( this, Serial.list()[2], 115200);  
        myPort.clear();  


    }  


    void draw() {  



         
            while ( myPort.available () > 0 ) {
                if (flag == 0) {
                    inString = myPort.readStringUntil('\n');
                    inString =  trim(inString);
                    pic_number = int(inString);
                    println("pic_number: "+pic_number);
                    flag = 1;
                }else {
                    try {  
                    output.write(myPort.read());

                    }   
                    catch (IOException e) {  
                        e.printStackTrace();  
                    }  


                    count++;
                

                    if (count == pic_number) {


                        try {   
                            output.flush(); // Writes the remaining data to the file   //<>//
                            output.close(); // Finishes the file  

                        }   

                        catch (IOException e) {  
                            e.printStackTrace();  
                        }  


                        img = loadImage("pic.jpg");
                        image(img, 0, 0);
                        break;
                    }


                }
            }  
        


       




    }  


    void keyPressed() {  
        if(key == 'a'){
            output = createOutput("pic.jpg"); 
            myPort.write('2');
            flag = 0;
            count = 0;


            println("taking a photo");
        }
    }    

Tips:

這個函數很吊,trim()可以把兩邊的特殊符號去掉

用arduino自帶的串口調試軟件發送東西的時候相當于serial.println();所以會在內容后面帶上\t\n所以用serial.read的話是不能完全讀完的,像這樣

while(Serial.available() > 0){
  int temp = Serial.readString();
}

會得到奇怪的東西,這樣就可以了。。。

while(Serial.available() > 0){
  String temp = Serial.readString();
}

一個神奇的函數

可以節省很多代碼,來源是arduino樣例代碼里面的SerialCallResponse
split()

processing讀取大量數據

最近遇到一個問題,就是processing和arduino通訊傳輸大量數據然后發現有點問題。。我發現可能processing3.0對串口一些變化?因為這段代碼我以前是可以工作的

temp = myPort.readChar();
while( temp == 0xffff)
temp = myPort.readChar();

但是現在我一定要在while里面有個delay(1);才能工作。而且時間很長,要用幾百ms才能查詢到數據。。。
目前還不知道為什么。。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,247評論 6 543
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,520評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,362評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,805評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,541評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,896評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,887評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,062評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,608評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,356評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,555評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,077評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,769評論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,175評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,489評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,289評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,516評論 2 379

推薦閱讀更多精彩內容