Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
master_i2c.cpp
- Committer:
- liangzhen
- Date:
- 2012-09-20
- Revision:
- 3:764ccaf29ce9
- Parent:
- 1:acf14b6dd1be
- Child:
- 4:fc56fa8aa794
File content as of revision 3:764ccaf29ce9:
//master
#include "mbed.h"
#include <stdlib.h>
I2C master(p28, p27); // sda, scl
Serial pc_master(USBTX, USBRX); // tx, rx
DigitalOut success(LED1);
DigitalOut fail(LED2);
DigitalIn read(p29);
const int SLAVEADDR = 0x88; // define the I2C Slave Address (mbed 2)
char cmd[2];
char buf[50];
void i2c_write(char * data)
{
int ack = master.write(SLAVEADDR, cmd, 2); // Send command string
if (ack)
fail=!fail;
else {
pc_master.printf("Master is writing..\n");
success=!success;
}
}
void i2c_read(char * buf)
{
/*
int ack = master.read(SLAVEADDR, buf, 6);
if (ack)
fail=!fail;
else {
pc_master.printf("Slave sent: %s\n", buf);
success=!success;
}
*/
int ack, data, scan_counter;
scan_counter = 0;
while(1) {
data=master.read(ack);
if(data==0xFF) {
pc_master.printf("Scan finish..\n");
break;
} else {
pc_master.printf("data %d reads %d\n",scan_counter++, data);
}
}
}
void i2c_test()
{
master.start();
cmd[0] = 'U';
cmd[1] = 'S';
while (1) {
if (read) {
i2c_read(buf);
} else {
i2c_write(cmd);
}
wait(0.07);
}
}
void i2c_test2()
{
//send signal to mbed2 and wait for response
master.start();
cmd[0] = 'C';
while (master.write(SLAVEADDR, cmd, 2)) {
fail=!fail;
}
int ack = 1;
while (1) {
if (read) {
while (ack) {
ack = master.read(SLAVEADDR, buf, 2);
}
success = 1;
//pc_master.printf("Slave sent: $s\n", buf);
break;
}
}
}
void master_write()
{
char cmd[] = "scan";
while (master.write(SLAVEADDR, cmd, 4)) {
fail=1;
}
fail = 0;
}
void master_read(int* ro_reading)
{
char* data_read;
data_read = new char [64*5+2];
for(int i=0; i<64*5+2; i++) {
data_read[i]=(char)47;
}
while(data_read[0]==47) {
wait(18);
master.read(SLAVEADDR|1, data_read, 64*5, true);
}
for(int i=0; i<64; i++) {
int out = 0;
out += data_read[i*5+4]-48;
out *= 10;
out += data_read[i*5+3]-48;
out *= 10;
out += data_read[i*5+2]-48;
out *= 10;
out += data_read[i*5+1]-48;
out *= 10;
out += data_read[i*5+0]-48;
ro_reading[i] = out;
}
}