switch to setup for Arduino Boards Manager

This commit is contained in:
Erik Tylek Kettenburg
2015-06-23 12:42:35 -07:00
parent bc55c9bb45
commit 6ca6b114d5
3581 changed files with 93 additions and 51 deletions

View File

@@ -0,0 +1,13 @@
void setup() {
//If prompted for a pairing code it is 1234, 12345, or 000000
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
if (Serial.available()) {
Serial.write(Serial.read());
}
}

View File

@@ -0,0 +1,94 @@
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); //open connection to bt/ble module
botInit(); //setup the pins for the bot
}
void loop() {
if(Serial.available()){
char input = Serial.read();
//route based on input
if(input == 'f'){
botForward(255);
}
else if(input == 'b'){
botReverse(255);
}
else if(input == 'r'){
botRight(255);
}
else if(input == 'l'){
botLeft(255);
}
else if(input == 's'){
botStop();
}
}
}
void botForward(int botSpeed){
digitalWrite(2, HIGH);
digitalWrite(5, HIGH);
analogWrite(0, 255 - botSpeed);
analogWrite(1, 255 - botSpeed);
}
void botReverse(int botSpeed){
digitalWrite(2, LOW);
digitalWrite(5, LOW);
analogWrite(0, botSpeed);
analogWrite(1, botSpeed);
}
void botRight(int botSpeed){
digitalWrite(2, LOW);
digitalWrite(5, HIGH);
analogWrite(0, 0);
analogWrite(1, 255 - botSpeed);
}
void botHardRight(int botSpeed){
digitalWrite(2, LOW);
digitalWrite(5, HIGH);
analogWrite(0, botSpeed);
analogWrite(1, 255 - botSpeed);
}
void botLeft(int botSpeed){
digitalWrite(2, HIGH);
digitalWrite(5, LOW);
analogWrite(0, 255 - botSpeed);
analogWrite(1, 0);
}
void botHardLeft(int botSpeed){
digitalWrite(2, HIGH);
digitalWrite(5, LOW);
analogWrite(0, 255 - botSpeed);
analogWrite(1, botSpeed);
}
void botStop(){
digitalWrite(2,LOW);
digitalWrite(5,LOW);
analogWrite(0,0);
analogWrite(1,0);
}
void botInit(){
pinMode(0,OUTPUT);
pinMode(1,OUTPUT);
pinMode(2,OUTPUT);
pinMode(5,OUTPUT);
}

View File

@@ -0,0 +1,79 @@
void setup() {
// put your setup code here, to run once:
botInit();
}
void loop() {
// put your main code here, to run repeatedly:
botForward(255); //speed can be any value from 0 (stopped) to 255 (full)
delay(5000);
botReverse(255);
delay(5000);
botRight(255);
delay(5000);
botHardRight(255);
delay(5000);
botLeft(255);
delay(5000);
botHardLeft(255);
delay(5000);
botStop();
delay(5000);
}
void botForward(int botSpeed){
digitalWrite(2, HIGH);
digitalWrite(5, HIGH);
analogWrite(0, 255 - botSpeed);
analogWrite(1, 255 - botSpeed);
}
void botReverse(int botSpeed){
digitalWrite(2, LOW);
digitalWrite(5, LOW);
analogWrite(0, botSpeed);
analogWrite(1, botSpeed);
}
void botRight(int botSpeed){
digitalWrite(2, LOW);
digitalWrite(5, HIGH);
analogWrite(0, 0);
analogWrite(1, 255 - botSpeed);
}
void botHardRight(int botSpeed){
digitalWrite(2, LOW);
digitalWrite(5, HIGH);
analogWrite(0, botSpeed);
analogWrite(1, 255 - botSpeed);
}
void botLeft(int botSpeed){
digitalWrite(2, HIGH);
digitalWrite(5, LOW);
analogWrite(0, 255 - botSpeed);
analogWrite(1, 0);
}
void botHardLeft(int botSpeed){
digitalWrite(2, HIGH);
digitalWrite(5, LOW);
analogWrite(0, 255 - botSpeed);
analogWrite(1, botSpeed);
}
void botStop(){
digitalWrite(2,LOW);
digitalWrite(5,LOW);
analogWrite(0,0);
analogWrite(1,0);
}
void botInit(){
pinMode(0,OUTPUT);
pinMode(1,OUTPUT);
pinMode(2,OUTPUT);
pinMode(5,OUTPUT);
}

View File

@@ -0,0 +1,138 @@
// where does our characterMap start in the ASCII code
#define MAP_START 32
#define DISPLAY_WIDTH 4
#define DISPLAY_HEIGHT 5
// "pixels" per second
#define SPEED 10
// the text to display
#define DISPLAY_STRING "HELLO WORLD!"
// maps characters to their 4x5 grid
unsigned long characterMap[59];
// set up a character in the characterMap
void Chr(char theChar, unsigned long value) {
characterMap[theChar - MAP_START] = value;
}
// The offset of our string in the display
int offset = 0;
unsigned long lastMillis = 0;
unsigned long currentMillis = 0;
unsigned int timeout;
char myString[] = DISPLAY_STRING;
int length = sizeof(myString);
// render the string on the given offset
void renderString(char *theString, int offset) {
int index = 0;
while (theString[index]) {
renderCharacter(theString[index], offset - index * (DISPLAY_WIDTH + 1));
index++;
}
}
// render a character on the given offset
void renderCharacter(char theChar, int charOffset) {
if (charOffset <= -DISPLAY_WIDTH || charOffset > DISPLAY_WIDTH) {
// off the 'screen' nothing to do
return;
}
unsigned long graphic = characterMap[theChar - MAP_START];
for (byte y = 0; y < DISPLAY_HEIGHT; y++) {
for (byte x = 0; x < DISPLAY_WIDTH; x++) {
if (graphic & 0x1) {
// 3 - x to reverse order
lightPixel(3 - x - charOffset, y);
}
graphic = graphic >> 1;
}
}
}
// light a pixel at the given coordinates
void lightPixel(byte x, byte y) {
if (x >= 0 && x < DISPLAY_WIDTH) {
if (y <= x) {
x++;
}
LEDon(y, x);
}
}
// turn on the pins to light a LED
void LEDon(byte vin, byte gnd) {
delay(1);
pinMode(0, INPUT);
pinMode(1, INPUT);
pinMode(2, INPUT);
pinMode(3, INPUT);
pinMode(4, INPUT);
pinMode(vin, OUTPUT);
pinMode(gnd, OUTPUT);
digitalWrite(vin, HIGH);
digitalWrite(gnd, LOW);
}
// runs at start
void setup() {
// set up render map
// Rows: 1---2---3---4---5---
Chr('A', 0b01101001111110011001);
Chr('B', 0b11101001111010011110);
Chr('C', 0b01111000100010000111);
Chr('D', 0b11101001100110011110);
Chr('E', 0b11111000111010001111);
Chr('F', 0b11111000111010001000);
Chr('G', 0b01111000101110010110);
Chr('H', 0b10011001111110011001);
Chr('I', 0b01110010001000100111);
Chr('J', 0b01110010001010100100);
Chr('K', 0b10011010110010101001);
Chr('L', 0b10001000100010001111);
Chr('M', 0b10011111111110011001);
Chr('N', 0b10011101101110011001);
Chr('O', 0b01101001100110010110);
Chr('P', 0b11101001111010001000);
Chr('Q', 0b01101001101101100001);
Chr('R', 0b11101001111010101001);
Chr('S', 0b11111000111100011111);
Chr('T', 0b01110010001000100010);
Chr('U', 0b10011001100110010110);
Chr('V', 0b10011001100110100100);
Chr('W', 0b10011001111111110110);
Chr('X', 0b10011001011010011001);
Chr('Y', 0b10011001011000101100);
Chr('Z', 0b11110001001001001111);
Chr(' ', 0b00000000000000000000);
Chr('!', 0b01000100010000000100);
// how long to wait between shifting the display
timeout = 1000 / SPEED;
}
// loops continuously
void loop() {
currentMillis = millis();
renderString(myString, offset);
if (currentMillis - lastMillis > timeout) {
lastMillis = currentMillis;
// shift string over one "pixel"
offset++;
// if it's past the length of the string, start over from the beginning
if (offset > length * (DISPLAY_WIDTH + 1)) {
offset = -DISPLAY_WIDTH;
}
}
}

