參考文章是用 raspberry 和 arduino 來做實驗
先從 raspberry 傳送到 arduino
在 arduino
.寫程式如下 : (可以參考 File->Examples->01.Basics->Blink. )const int ledPin = 13;
void setup(){
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop(){
if (Serial.available()) {
blink(Serial.read() - '0'); // convert the character '1'-'9' to decimal 1-9
}
delay(500);
}
void blink(int numberOfTimes){
for (int i = 0; i < numberOfTimes; i++) {
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
delay(100);
}
}
最主要就是使用 Serial 這個物件
void Serial.begin (9600) -> 鲍率 9600
bool Serial.available() -> check serial 有沒有message
int Serial.read() -> 傳回接收到的數字
在Raspberry
use pythonsudo vi main.py
#!/usr/bin/python
import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
ser.write('3')
大概就是RPI 傳送 3 出去....
從 arduino 傳送到 raspberry
在 arduino
void setup(){
Serial.begin(9600);
}
void loop(){
Serial.println("Hello, World!");
delay(1000);
}
多了一個function : Serial.println("Hello, World!");
在 raspberry
import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
while 1 :
ser.readline()</span>
多了一個function serial .readline()
執行的結果如下:
'Hello, World!\r\n' 'Hello, World!\r\n' 'Hello, World!\r\n' ...
不過我目前沒有arduino....所以我會用兩個RPI來互相傳送資料試試...
Reference : http://www.seeedstudio.com/recipe/166-basic-pi-lt-gt-arduino-communication-over-usb.html
沒有留言:
張貼留言