我试图从红宝石文件打开连接到Arduino的LED,以及从该Arduino发送一个字符串到我的ruby文件/终端。 (我分开做这两件事,以避免潜在的问题)。
我使用USB端口连接Arduino - 计算机和serialport gem。我在Linux工作。
要在我的计算机上接收字符串:
我已经按照几个教程推荐运行这个ruby文件:
require 'serialport'
port_str = '/dev/ttyACM0'
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
while(true) do
message = sp.gets.chomp
puts message
end
并将其上传到Arduino:
uint8_t c;
int i;
void setup() {
Serial.begin(9600); // set baud rate
pinMode(13, OUTPUT); // set pin 13 to be output for LED
digitalWrite(13, LOW); // start with LED off
}
void loop() {
while (Serial.available() > 0) { // check if serial port has data
// writes to computer
Serial.println("Hello world");
}
}
我收到此错误消息:未定义的方法`chomp' for nil:NilClass(NoMethodError)。当摆脱.chomp时,我可以在某些时候获得“#Hello Hello"被打印在我的终端上,例如" Hell",然后很久以后" o"等等。
现在我甚至都没有得到任何东西了。
要开启指示灯:
在ruby文件中,我用
替换了消息部分 sp.write('a')
在arduino文件中,
void loop() {
while (Serial.available() > 0) { // check if serial port has data
c = Serial.read(); // read the byte
if (c == 'a'){
digitalWrite(13, HIGH); // turn on LED
delay(500); // wait 500 milliseconds
digitalWrite(13, LOW); // turn off LED
delay(500); // wait 500 milliseconds
}
}
}
如果我删除条件(c ==' a'),led会亮起,但显然我需要它,如果我想让arduino执行不同的操作。
我是串口通信的新手,所以我不太确定错误来自哪里,因为我觉得似乎某些某些数据似乎已被传输。