View File

@@ -0,0 +1,63 @@
void setup() {
// initialize the digital pin as an output.
}
// the loop routine runs over and over again forever:
void loop() {
LEDon(0, 1);
delay(1000);
LEDon(0, 2);
delay(1000);
LEDon(0, 3);
delay(1000);
LEDon(0, 4);
delay(1000);
LEDon(1, 0);
delay(1000);
LEDon(1, 2);
delay(1000);
LEDon(1, 3);
delay(1000);
LEDon(1, 4);
delay(1000);
LEDon(2, 0);
delay(1000);
LEDon(2, 1);
delay(1000);
LEDon(2, 3);
delay(1000);
LEDon(2, 4);
delay(1000);
LEDon(3, 0);
delay(1000);
LEDon(3, 1);
delay(1000);
LEDon(3, 2);
delay(1000);
LEDon(3, 4);
delay(1000);
LEDon(4, 0);
delay(1000);
LEDon(4, 1);
delay(1000);
LEDon(4, 2);
delay(1000);
LEDon(4, 3);
delay(1000);
}
void LEDon(int vin, int gnd) {
pinMode(0, INPUT);
pinMode(1, INPUT);
pinMode(2, INPUT);
pinMode(3, INPUT);
pinMode(4, INPUT);
pinMode(5, INPUT);
pinMode(vin, OUTPUT);
pinMode(gnd, OUTPUT);
digitalWrite(vin, HIGH);
digitalWrite(gnd, LOW);
}

View File

@@ -0,0 +1,53 @@
#include <TinyWireM.h>
#define disk1 0x50 //Address of 24LC256 eeprom chip
int returned = 0;
void setup(void)
{
//Serial.begin(9600);
TinyWireM.begin();
unsigned int address = 0;
pinMode(5, OUTPUT);
writeEEPROM(disk1, address, 5);
returned = readEEPROM(disk1, address);
while(returned>0){
digitalWrite(5,HIGH);
delay(500);
digitalWrite(5,LOW);
delay(500);
returned--;
}
}
void loop(){}
void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data )
{
TinyWireM.beginTransmission(deviceaddress);
TinyWireM.send((int)(eeaddress >> 8)); // MSB
TinyWireM.send((int)(eeaddress & 0xFF)); // LSB
TinyWireM.send(data);
TinyWireM.endTransmission();
delay(5);
}
byte readEEPROM(int deviceaddress, unsigned int eeaddress )
{
byte rdata = 0xFF;
TinyWireM.beginTransmission(deviceaddress);
TinyWireM.send((int)(eeaddress >> 8)); // MSB
TinyWireM.send((int)(eeaddress & 0xFF)); // LSB
TinyWireM.endTransmission();
TinyWireM.requestFrom(deviceaddress,1);
if (TinyWireM.available()) rdata = TinyWireM.receive();
return rdata;
}

View File

@@ -0,0 +1,33 @@
#include <TinyWireM.h>
#define expander 0x20
byte expanderStatus = B11111111; //all off
void setup()
{
TinyWireM.begin();
}
void loop()
{
expanderWrite(0,HIGH);
delay(1000);
expanderWrite(0,LOW);
delay(1000);
}
void expanderWrite(byte pinNumber, boolean state){
if(state == HIGH)
expanderStatus &= ~(1 << pinNumber);
else
expanderStatus |= (1 << pinNumber);
expanderWrite(expanderStatus);
}
void expanderWrite(byte _data ) {
TinyWireM.beginTransmission(expander);
TinyWireM.send(_data);
TinyWireM.endTransmission();
}

View File

