【问题标题】:Wrong data transmission I2C RasPi->Arduino数据传输错误 I2C RasPi->Arduino
【发布时间】:2015-08-25 11:39:52
【问题描述】:

我正在修改我的 RaspberryPi 和我的 Arduino 以通过 I2C 发送一些文本。到目前为止我得到了它的工作,但出现了一个不应该存在的数字。

我正在发送“Hello”,将其转换为 int 数组并通过 I2C 发送。

['H','e','l','l','o'] => [72,97,108,108,111] // This should be the result
['H','e','l','l','o'] => [0, 5, 72, 101, 108, 108, 111] // This is what i get

前导 0 是故意的,但 5 根本不应该存在!

我在 Arduino 上运行的(缩短的)代码:

void setup() {
  Serial.begin(9600); // start serial for output
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);

  // define callbacks for i2c communication
  Wire.onReceive(receiveData);  
  Serial.println("Ready!");
}

receiveData(int byteCount) {
    int i;

    // Iterate through the byte packets
    for(i = 0; Wire.available(); i++) { 
        number = Wire.read();

        if(i != 0) {  // Ignore the first byte
            text[i-1] = (char)number;
        }

        // Output number, byteCount, and i over the serial bus
    }

    Serial.print("Result: ");
    Serial.println(text);
}

我得到的确切输出:

[CMD]data received: 0, 2char: , byteCount: 7, Iteration: 0 //The cmd byte
data received: 5, 2char: , byteCount: 7, Iteration: 1
data received: 72, 2char: H, byteCount: 7, Iteration: 2
data received: 101, 2char: e, byteCount: 7, Iteration: 3
data received: 108, 2char: l, byteCount: 7, Iteration: 4
data received: 108, 2char: l, byteCount: 7, Iteration: 5
data received: 111, 2char: o, byteCount: 7, Iteration: 6
Result: "Hello"

在树莓派(Python)上运行的代码:

import smbus
import time

# Initiate the SMBus on device 1
bus = smbus.SMBus(1)

# The address of the Arduino
address = 0x04

chars = [] # The character/int array
test = "Hello" # The test text

# Split up the string in individual chars, 
# convert them to int and add them to the array
for c in test:
    chars.append(ord(c))

# send the data... the 0 is the cmd byte! The function accepts an int array
bus.write_block_data(address, 0, chars) 

【问题讨论】:

  • 什么是电线? @thetruefreestyle
  • 不要尝试自己的 .先试试例子.....
  • @SDilmac 哦!对不起,我把它忘记在 src 中了! Wire 是处理 Arduino 上 I2C 接口的对象。
  • @SDilmac 为什么不自己尝试一下?我认为只关注示例和教程太简单了!
  • 在开始你自己的之前阅读文档和相关的 RFC。示例:读取使用过的 ic 文档以获取地址、总线和内存映射。否则会浪费很多时间(很快就无聊了)。电子产品需要大量计算。

标签: python arduino raspberry-pi i2c arduino-uno


【解决方案1】:

仅从显示的值来看,它很可能是在传输的字符串部分中发送的字符数或字节数。 "Hello" 有 5 个字节的 ASCII 表示。

如果您查看write_block_data 命令部分中对smbus protocol 的描述,它记录了在给出数据块长度的命令字节之后发送了一个 8 位计数。

SMBus 块写入:i2c_smbus_write_block_data()

与块读取命令相反,它最多写入 32 个字节到 一个设备,通过指定的寄存器 通讯字节。数据量在 Count 字节中指定。

S Addr Wr [A] Comm [A] 计数 [A] Data [A] Data [A] ... [A] Data [A] P

【讨论】:

  • 哦^^ 看来我在阅读文档时错过了那行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-25
  • 1970-01-01
  • 2018-08-22
  • 1970-01-01
  • 2014-11-14
相关资源
最近更新 更多