1 IIC总线-数据主机写向从机
1.1 主机
#include <SPI.h>
#include <Wire.h>
#include "USB.h"
#include <SlowSoftWire.h>
#define SSDA_PIN 42
#define SSCL_PIN 41
SlowSoftWire i2c(SSDA_PIN, SSCL_PIN,true);
void init_Blink(){
pinMode(13, OUTPUT);
pinMode(SSDA_PIN, OUTPUT);
pinMode(SSCL_PIN, OUTPUT);
}
void drive_Blink()
{
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
}
void setup() {
USBSerial.begin(115200);
Wire.begin();
}
void loop() {
i2c.beginTransmission(8);
i2c.write("C0C0C0C0C0");
i2c.endTransmission();
delay(10);
}
1.2 从机
#include <Wire.h>
#include "string.h"
int iic_addr=11;
int nReg=0;
static int FluxInt[5];
int nChar=0;
static char flex[10];
unsigned int char_to_hex(char *pUserInput, unsigned char *pKeyArray);
void setup() {
Wire.begin(iic_addr);
Wire.onReceive(receiveEvent);
Serial.begin(115200);
begin();
}
void loop() {
}
void receiveEvent(int howMany) {
while (0 < Wire.available()) {
char c = Wire.read();
flex[nChar++]=c;
}
nChar=0;
drive_Fluxels();
}
unsigned int char_to_hex(char *pUserInput, unsigned char *pKeyArray)
{
if (NULL == pUserInput || NULL == pKeyArray)
{
return 0;
}
unsigned int uiKeySize = strlen(pUserInput) / 2;
int i = 0;
char cTempor = 0;
while(i < uiKeySize)
{
if (*pUserInput >= '0' && *pUserInput <= '9')
{
cTempor = *pUserInput - 48;
}
else if (*pUserInput >= 'a' && *pUserInput <= 'z')
{
cTempor = 0xa + (*pUserInput - 'a');
}
else
{
cTempor = 0xa + (*pUserInput - 'A');
}
pKeyArray[i] = cTempor;
pUserInput++;
if (*pUserInput >= '0' && *pUserInput <= '9')
{
cTempor = *pUserInput - 48;
}
else if (*pUserInput >= 'a' && *pUserInput <= 'z')
{
cTempor = 0xa + (*pUserInput - 'a');
}
else
{
cTempor = 0xa + (*pUserInput - 'A');
}
pKeyArray[i] = (pKeyArray[i] << 4) | cTempor;
pUserInput++;
i++;
}
return uiKeySize;
}
3 IIC总线-数据主机向从机请求数据
3.1 从机响应数据
#include <Wire.h>
void setup() {
Wire.begin(8);
Wire.onRequest(requestEvent);
Serial.begin(115200);
}
void loop() {
delay(100);
}
void requestEvent() {
Wire.write("101010");
Serial.println(101010);
}
3.2 主机请求数据
#include <SPI.h>
#include <Wire.h>
#include "USB.h"
#include <SlowSoftWire.h>
#define SSDA_PIN 42
#define SSCL_PIN 41
uint8_t value8;
uint8_t value9;
SlowSoftWire i2c(SSDA_PIN, SSCL_PIN,true);
void init_Blink(){
pinMode(13, OUTPUT);
pinMode(SSDA_PIN, OUTPUT);
pinMode(SSCL_PIN, OUTPUT);
}
void drive_Blink()
{
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
}
void setup() {
init_Blink();
USBSerial.begin(115200);
Wire.begin();
}
void loop() {
i2c.requestFrom(8,6);
while (i2c.available()) {
char c = i2c.read();
USBSerial.print(c);
}
USBSerial.println();
delay(1000);
i2c.requestFrom(9,6);
while (i2c.available()) {
char c = i2c.read();
USBSerial.print(c);
}
USBSerial.println();
delay(1000);
i2c.requestFrom(10,6);
while (i2c.available()) {
char c = i2c.read();
USBSerial.print(c);
}
USBSerial.println();
delay(1000);
}