@@ -0,0 +1,289 @@
#include "DigiKeyboard.h"
char nmeaString[57];
bool gpsReady = 0;
bool gpsDateTimeReady = 0;
void setup() {
DigiKeyboard.delay(3000);//When this sketch is used with DigiKeyboard as it is here, it tends to need a bit of a delay at the start
Serial.begin(9600); //Connect to GPS
DigiKeyboard.delay(1000);//We need a delay before we init the GPS module
initGPS(); //Send init msgs to GPS
}
void loop() {
if(updateGPS()){ //this will return true if it was able to get a valid string from the GPS
DigiKeyboard.println(nmeaString); //the whole string from the GPS unit
DigiKeyboard.println(getStatus()); //A means we are good to go, V means it is still getting a fix
if(gpsDateTimeReady){ //date and time are oftenr eady before the rest of the data, so if we are just looking for that we can use it much sooner
DigiKeyboard.println(getTime());
DigiKeyboard.println(getDate());
}
if(gpsReady){
DigiKeyboard.println(getLat());
DigiKeyboard.println(getLon());
}
}
DigiKeyboard.delay(1000);
}
void initGPS(){
Serial.println(F("$PUBX,40,RMC,1,1,1,0*46")); //turn on RMC msgs
Serial.println(F("$PUBX,40,GLL,0,0,0,0*5C")); //turn off the rest
Serial.println(F("$PUBX,40,GGA,0,0,0,0*5A"));
Serial.println(F("$PUBX,40,GSA,0,0,0,0*4E"));
Serial.println(F("$PUBX,40,GSV,0,0,0,0*59"));
Serial.println(F("$PUBX,40,VTG,0,0,0,0*5E"));
}
bool updateGPS() {
while(Serial.read()!='$');
while(Serial.read()!=',');
unsigned int i = 0;
while(i<56){nmeaString[i] = Serial.read();i++;}
nmeaString[56] = '\0';
if(getStatus() == 'A'){ //we're good to go
gpsReady = 1;
gpsDateTimeReady = 1;
}
else if (getStatus() == 'V'){ //string is valid but gps isn't ready - check if we have date and time at least
gpsReady = 0;
gpsDateTimeReady = dateTimeReady();
}
else
return false; //we got an invalid string
return true;
}
unsigned int charIndexOf(char* array, char searchChar){
unsigned int i = 0;
while(array[i] != '\0'){
if(array[i] == searchChar)
return i;
i++;
}
return false;
}
unsigned int charLastIndexOf(char* array, char searchChar){
unsigned int i = 0;
unsigned int l = '\0';
while(array[i] != '\0'){
if(array[i] == searchChar)
l=i;
i++;
}
if(l=='\0')
return false;
else
return l;
}
long getTime(){
char time[7];
memcpy(time,&nmeaString[0],6);
time[6] = '\0';
return atol(time);
}
int getHour(){
char time[3];
memcpy(time,&nmeaString[0],2);
time[2] = '\0';
return atoi(time);
}
int getMin(){
char time[3];
memcpy(time,&nmeaString[2],2);
time[2] = '\0';
return atoi(time);
}
int getSec(){
char time[3];
memcpy(time,&nmeaString[4],2);
time[2] = '\0';
return atoi(time);
}
char getStatus(){
return nmeaString[charIndexOf(nmeaString,',')+1]; //this has to work even if the other data isn't present
}
bool dateTimeReady(){
if(nmeaString[0] != ',' && nmeaString[18] != ','){
return true;
}
else
return false;
}
float getLat(){
char temp[11];
memcpy( temp, &nmeaString[12], 10 );
temp[10] = '\0';
return atof(temp);
}
int getLatDeg(){
char temp[3];
memcpy( temp, &nmeaString[12], 2 );
temp[2] = '\0';
return atoi(temp);
}
float getLatMin(){
char temp[9];
memcpy( temp, &nmeaString[14], 8 );
temp[8] = '\0';
return atof(temp);
}
float getLon(){
char temp[12];
memcpy( temp, &nmeaString[25], 11 );
temp[11] = '\0';
return atof(temp);
}
int getLonDeg(){
char temp[4];
memcpy( temp, &nmeaString[25], 3 );
temp[3] = '\0';
return atoi(temp);
}
float getLonMin(){
char temp[9];
memcpy( temp, &nmeaString[28], 8 );
temp[8] = '\0';
return atof(temp);
}
float getKnots(){
char temp[6];
memcpy( temp, &nmeaString[39], 5 );
temp[5] = '\0';
return atof(temp);
}
float getCourse(){
char temp[7];
memcpy( temp, &nmeaString[45], 6 );
temp[6] = '\0';
return atof(temp);
}
bool isCoursePresent(){
if(nmeaString[12] == ',')
return false;
else if(charLastIndexOf(nmeaString,',')>53)
return false;
else
return true;
}
long getDate(){
char date[7];
if(isCoursePresent()){
memcpy( date, &nmeaString[52], 4 );
date[4] = '\0';
return atol(date)*100+14;
}
else{
if(nmeaString[12] == ',')
memcpy( date, &nmeaString[18], 6 );
else
memcpy( date, &nmeaString[46], 6 );
date[6] = '\0';
return atol(date);
}
}
int getDay(){
char date[3];
if(isCoursePresent())
memcpy( date, &nmeaString[52], 2 );
else{
if(nmeaString[12] == ',')
memcpy( date, &nmeaString[18], 2 );
else
memcpy( date, &nmeaString[46], 2 );
}
date[2] = '\0';
return atoi(date);
}
int getMonth(){
char date[3];
if(isCoursePresent())
memcpy( date, &nmeaString[54], 2 );
else{
if(nmeaString[12] == ',')
memcpy( date, &nmeaString[20], 2 );
else
memcpy( date, &nmeaString[48], 2 );
}
date[2] = '\0';
return atoi(date);
}
int getYear(){
if(isCoursePresent())
return 14; //just assume the year hasn't changed - we could also save it when we have it, but that would take more ram
else{
char date[3];
if(nmeaString[12] == ',')
memcpy( date, &nmeaString[22], 2 );
else
memcpy( date, &nmeaString[50], 2 );
date[2] = '\0';
return atoi(date);
}
}
int getFullYear(){
if(isCoursePresent())
return 2014; //just assume the year hasn't changed - we could also save it when we have it, but that would take more ram
else{
char date[3];
if(nmeaString[12] == ',')
memcpy( date, &nmeaString[22], 2 );
else
memcpy( date, &nmeaString[50], 2 );
date[2] = '\0';
return atoi(date)+2000;
}
}
char getNS(){
return nmeaString[23];
}
char getEW(){
return nmeaString[37];
}

View File

@@ -0,0 +1,27 @@
int irPin=2;
void setup()
{
pinMode(irPin,INPUT);
pinMode(0,OUTPUT);
//Serial.begin(9600);
digitalWrite(0,HIGH);
//Serial.println("You pressed a button");
delay(1000);
digitalWrite(0,LOW);
}
void loop()
{
if(pulseIn(irPin,LOW))
{
//button pressed
delay(100);
digitalWrite(0,HIGH);
//Serial.println("You pressed a button");
delay(1000);
digitalWrite(0,LOW);
}
}

View File

@@ -0,0 +1,105 @@
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
//THESE MUST BE SET! CHANGE ADDRESS AS YOU UPLOAD TO EACH NODE!
#define TOTAL_NODES 3 //TOTAL NUMBER OF NODES IN MESH
#define NODE_ADDRESS 0 //the sero indexed address of this node - nodes must be numbered 0 thru TOTAL_NODES-1 //also note 255 is broadcast address
//hold the seuqnce numbers to avoid repeating the same messages
uint8_t sequence[TOTAL_NODES];
//setup radio module
RF24 radio(9,12);
//message format - adjust data as needed - the rest is madatory for this mesh to work
struct
{
char toAddress;
char fromAddress;
char fromSequence;
long data;
} msg;
//don't change! read is same for all nodes, write is automatically calculated here
const uint64_t writePipe = 0xF0F0F0F00LL + NODE_ADDRESS;
const uint64_t readPipe = 0xF0F0F0F0D2LL;
void setup() {
// put your setup code here, to run once:
radio.begin();
radio.setDataRate(RF24_250KBPS); //lowest speed = most range
radio.setAutoAck(false); //this is a mesh so we don't want ACKs!
radio.setRetries(15, 15);
radio.setPayloadSize(sizeof(msg));
radio.openWritingPipe(writePipe);
radio.openReadingPipe(1, readPipe);
radio.startListening();
}
long now = 0;
void loop() {
if(readAndRepeat()){ //will repeat messages as needed and return false unless there is packet for this node - CALL FREQUENTLY!
//if this does not return false then we have a packet for THIS node!
//msg.fromAddress is the node that sent it
//msg.data is the data itself
//Do something with it!
//For example display packets coming to this node on a LCD:
/*
NOTE: TO USE THIS ADD THE LCD INCLUDES AND SETUP ROUTINE FROM THE DigisparkLCD example
lcd.clear();
lcd.print("From: ");
lcd.println(msg.fromAddress);
lcd.print("Value: ");
lcd.println(msg.data);
*/
}
if(millis() - now > 10000){ //send a packet from this node to the mesh every 10 seconds but wait in a non-blocking way so that we can still run this loop and repeat things
now = millis(); //set now to millis so we wait another 10 seconds before sending again
//sendToMesh(To_Address,Data_To_Send);
//sendToMesh(0, analogRead(A5)); //send to node 0 the analog read value of pin 5 - could also send a temp sensor value, etc ,etc
//sendToMesh(255, analogRead(A5)); //send to all nodes (255 is the broadcast address) the analog read value of pin 5
}
}
void sendToMesh(uint8_t toAddress, long data){
if(sequence[NODE_ADDRESS]<255)
sequence[NODE_ADDRESS]++; //increment sequence count for this device
else
sequence[NODE_ADDRESS] = 0; //set to zero if last was 255 so we don't overflow - logic for read is built to handle this too
msg.toAddress = toAddress; //set the address of the destination node
msg.fromAddress = NODE_ADDRESS; //set the from as this node - of course
msg.fromSequence = sequence[NODE_ADDRESS]; //set it to the sequence number we just implemented which should be greater than any the nodes have received
radio.stopListening(); //turn of recv so we can transmit
radio.write(&msg, sizeof(msg));
radio.startListening(); //turn recv back on
}
bool readAndRepeat(){
if(radio.read(&msg, sizeof(msg))){ //if we have incoming data
if(msg.fromAddress!=NODE_ADDRESS){ //make sure this node didn't send it
if(sequence[msg.fromAddress] < msg.fromSequence || (sequence[msg.fromAddress] == 255 && msg.fromSequence == 0)){ //make sure we haven't already repeated it or received it
//increment sequence for that address so we don't repeat it twice from this node or receive it twice
sequence[msg.fromAddress] = msg.fromSequence;
if(msg.toAddress==NODE_ADDRESS){ //is it for this node? if so return true so we can use it!
return true;
}
//otherwise repeat it - send it back out
radio.write(&msg, sizeof(msg));
if(msg.toAddress == 255){ //it was a broadcast so return true so we do something with it
return true;
}
}
}
}
return false;
}

