通过引脚从Arduino到RPi的串行通信

时间:2016-06-13 13:42:47

标签: python arduino ide raspberry-pi2 hardware-programming

我被困住了,不知道为什么。我试图分别通过TX和Rx引脚从Arduino Nano传输到RPi。

到目前为止我的代码:

Arduino TX:

void setup(){
  Serial.begin(9600);
}

void loop(){
  bProgramLoop = 1
  while(bProgramLoop == 1){
    Serial.write(1);
  }
}

Raspberry Side:

import serial
oSer = serial.Serial("/dev/ttyAMA0",baudrate=9600,timeout=1)

while True:
    sSerialInput = oSer.read(1)
    #sSerialInput = oSer.readline()
    print sSerialInput

将草图加载到Arduino并启动python脚本后,Raspberry根本不会读取任何内容。

注意:

  • 我已经通过分压器和一些跳线将来自Arduino的Tx引脚连接到RPi的Rx引脚。
  • 我也试过“readline()”,但没有运气

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我找到了解决问题的方法。我仍然是一个正常的菜鸟,但据我所知,通过Tx引脚发送串行数据是有问题的,因为它被usb端口使用,然后用于你的PC。

因此解决方案是使用SoftwareSerial库。我修改了我的两个代码草图如下:

Arduino的:

string = ""
string2 = ""
length = 0
lenght2 = 0
pad = ""


string = input("Enter String To Encrypt: ")
string2 = input("Enter PAD: ")

length = len(string)
length2 = len(string2)

textBinary = list(string)
pad = list(string2)
ciphertextBinary = list(string)
ciphertext = list(string)

for i in range(0, length):
    textBinary[i] = "{0:b}".format(ord(string[i]))
    for x in range(0, len(textBinary[i])):
        ciphertextBinary[i] = ciphertextBinary[i] + "a"

for i in range(0, length2):
    pad[i] = "{0:b}".format(ord(string2[i]))

for i in range(0, length):
    for x in range(0, len(textBinary[i])):
        if (textBinary[i])[x] == (pad[i])[x]:
            (ciphertextBinary[i])[x] = "0"
        elif (textBinary[i])[x] != pad[i][x]:
            (ciphertextBinary[i])[x] = "1"

for i in range(0, length):
    ciphertext[i] = int(ciphertextBinary[i], 2)
    print(chr(ciphertext[i]))

莓:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(4,3); // (RX,TX) - Pin Setup for any digital pins you want as Rx or Tx

void setup(){
  Serial.begin(9600);
  mySerial.begin(57600); // initialize serial communication with serial pin
}

void loop(){
  bProgramLoop = 1
  while(bProgramLoop == 1){
    mySerial.write("Anything");
  }
}

因为它是我能够将数据从Arduino传输到RPi。 HOWEVER ,我仍然遇到将字符串转换为整数或浮点数的问题。

请参阅此帖子了解详情:Python readline() returns string that wont convert to int or float