gpt4 book ai didi

c - Arduino 作为 I2C 从设备与 RPi 通信

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:26 29 4
gpt4 key购买 nike

我使用 Arduino 作为 I2C 从站来处理一些超声波传感器并将相关数据发送到 Raspberry。在 Arduino 上运行的代码:

void setup() {
// initialize i2c as slave
Serial.begin(9600);
Wire.begin(SLAVE_ADDRESS);
// define callbacks for i2c communication
Wire.onReceive(receiveData);
Wire.onRequest(sendData);

// useless
}

void loop() {
// useless
}

// callback for received data
void receiveData(int byteCount) {
int i = 0;
while (Wire.available()) {
number[i] = (char) Wire.read();
i++;
}
number[i] = '\0';
Serial.println(atoi(number));
if(atoi(number) != 0) { caseN = atoi(number); }
}

int SonarSensor(int trigPin,int echoPin)
{
// uselesss
}

// callback for sending data
void sendData() {
if(caseN == 1) { Wire.write(distance1);}
else if(caseN == 2) { Wire.write(distance2);}
else if(caseN == 3) { Wire.write(distance3);}
else if(caseN == 4) { Wire.write(distance4);}
else if(caseN == 5)
{
if(state == 0)
{
state = 1;
digitalWrite(ledPin, HIGH);
}
else
{
state = 0;
digitalWrite(ledPin, LOW);
}
}
else { Wire.write(0); }
}

我用 Python 做了第一个版本的总线“聊天”,效果很好:

import smbus
import time

bus = smbus.SMBus(1)


address = 0x04

def writeNumber(value):
bus.write_byte(address, value)
return -1

def readNumber():
number = bus.read_byte_data(address, 1)
return number

while True:
data = raw_input("Enter the data to be sent : ")
data_list = list(data)
for i in data_list:
writeNumber(int(ord(i)))
time.sleep(.1)

writeNumber(int(0x0A))

我正尝试在 C 中做同样的事情,但它看起来有点困难:

#include "i2c-dev.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <string.h>

int main() {
const int adapter_nr = 1;
char filename[20];
snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
const int file = open(filename, O_RDWR);
if (file < 0) {
printf("Unable to connect to Atmega, I2C plugged ? DC ok ?");
exit(EXIT_FAILURE);
}

// Atmega address
const int addr = 0x04;

if(ioctl(file, I2C_SLAVE, addr) < 0)
{
printf("Fail to reach Atmega");
exit(EXIT_FAILURE);
}

const __u8 add = 5; // Ask to "distance 5"
i2c_smbus_write_byte_data(file, 0x04, add); // What is the adress ?


const __u8 reg = 0x0A;
const __s32 result = i2c_smbus_read_byte_data(file, reg);
if(result < 0)
{
printf("Fail to reach Atmega reg");
exit(EXIT_FAILURE);
}
else
{
printf("Distance %d cm \n", result);
}

close(file);

return(EXIT_SUCCESS);
}

正如我在代码中提到的,我不知道我的 Arduino slave 有哪个寄存器地址。我可以在 Arduino COM 终端中看到很多 0 而只有 0。

我希望你能理解我的问题。谢谢。

最佳答案

为什么不定义从机地址,这样您就可以确切地知道它是什么。另外,如果您将来使用超过 1 个 arduino,这将允许您设置不同的地址。

在 arduino 上安装之前运行这行代码。您可以将地址更改为任何您想要的地址,只要它不被 I2C 连接上的另一个系统使用。

#define  SLAVE_ADDRESS           0x29  //slave address,any number from 0x01 to 0x7F

这是一个Tutorial讨论使用 Arduino 作为奴隶

关于c - Arduino 作为 I2C 从设备与 RPi 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55387243/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com