View File

@@ -0,0 +1,50 @@
/*
This example code is in the public domain.
*/
int MotorADir = 2;
int MotorASpeed = 0;
int MotorBDir = 5;
int MotorBSpeed = 1;
// the setup routine runs once when you press reset:
void setup() {
// initialize the outputs.
pinMode(MotorADir, OUTPUT);
pinMode(MotorASpeed, OUTPUT);
pinMode(MotorBDir, OUTPUT);
pinMode(MotorBSpeed, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
//both motors forward full speed
digitalWrite(MotorADir, HIGH); //forward
digitalWrite(MotorBDir, HIGH);
analogWrite(MotorASpeed, 255); //full speed
analogWrite(MotorBSpeed, 255);
delay(5000); // wait for 5 seconds
//turn in place (if using a skid steer configuration)
digitalWrite(MotorADir, HIGH); //forward
digitalWrite(MotorBDir, HIGH);
analogWrite(MotorASpeed, 255);
analogWrite(MotorBSpeed, 0); //off
delay(5000); // wait for 5 seconds
//turn gradually - the other direction (if using a skid steer configuration)
digitalWrite(MotorADir, HIGH); //forward
digitalWrite(MotorBDir, HIGH);
analogWrite(MotorASpeed, 100);
analogWrite(MotorBSpeed, 255);
delay(5000); // wait for 5 seconds
//stop
digitalWrite(MotorADir, HIGH); //forward
digitalWrite(MotorBDir, HIGH);
analogWrite(MotorASpeed, 0);
analogWrite(MotorBSpeed, 0); //off
//reverse slowly
digitalWrite(MotorADir, LOW); //reverse
digitalWrite(MotorBDir, LOW);
analogWrite(MotorASpeed, 100);
analogWrite(MotorBSpeed, 100);
}

View File

@@ -0,0 +1,297 @@
// This sketch will send a RFM12b packet that is compatible with the Jeelib and can be picked up by a JeeNode running RFM12 demo sketch
//See http://jeelabs.org/2011/06/09/rf12-packet-format-and-design/
//for packet design
#define GROUP 212
#define HEADER 17
//433mhz = 1, 868mhz = 2, 915mhz = 3
#define RF12_FREQ 1
#define RF12_NOT_CS() PORTB |= _BV(PB3)
#define RF12_CS() PORTB &= ~_BV(PB3)
#define MOSI_LOW() PORTB &= ~_BV(PB1)
#define MISO_LEVEL() (PINB & _BV(PB0))
#define RF12_TRANSMIT 0xB8
union
{
unsigned char byte;
struct
{
char ATS_RSSI:
1; //ATS=Antenna tuning circuit detected strong enough RF signal
//RSSI=The strength of the incoming signal is above the pre-programmed limit
char FFEM:
1; //FIFO is empty
char LBD:
1; //Low battery detect, the power supply voltage is below the pre-programmed limit
char EXT:
1; //Logic level on interrupt pin (pin 16) changed to low (Cleared after Status Read Command)
char WKUP:
1; //Wake-up timer overflow (Cleared after Status Read Command )
char RGUR_FFOV:
1; //RGUR=TX register under run, register over write (Cleared after Status Read Command )
//FFOV=RX FIFO overflow (Cleared after Status Read Command )
char POR:
1; //Power-on reset (Cleared after Status Read Command )
char RGIT_FFIT:
1; //RGIT=TX register is ready to receive the next byte
//(Can be cleared by Transmitter Register Write Command)
//FFIT=The number of data bits in the RX FIFO has reached the pre-programmed limit
//(Can be cleared by any of the FIFO read methods)
}bits;
} status_H;
union
{
unsigned char byte;
struct
{
char OFFS:
4; //Offset value to be added to the value of the frequency control parameter (Four LSB bits)
char OFFS6:
1; //MSB of the measured frequency offset (sign of the offset value)
char ATGL:
1; //Toggling in each AFC cycle
char CRL:
1; //Clock recovery locked
char DQD:
1; //Data quality detector output
}bits;
} status_L;
void setup(){
DDRB = _BV(PB1) | _BV(PB2) | _BV(PB3) | _BV(PB4);
// MOSI, SCK, SEL
PORTB = _BV(PB3); // deselect RFM12
rf12_init();
}
//Some extremely dummy packet payload, just to show it works..
uint8_t data[] = { "TEST" };
void loop(){
rf12_cmd(0x82,0x38); //Enable transciever
rf12_send((uint8_t *)&data, sizeof(data));
//wait till the next-to-last byte is sent (the last is the dummy)
while (!rf12_read_status_MSB());
rf12_cmd(0x82,0x08); //Disable transciever
delay(3000);
}
static void spi_run_clock () {
USICR = _BV(USIWM0) | _BV(USITC);
USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK);
USICR = _BV(USIWM0) | _BV(USITC);
USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK);
USICR = _BV(USIWM0) | _BV(USITC);
USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK);
USICR = _BV(USIWM0) | _BV(USITC);
USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK);
USICR = _BV(USIWM0) | _BV(USITC);
USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK);
USICR = _BV(USIWM0) | _BV(USITC);
USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK);
USICR = _BV(USIWM0) | _BV(USITC);
USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK);
USICR = _BV(USIWM0) | _BV(USITC);
USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK);
}
void rf12_cmd(uint8_t highbyte, uint8_t lowbyte)
{
RF12_CS();
USIDR = highbyte;
spi_run_clock();
USIDR = lowbyte;
spi_run_clock();
RF12_NOT_CS();
}
void rf12_loop_until_FFIT_RGIT(void)
{
do
{
rf12_read_status_MSB();
}
while (!status_H.bits.RGIT_FFIT);
}
/* rf12_read_status_MSB
RX Mode: FFIT = The number of data bits in the RX FIFO has reached the pre-programmed limit.
Can be cleared by any of the FIFO read methods
TX Mode: RGIT = TX register is ready to receive the next byte
(Can be cleared by Transmitter Register Write Command)
*/
uint8_t rf12_read_status_MSB(void)
{
RF12_CS();
MOSI_LOW();
asm volatile("nop");
if (MISO_LEVEL())
status_H.bits.RGIT_FFIT=1;
else
status_H.bits.RGIT_FFIT=0;
RF12_NOT_CS();
return status_H.bits.RGIT_FFIT;
}
void rf12_read_status(void)
{
RF12_CS();
USIDR = 0x00; //Status Read Command
spi_run_clock();
status_H.byte = USIDR;
USIDR = 0x00; //Status Read Command
spi_run_clock();
status_L.byte = USIDR;
RF12_NOT_CS();
}
void rf12_TX(uint8_t aByte)
{
//FFIT wird gepollt um zu erkennen ob das FIFO TX
//Register bereit ist.
//Alternativ ist es auch möglich(wenn verbunden)
//den Interrupt Ausgang des RF12 zu pollen: while(INT1_LEVEL());
while (!rf12_read_status_MSB());
rf12_cmd(RF12_TRANSMIT,aByte);
}
#if RF12_RECEIVE_CODE
uint8_t rf12_RX(void)
{
rf12_loop_until_FFIT_RGIT();
RF12_CS();
USIDR = 0xB0;
spi_run_clock();
USIDR = 0x00;
spi_run_clock();
RF12_NOT_CS();
return USIDR;
}
#endif
static __inline__ uint16_t _crc16_update(uint16_t __crc, uint8_t __data)
{
uint8_t __tmp;
uint16_t __ret;
__asm__ __volatile__ (
"eor %A0,%2" "\n\t"
"mov %1,%A0" "\n\t"
"swap %1" "\n\t"
"eor %1,%A0" "\n\t"
"mov __tmp_reg__,%1" "\n\t"
"lsr %1" "\n\t"
"lsr %1" "\n\t"
"eor %1,__tmp_reg__" "\n\t"
"mov __tmp_reg__,%1" "\n\t"
"lsr %1" "\n\t"
"eor %1,__tmp_reg__" "\n\t"
"andi %1,0x07" "\n\t"
"mov __tmp_reg__,%A0" "\n\t"
"mov %A0,%B0" "\n\t"
"lsr %1" "\n\t"
"ror __tmp_reg__" "\n\t"
"ror %1" "\n\t"
"mov %B0,__tmp_reg__" "\n\t"
"eor %A0,%1" "\n\t"
"lsr __tmp_reg__" "\n\t"
"ror %1" "\n\t"
"eor %B0,__tmp_reg__" "\n\t"
"eor %A0,%1"
: "=r" (__ret), "=d" (__tmp)
: "r" (__data), "0" (__crc)
: "r0"
);
return __ret;
}
void rf12_send(const uint8_t* buf, uint8_t cnt)
{
if (!cnt) return;
uint16_t chksum=~0;
//See http://jeelabs.org/2011/06/09/rf12-packet-format-and-design/
//http://jeelabs.org/2010/12/07/binary-packet-decoding/
rf12_TX(0xAA); //PREAMBLE
rf12_TX(0xAA); //PREAMBLE
rf12_TX(0xAA); //PREAMBLE
rf12_TX(0x2D); //SYNC HI BYTE
rf12_TX(GROUP); //SYNC LOW BYTE (group 210)
chksum = _crc16_update(chksum, GROUP);
rf12_TX(HEADER); // Header byte
chksum = _crc16_update(chksum, HEADER);
rf12_TX(cnt);
chksum = _crc16_update(chksum, cnt);
while (cnt--)
{
rf12_TX(*buf);
chksum = _crc16_update(chksum,*buf++);
}
rf12_TX(chksum);
rf12_TX(chksum>>8);
rf12_TX(0xAA); //dummy byte
}
#if RF12_RECEIVE_CODE
//returns 0 if no data is available
//returns -1(255) if there is a CRC Error
//else, returns number of received byte
uint8_t rf12_read(uint8_t* buf, const uint8_t max)
{
uint16_t checksum=~0;
uint16_t received_checksum;
uint8_t hdr;
hdr=rf12_RX();
checksum = _crc16_update(checksum,hdr);
uint8_t len;
len=rf12_RX();
checksum = _crc16_update(checksum,len);
uint8_t i=len;
while (i--)
{
*buf=rf12_RX();
checksum = _crc16_update(checksum,*buf++);
}
received_checksum=rf12_RX();
received_checksum=received_checksum<<8;
received_checksum |= rf12_RX();
if (received_checksum==checksum)
return len;
else
return -1;
}
#endif
void rf12_init(void)
{
USICR = _BV(USIWM0); // 3-wire, software clock strobe
rf12_cmd(0x80, 0xC7 | (RF12_868MHZ << 4)); // EL (ena TX), EF (ena RX FIFO), 12.0pF
rf12_cmd(0xA6,0x40); // 868MHz
rf12_cmd(0xC6,0x06); // approx 49.2 Kbps, i.e. 10000/29/(1+6) Kbps
rf12_cmd(0x94,0xA2); // VDI,FAST,134kHz,0dBm,-91dBm
rf12_cmd(0xC2,0xAC); // AL,!ml,DIG,DQD4
rf12_cmd(0xCA,0x83); // FIFO8,2-SYNC,!ff,DR
rf12_cmd(0xCE,0x00 | GROUP); // SYNC=2DXX
rf12_cmd(0xC4,0x83); // @PWR,NO RSTRIC,!st,!fi,OE,EN
rf12_cmd(0x98,0x50); // !mp,90kHz,MAX OUT
rf12_cmd(0xCC,0x77); // OB1OB0, LPX,ddyDDITBW0
rf12_cmd(0xE0,0x00); // NOT USE
rf12_cmd(0xC8,0x00); // NOT USE
rf12_cmd(0xC0,0x40); // 1.66MHz,2.2V
}

