Download presentation
Presentation is loading. Please wait.
Published byThomasina Quinn Modified over 6 years ago
1
I2C communication* I²C - Inter-Integrated Circuit – or –I squared C)
Used for attaching low-speed peripherals to a motherboard, embedded system, cellphone, or other digital device Any number of masters and slaves can be connected Devices are addressed by a 7-bit address Fees are required to obtain I²C slave addresses allocated by NXP SCL – serial clock line SDA – serial data line Transfer rates from: 10 kbit/s (low-speed mode) 5-MHz (Ultra Fast-mode) *
2
I2C pins on the RPi GPIO Pin 3 Serial Data Line
Pin 5 Serial Clock Line Pin 1 3.3V Pin 6 ground
3
To access I2C pins… You MAY need to edit the following files:
sudo nano /etc/modprobe.d/raspi-blacklist.conf Add a # character before the i2c line and save: #blacklist i2c-bcm2708 sudo nano /etc/modules Add these lines at the end of the file and save: i2c-dev i2c-bcm2708
4
I2C Code to control HMC5883L /* This code reads data from a Honeywell HMC 5883L 3-axis compass whether it is a standalone breakout board or part of an IMU. Data is read via I2C communications indefinitely. There are only minor adaptations of this code from one that was found on an on-line discussion board. Wes Lawson 4/20/2014 Initial version */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <linux/i2c-dev.h> #include <math.h>
5
I2C Code to control HMC5883L const int HMC5883L_I2C_ADDR = 0x1E; void selectDevice(int fd, int addr, char * name) { if (ioctl(fd, I2C_SLAVE, addr) < 0) { fprintf(stderr, "%s not present\n", name); } } void writeToDevice(int fd, int reg, int val) char buf[2]; buf[0]=reg; buf[1]=val; if (write(fd, buf, 2) != 2) { fprintf(stderr, "Can't write to HMC5883L\n"); }
6
I2C Code to control HMC5883L int main(int argc, char **argv) { int fd; unsigned char buf[16]; if ((fd = open("/dev/i2c-1", O_RDWR)) < 0) // Open port for reading and writing fprintf(stderr, "Failed to open i2c bus\n"); return 1; } /* initialize HMC5883L*/ selectDevice(fd, HMC5883L_I2C_ADDR, "HMC5883L"); writeToDevice(fd, 0x01, 32); writeToDevice(fd, 0x02, 0);
7
I2C Code to control HMC5883L while(1) { buf[0] = 0x03; if ((write(fd, buf, 1)) != 1) { fprintf(stderr, "Error writing to i2c slave\n"); // Send the register to read from } if (read(fd, buf, 6) != 6) { fprintf(stderr, "Unable to read from HMC5883L\n"); } else { short x = (buf[0] << 8) | buf[1]; short y = (buf[4] << 8) | buf[5]; short z = (buf[2] << 8) | buf[3]; float angle = atan2(y, x) * 180 / M_PI; printf("x=%d, y=%d, z=%d\n", x, y, z); printf("angle = %0.1f\n\n", angle); } usleep(500 * 1000); // wait 1/2 second return 0;
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.