View File

@@ -0,0 +1,17 @@
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(0, OUTPUT); //LED on Model B
pinMode(1, OUTPUT); //LED on Model A or Pro
}
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(0, HIGH); // turn the LED on (HIGH is the voltage level)
digitalWrite(1, HIGH);
delay(1000); // wait for a second
digitalWrite(0, LOW); // turn the LED off by making the voltage LOW
digitalWrite(1, LOW);
delay(1000); // wait for a second
}

View File

@@ -0,0 +1,118 @@
#include <DigiKeyboard.h>
void setup() {
// put your setup code here, to run once:
wifiDelay(10000); //wait a good amount of time for moduel to connect to wifi - this script assumes it can connect and doesn't check
Serial.begin(9600);
/*==========================================================
= NOTE: This assumes you have used the wifi module =
= web interface to set it up as a client and 9600 baud =
= See the wifi shield page for more info. =
= =
= NOTE YOU MAY NEED TO CHANGE THE begin STATEMENT AND =
= THE MODULED TO 4800 baud IF YOU EXPERIENCE SCRAMBLED =
= OUTPUT =
= =
= If not useing DigiKeyboard change wifiDelay as noted =
==========================================================*/
if(wifiConnect(F("digistump.com"))){ //host wrapped in F() to save ram
if(wifiSendGet(F("digistump.com"),F("/test.txt"))){ //host and path wrapped in F() to save ram
//uncomment one of the three test methods below to try one out, only one will work at a time
//YOU CAN READ IT OUT ONE CHAR AT A TIME AND PRINT IT
while(!Serial.available()){wifiDelay(10);} //wait for some data
while(Serial.available()){ //as long as there is data read it and do something with it
DigiKeyboard.write(Serial.read()); //in this case we just type it out
}
/*
//OR YOU CAN FIND SOMETHING AND THEN READ AFTER THAT
//try this with ip.jsontest.com
//See also: Serial.findUntil, Serial.readBytesUntil, Serial.readStringUntil, Serial.find, etc
Serial.find(": \""); //find the start of where the ip is shown
String ip = Serial.readStringUntil('"'); //read until the end of the ip which is the "
DigiKeyboard.print(ip); //type it out for the demo
*/
/*
//OR YOU CAN GRAB IT ALL AT ONCE
//ASSUMING THE BODY ISN'T LARGER THAN AVAILABLE RAME
String body = Serial.readString(); //read it all to a string
DigiKeyboard.print(body.trim()); //type it out for the demo - but first trim the whitespace off the start and end
*/
}
else{
//we didn't get a response to our GET - something failed
DigiKeyboard.write('1');
}
}
else{
//we couldn't talk to the wifi module properly - see wifiConnect for possible break points
DigiKeyboard.write('2');
}
}
void loop() {
// put your main code here, to run repeatedly:
}
void wifiDelay(long time){
/*
If you are not using DigiKeyboard in you sketch
change this by commenting out the DigiKeyboard delay and
uncommenting the regular delay
Also remove the DigiKeyboard.h include at the top
Note: This sketch will not run with DigiKeyboard in use
unless connected to a computer
*/
DigiKeyboard.delay(time);
//delay(time);
}
bool wifiConnect(String host){
wifiDelay(50);
Serial.write("+++");
if (!Serial.find("a")) return false; //error in entering AT mode - try restoring module and then setting settings again
Serial.write("a");
if (!wifiWaitForOK()) return false; //error in entering AT mode
Serial.print(F("AT+NETP=TCP,CLIENT,80,"));
Serial.print(host);
Serial.print(F("\r"));
if (!wifiWaitForOK()) return false; //error in setting host
Serial.print(F("AT+ENTM\r"));
if (!wifiWaitForOK()) return false; //error in going back to transparent mode
wifiDelay(1000); //instead of calling TCPLK to check for a link we just wait a good amount of time for a link, because TCPLK can be buggy
while(Serial.read()!=-1); //empty the read buffer so we are ready for a clean GET OR POST
return true;
}
bool wifiWaitForOK(){
return Serial.find("k");
}
bool wifiSendGet(String host, String path){
Serial.print(F("GET "));
Serial.print(path);
Serial.println(F(" HTTP/1.1"));
Serial.print(F("Host: "));
Serial.println(host);
Serial.println(F("Cache-Control: no-cache"));
Serial.println();
Serial.setTimeout(5000);
if(!Serial.find("\r\n\r")) //skip the header - if this fail then the GET probably did too
return false;
Serial.setTimeout(1000);
return true;
}

View File

@@ -0,0 +1,127 @@
#include <DigiKeyboard.h>
void setup() {
// put your setup code here, to run once:
wifiDelay(10000); //wait a good amount of time for moduel to connect to wifi - this script assumes it can connect and doesn't check
Serial.begin(600);
/*==========================================================
= NOTE: This assumes you have used the wifi module =
= web interface to set it up as a client and 600 baud =
= See the wifi shield page for more info. =
= =
= NOTE YOU MAY NEED TO CHANGE THE begin STATEMENT AND =
= THE MODULE TO A LOWER BAUD IF YOU EXPERIENCE SCRAMBLED=
= OUTPUT - see notes in the wiki on how to set these =
= =
= If not useing DigiKeyboard change wifiDelay as noted =
==========================================================*/
if(wifiConnect(F("requestb.in"))){ //host wrapped in F() to save ram
if(wifiSendPost(F("requestb.in"),F("/12tefnq1"),F("test=test123"))){ //host and path and parameters wrapped in F() to save ram
//uncomment one of the three test methods below to try one out, only one will work at a time
//you could also just ignore all of this - we know we got headers back so we're probably good and out data was sent
//TODO: read the status code to be sure
/*
//YOU CAN READ IT OUT ONE CHAR AT A TIME AND PRINT IT
while(!Serial.available()){wifiDelay(10);} //wait for some data
while(Serial.available()){ //as long as there is data read it and do something with it
DigiKeyboard.write(Serial.read()); //in this case we just type it out
}
*/
/*
//OR YOU CAN FIND SOMETHING AND THEN READ AFTER THAT
//try this with ip.jsontest.com
//See also: Serial.findUntil, Serial.readBytesUntil, Serial.readStringUntil, Serial.find, etc
Serial.find(": \""); //find the start of where the ip is shown
String ip = Serial.readStringUntil('"'); //read until the end of the ip which is the "
DigiKeyboard.print(ip); //type it out for the demo
*/
/*
//OR YOU CAN GRAB IT ALL AT ONCE
//ASSUMING THE BODY ISN'T LARGER THAN AVAILABLE RAME
String body = Serial.readString(); //read it all to a string
DigiKeyboard.print(body.trim()); //type it out for the demo - but first trim the whitespace off the start and end
*/
}
else{
//we didn't get a response to our GET - something failed
DigiKeyboard.write('1');
}
}
else{
//we couldn't talk to the wifi module properly - see wifiConnect for possible break points
DigiKeyboard.write('2');
}
}
void loop() {
// put your main code here, to run repeatedly:
}
void wifiDelay(long time){
/*
If you are not using DigiKeyboard in you sketch
change this by commenting out the DigiKeyboard delay and
uncommenting the regular delay
Also remove the DigiKeyboard.h include at the top
Note: This sketch will not run with DigiKeyboard in use
unless connected to a computer
*/
DigiKeyboard.delay(time);
//delay(time);
}
bool wifiConnect(String host){
wifiDelay(50);
Serial.write("+++");
if (!Serial.find("a")) return false; //error in entering AT mode - try restoring module and then setting settings again
Serial.write("a");
if (!wifiWaitForOK()) return false; //error in entering AT mode
Serial.print(F("AT+NETP=TCP,CLIENT,80,"));
Serial.print(host);
Serial.print(F("\r"));
if (!wifiWaitForOK()) return false; //error in setting host
Serial.print(F("AT+ENTM\r"));
if (!wifiWaitForOK()) return false; //error in going back to transparent mode
wifiDelay(1000); //instead of calling TCPLK to check for a link we just wait a good amount of time for a link, because TCPLK can be buggy
while(Serial.read()!=-1); //empty the read buffer so we are ready for a clean GET OR POST
return true;
}
bool wifiWaitForOK(){
return Serial.find("k");
}
bool wifiSendPost(String host, String path, String data){
Serial.print(F("POST "));
Serial.print(path);
Serial.println(F(" HTTP/1.1"));
Serial.print(F("Host: "));
Serial.println(host);
Serial.println(F("Content-Type: application/x-www-form-urlencoded"));
Serial.print(F("Content-Length: "));
Serial.println(data.length());
Serial.println();
Serial.println(data);
Serial.println();
Serial.setTimeout(5000);
if(!Serial.find("\r\n\r")) //skip the header - if this fail then the GET probably did too
return false;
Serial.setTimeout(1000);
return true;
}

View File

@@ -0,0 +1,83 @@
void setup() {
// put your setup code here, to run once:
pinMode(1,OUTPUT); //use onboard LED as output
delay(10000);//wait for wifi to connect
Serial.begin(9600); //open connection to wifi module
/*==========================================================
= NOTE: This assumes you have used the wifi module =
= web interface to set it up as a server and 9600 baud =
= See the wifi shield page for more info. =
==========================================================
Goto: http://[WIFI IP ADDRESS]:[WIFI SERVER PORT]/ to see the response
ie. http://192.168.0.123:8899/
*/
}
void loop() {
if(serverRequest()){
//new request
//find the path requested
String path = getRequestPath();
//route based on path
///wrap responses and other strings in F() to save ram
if(path == F("/on")){
digitalWrite(1,HIGH);
sendResponse(F("LED ON<BR><A HREF=\"/off\">LED OFF</A>"));
}
else if(path == F("/off")){
digitalWrite(1,LOW);
sendResponse(F("LED OFF<BR><A HREF=\"/on\">LED ON</A>"));
}
else{
sendResponse(F("<B>WELCOME</B><BR><A HREF=\"/on\">LED ON</A><BR><A HREF=\"/off\">LED OFF</A>"));
}
}
}
bool serverRequest(){
if(Serial.available()>4){
return Serial.find("GET ");
}
return false;
}
String getRequestPath(){
String path = Serial.readStringUntil(' ');
while(Serial.read() != -1); //clear read buffer
return path;
}
void sendResponse(String response){
sendResponseStart();
sendResponseChunk(response);
sendResponseEnd();
}
void sendResponseStart(){
//sends a chunked response
Serial.println(F("HTTP/1.1 200 OK"));
Serial.println(F("Content-Type: text/html"));
Serial.println(F("Connection: close"));
Serial.println(F("Transfer-Encoding: chunked"));
Serial.println();
}
void sendResponseChunk(String response){
Serial.println(response.length()+2,HEX);
Serial.println(response);
Serial.println();
}
void sendResponseEnd(){
Serial.println(F("0"));
Serial.println();
}

View File

@@ -0,0 +1,167 @@
void setup() {
// put your setup code here, to run once:
delay(10000);//wait for wifi to connect
Serial.begin(9600); //open connection to wifi module
/*==========================================================
= NOTE: This assumes you have used the wifi module =
= web interface to set it up as a server and 9600 baud =
= See the wifi shield page for more info. =
==========================================================
Goto: http://[WIFI IP ADDRESS]:[WIFI SERVER PORT]/forward to make the bot go forward
ie. http://192.168.0.123:8899/forward
change the forward to back, right, left, or stop to do those things instead
*/
botInit(); //setup the pins for the bot
}
void loop() {
if(serverRequest()){
//new request
//find the path requested
String path = getRequestPath();
//route based on path
///wrap responses and other strings in F() to save ram
if(path == F("/forward")){
botForward(255);
sendOK();
}
else if(path == F("/back")){
botReverse(255);
sendOK();
}
else if(path == F("/right")){
botRight(255);
sendOK();
}
else if(path == F("/left")){
botLeft(255);
sendOK();
}
else if(path == F("/stop")){
botStop();
sendOK();
}
else{
//it doesn't like sending big responses as one chunk - so you can use these functions to break it up
sendResponseStart();
sendResponseChunk(F("<B>BOTLY - your RESTful Bot!</B>"));
sendResponseChunk(F("<BR><A HREF=\"/forward\">Forward</A>"));
sendResponseChunk(F("<BR><A HREF=\"/back\">Back</A>"));
sendResponseChunk(F("<BR><A HREF=\"/right\">Right</A>"));
sendResponseChunk(F("<BR><A HREF=\"/left\">Left</A>"));
sendResponseChunk(F("<BR><A HREF=\"/stop\">Stop</A>"));
sendResponseEnd();
}
}
}
void sendOK(){
sendResponse(F("OK"));
}
void botForward(int botSpeed){
digitalWrite(2, HIGH);
digitalWrite(5, HIGH);
analogWrite(0, 255 - botSpeed);
analogWrite(1, 255 - botSpeed);
}
void botReverse(int botSpeed){
digitalWrite(2, LOW);
digitalWrite(5, LOW);
analogWrite(0, botSpeed);
analogWrite(1, botSpeed);
}
void botRight(int botSpeed){
digitalWrite(2, LOW);
digitalWrite(5, HIGH);
analogWrite(0, 0);
analogWrite(1, 255 - botSpeed);
}
void botHardRight(int botSpeed){
digitalWrite(2, LOW);
digitalWrite(5, HIGH);
analogWrite(0, botSpeed);
analogWrite(1, 255 - botSpeed);
}
void botLeft(int botSpeed){
digitalWrite(2, HIGH);
digitalWrite(5, LOW);
analogWrite(0, 255 - botSpeed);
analogWrite(1, 0);
}
void botHardLeft(int botSpeed){
digitalWrite(2, HIGH);
digitalWrite(5, LOW);
analogWrite(0, 255 - botSpeed);
analogWrite(1, botSpeed);
}
void botStop(){
digitalWrite(2,LOW);
digitalWrite(5,LOW);
analogWrite(0,0);
analogWrite(1,0);
}
void botInit(){
pinMode(0,OUTPUT);
pinMode(1,OUTPUT);
pinMode(2,OUTPUT);
pinMode(5,OUTPUT);
}
bool serverRequest(){
if(Serial.available()>4){
return Serial.find("GET ");
}
return false;
}
String getRequestPath(){
String path = Serial.readStringUntil(' ');
while(Serial.read() != -1); //clear read buffer
return path;
}
void sendResponse(String response){
sendResponseStart();
sendResponseChunk(response);
sendResponseEnd();
}
void sendResponseStart(){
//sends a chunked response
Serial.println(F("HTTP/1.1 200 OK"));
Serial.println(F("Content-Type: text/html"));
Serial.println(F("Connection: close"));
Serial.println(F("Transfer-Encoding: chunked"));
Serial.println();
}
void sendResponseChunk(String response){
Serial.println(response.length()+2,HEX);
Serial.println(response);
Serial.println();
}
void sendResponseEnd(){
Serial.println(F("0"));
Serial.println();
}

View File

@@ -0,0 +1,157 @@
#include <Wire.h>
#include <DigiKeyboard.h>
#define ADXL345 (0x53) //address of Accelerometer
#define ADXL345_X (0x32) //register for X value from Accelerometer
#define ADXL345_Y (0x34) //register for Y value from Accelerometer
#define ADXL345_Z (0x36) //register for Z value from Accelerometer
#define HMC5883 (0x1E) //address of Magnetometer
#define ITG3200 (0x68) //address of Gyro
int16_t magX = 0; //X value from Magnetometer
int16_t magY = 0; //Y value from Magnetometer
int16_t magZ = 0; //Z value from Magnetometer
int gyroHX = 0; //HX value from Gyro
int gyroHY = 0; //HY value from Gyro
int gyroHZ = 0; //HZ value from Gyro
void setup()
{
Wire.begin();
initAccelerometer();
initMagnetometer();
initGyro();
}
void loop()
{
DigiKeyboard.println(readAccelerometer(ADXL345_X));
DigiKeyboard.println(readAccelerometer(ADXL345_Y));
DigiKeyboard.println(readAccelerometer(ADXL345_Z));
DigiKeyboard.delay(1000);
readMagnetometer();
DigiKeyboard.println(magX);
DigiKeyboard.println(magY);
DigiKeyboard.println(magZ);
DigiKeyboard.println(getHeading());
DigiKeyboard.delay(1000);
readGyro();
DigiKeyboard.println(gyroHX);
DigiKeyboard.println(gyroHY);
DigiKeyboard.println(gyroHZ);
DigiKeyboard.delay(1000);
}
void initGyro(){
writeRegister(ITG3200, 0x3E, 0x00); //enable
writeRegister(ITG3200, 0x15, 0x07); // EB, 50, 80, 7F, DE, 23, 20, FF
writeRegister(ITG3200, 0x16, 0x1E); // +/- 2000 dgrs/sec, 1KHz, 1E, 19
writeRegister(ITG3200, 0x17, 0x00);
}
void readGyro(){
Wire.beginTransmission(ITG3200);
Wire.write(0x1B); //format x y z temp
Wire.endTransmission();
Wire.requestFrom(ITG3200, (byte)8);
// Wait around until enough data is available
while (Wire.available() < 8);
uint8_t lo = Wire.read();
uint8_t hi = Wire.read();
//throw out first two - don't seem accurate
//gyroTemp = (lo << 8) | hi; // temperature
//gyroTemp = ((double) (gyroTemp + 13200)) / 280;
lo = Wire.read();
hi = Wire.read();
gyroHX = (((lo << 8) | hi) + 120 )/ 14.375;
lo = Wire.read();
hi = Wire.read();
gyroHY = (((lo << 8) | hi) + 20 )/ 14.375;
lo = Wire.read();
hi = Wire.read();
gyroHZ = (((lo << 8) | hi) + 93 )/ 14.375;
}
void initMagnetometer(){
writeRegister(HMC5883, 0x02, 0x00); //enable
}
void readMagnetometer(){
Wire.beginTransmission(HMC5883);
Wire.write(0x03); //format X_H_M
Wire.endTransmission();
Wire.requestFrom(HMC5883, (byte)6);
// Wait around until enough data is available
while (Wire.available() < 6);
// Note high before low (different than accel)
uint8_t hi = Wire.read();
uint8_t lo = Wire.read();
// Shift values to create properly formed integer (low byte first)
magX = (int16_t)(hi | ((int16_t)lo << 8));
// Note high before low (different than accel)
hi = Wire.read();
lo = Wire.read();
// Shift values to create properly formed integer (low byte first)
magY = (int16_t)(hi | ((int16_t)lo << 8));
// Note high before low (different than accel)
hi = Wire.read();
lo = Wire.read();
// Shift values to create properly formed integer (low byte first)
magZ = (int16_t)(hi | ((int16_t)lo << 8));
}
void initAccelerometer(){
//if(readRegister(ADXL345,0x00) != 0xE5)
writeRegister(ADXL345, 0x2D, 0x08); //power up and enable measurements
writeRegister(ADXL345, 0x31, 0x01);//set range to +/-4G
}
uint16_t readAccelerometer(uint8_t reg){
Wire.beginTransmission(ADXL345);
Wire.write(reg);
Wire.endTransmission();
Wire.requestFrom(ADXL345, 2);
return (uint16_t)(Wire.read() | (Wire.read() << 8));
}
uint8_t readRegister(uint8_t address, uint8_t reg){
Wire.beginTransmission(address);
Wire.write(reg);
Wire.endTransmission();
Wire.requestFrom(address, 1);
return Wire.read();
}
void writeRegister(uint8_t address, uint8_t reg, uint8_t val){
Wire.beginTransmission(address);
Wire.write(reg);
Wire.write(val);
Wire.endTransmission();
}
float getHeading(){
// Hold the module so that Z is pointing 'up' and you can measure the heading with x&y
// Calculate heading when the magnetometer is level, then correct for signs of axis.
float heading = atan2(magY, magX);
// Correct for when signs are reversed.
if(heading < 0)
heading += 2*PI;
// Check for wrap due to addition of declination.
if(heading > 2*PI)
heading -= 2*PI;
// Convert radians to degrees for readability.
heading = heading * 180/M_PI;
return heading;
}

View File

@@ -0,0 +1,83 @@
// --------------------------------------
// i2c_scanner
//
// Version 1
// This program (or code that looks like it)
// can be found in many places.
// For example on the Arduino.cc forum.
// The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
// Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26 2013
// V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
// by Arduino.cc user Krodal.
// Changes by louarnold removed.
// Scanning addresses changed from 0...127 to 1...119,
// according to the i2c scanner by Nick Gammon
// http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
// As version 4, but address scans now to 127.
// A sensor seems to use address 120.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//
#include <Wire.h>
#include <DigiKeyboard.h>
void setup()
{
Wire.begin();
DigiKeyboard.delay(3000);
DigiKeyboard.println("\nI2C Scanner");
}
void loop()
{
byte error, address;
int nDevices;
DigiKeyboard.println("Scanning...");
nDevices = 0;
for (address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
DigiKeyboard.print("I2C device found at address 0x");
if (address < 16)
DigiKeyboard.print("0");
DigiKeyboard.print(address, HEX);
DigiKeyboard.println(" !");
nDevices++;
}
else if (error == 4)
{
DigiKeyboard.print("Unknow error at address 0x");
if (address < 16)
DigiKeyboard.print("0");
DigiKeyboard.println(address, HEX);
}
}
if (nDevices == 0)
DigiKeyboard.println("No I2C devices found\n");
else
DigiKeyboard.println("done\n");
DigiKeyboard.delay(5000); // wait 5 seconds for next scan
}