How I wanted it to work:
This is a thing that checks temperature and display the temperature and the temperature that I want. You can change the hoping temperature by using the buttons. One is high and the other is low.If the temperature is higher the fan gets on.If the spaeaker rings just once when the temp is higher than what I wanted it to be.
There seems to be no error in the code but the lcd is displaying nothing.
The speaker, TMP, MOTOR seems to be working well which is strange.
Please help me what's wrong.
Code:
*
[//LCD_Thermostat
#include <Wire.h>
#define TEMP_ADDR 72
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
byte degree\[8\] = {
B00110,
B01001,
B01001,
B00110,
B00000,
B00000,
B00000,
B00000,
};
byte fan_on\[8\] = {
B00100,
B10101,
B01110,
B11111,
B01110,
B10101,
B00100,
B00000,
};
byte fan_off\[8\] = {
B00100,
B00100,
B00100,
B11111,
B00100,
B00100,
B00100,
B00000,
};
const int SPEAKER=8;
const int DOWN_BUTTON =9;
const int UP_BUTTON=10;
const int FAN =11;
const int T0=0;
boolean lastDownTempButton = LOW;
boolean currentDownTempButton = LOW;
boolean lastUpTempButton = LOW;
boolean currentUpTempButton = LOW;
int set_temp = 23;
boolean one_time = false;
void setup()
{
pinMode(FAN, OUTPUT);
//Create a wire object for the temp sensor
Wire.begin();
//Set up the LCD's number of columns and rows
lcd.begin(16, 2);
//Make custom characters
lcd.createChar(0, degree);
lcd.createChar(1, fan_off);
lcd.createChar(2, fan_on);
//Print a static message to the LCD
lcd.setCursor(0,0);
lcd.print("Current:");
lcd.setCursor(10,0);
lcd.write((byte)0);
lcd.setCursor(11,0);
lcd.print("C");
lcd.setCursor(0,1);
lcd.print("Set:");
lcd.setCursor(10,1);
lcd.write((byte)0);
lcd.setCursor(11,1);
lcd.print("C");
lcd.setCursor(15,1);
lcd.write(1);
}
boolean debounce(boolean last, int pin)
{
boolean current = digitalRead(pin);
if (last != current)
{
delay(5);
current = digitalRead(pin);
}
return current;
}
void loop()
{/*
Wire.beginTransmission(TEMP_ADDR);
Wire.write(0);
Wire.endTransmission();
Wire.requestFrom(TEMP_ADDR, 1);
while(Wire.available() == 0);
int c = Wire.read();
*/
// for LM35 temperature sensor (Chapter3. 아날로그 신호와 센서값)
int c = analogRead(T0);
c = c*5.0 /1024.0 * 100;
Serial.println(c);
lcd.setCursor(8,0); //Move the cursor
lcd.print(c); //Print this new value
lcd.setCursor(8,0);
lcd.print(c);
currentDownTempButton = debounce(lastDownTempButton, DOWN_BUTTON);
currentUpTempButton = debounce(lastUpTempButton, UP_BUTTON);
if (lastDownTempButton== LOW && currentDownTempButton == HIGH)
{
set_temp--;
}
//Turn up the set temp
else if (lastUpTempButton== LOW && currentUpTempButton == HIGH)
{
set_temp++;
}
//Print the set temp
lcd.setCursor(8,1);
lcd.print(set_temp);
lastDownTempButton = currentDownTempButton;
lastUpTempButton = currentUpTempButton;
if (c >= set_temp)
{
if (!one_time)
{
tone(SPEAKER, 400);
delay(500);
one_time = true;
}
else
{
noTone(SPEAKER);
}
digitalWrite(FAN, HIGH);
lcd.setCursor(15,1);
lcd.write(2);
}
else
{
noTone(SPEAKER);
one_time = false;
digitalWrite(FAN, LOW);
lcd.setCursor(15,1);
lcd.write(1);
}
}][1]
*
Try to use LCD wiring as described in LiquidCristal library, use examples such as HelloWorld.
Here you can find a 'Hello World' example
Related
my esp8266 seems to be printing out a ton of memory locations to the serial monitor on arduino. my code mainly takes a post request from an android app and uses the string to execute respective blocks of code like setting and entering password.
this is my code
*i initialized some declarations for testing so i dont have to use my android phone and can just test my functions by setting variables.
#include <base64.h>
#include <xbase64.h>
#include <AES.h>
#include <AESLib.h>
#include <AES_config.h>
#include <base64.h>
#include <ESP8266WebServer.h>
#include <Servo.h>
#include <Keypad.h>
#define SOUND_VELOCITY 0.034
#define CM_TO_INCH 0.393701
const byte ROWS = 3;
const byte COLS = 3;
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'}
};
byte rowPins[ROWS] = { D3, D2, D1};
byte colPins[COLS] = { D7, D6, D5};
const char* ssid = "ESP8266-AP";
const char* passwordd = "password";
const int trigPin=D4;
const int echoPin=D0;
const float DISTANCE_THRESHOLD = 20;
long duration;
float distanceCm;
float distanceInch;
String tempString;
String pass;
char keyp;
String newString = "1020"; //change to 0102 to test other case
Keypad pad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String password = "0000"; //variable to store the password, default=0000
String input = ""; //variable to store the input
bool setPass = false; //variable to track if the user is setting the password
bool passwordSet = false; //variable to track if the password has been set
bool unlocked = false; //variable to track if the system is unlocked
bool doorOpen = false;
bool isPostHandled = true;
int openClose = 0;
const byte key[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
ESP8266WebServer server(80);
AES aes;
Servo myservo;
void handlePost() {
String val = server.arg("data");
int decodedLength = base64_dec_len(val.c_str(), val.length());
char decodedData[decodedLength];
base64_decode(decodedData, val.c_str(), val.length());
byte decrypted[decodedLength];
aes.set_key(key, sizeof(key));
aes.decrypt((byte*)decodedData, decrypted);
String decryptedVal = String((char*)decrypted);
for(int i=0; i<4; i++){
tempString[i]=decryptedVal[i];
}
newString = String(tempString);
//Serial.println("Encrypted value: " + val);
//Serial.println("Decrypted value: " + decryptedVal);
server.send(200, "text/plain", "Value Received");
isPostHandled = true;
}
/*void moveServo() {
myservo.write(0);
delay(1000);
int count = 0;
myservo.write(180);
} */
//move servo, pass argument to control degrees
void moveServo(int position) {
myservo.write(position);
delay(1000);
}
float calculateDistance() {
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
// Measure the echo return time and calculate the distance
duration = pulseIn(echoPin, HIGH);
float distanceCm = (duration / 2) * SOUND_VELOCITY;
float distanceInch = distanceCm * CM_TO_INCH;
return distanceInch;
}
void setup() {
float duration, distanceCm, distanceInch;
//esp declaration
Serial.begin(9600);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, passwordd);
server.begin();
server.on("/post", HTTP_POST, handlePost);
Serial.println("Server started");
//servo motor declaration
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
myservo.attach(D8);
myservo.write(180); // set the servo to 0 degrees
}
void loop() {
server.handleClient();
float distance = calculateDistance();
if((distance < 20) && (openClose == 0)){
doorOpen = true;
}
if ((distance < 20) && (openClose == 1)) {
doorOpen = false;
}
if(isPostHandled){
if(newString == "0102"){
do{
password = ""; //set password to a null string
Serial.println("Please set 4 digit passcode");
for(int i=0; i<4; i++){
keyp = pad.getKey();
if (keyp != NO_KEY) {
password += keyp; //add the key press to the password
Serial.print("*"); //print a * to indicate a key press
}
if (password.length() == 4) { //if the password is the same length as desired
Serial.println("Password set: " + password);
passwordSet = true;
moveServo(0);
break;
}
}
}while(!passwordSet);
newString = "";
}
else if(newString == "1020"){
input = "";
Serial.println("Please enter passcode");
do{
for(int i=0; i<4; i++){
keyp = pad.getKey();
if (keyp != NO_KEY) {
input += keyp; //add the key press to the input
Serial.print("*"); //print a * to indicate a key press
}
}
}while(!unlocked && (input.length() != 4));
if (input == password) { //if the input is the same length as the password
delay(1000);
Serial.println("Unlocked");
moveServo(0); //unlock
unlocked = true;
}else{
Serial.println("Access Denied, Wrong password");
return;
}
}
}
else{
Serial.print("isPostHandled = false");
return;
}
}
and this is the output
3fffff40: 00000000 00001113 39999999 0013be3a
3fffff50: 3ffe8a32 fffffffc 3fff019c 3ffefe98
3fffff60: 3ffeffc0 00000002 3ffefeb0 40205875
3fffff70: 3fffdad0 00000002 3ffefeb0 402058be
3fffff80: 3fffdad0 00000000 3fff001c 40203919
3fffff90: 3ffefc68 3ffefff8 00000001 40205522
3fffffa0: 00000000 00000000 3ffefc68 3fff0108
3fffffb0: 3fffdad0 00000000 3fff00dc 40208560
3fffffc0: feefeffe feefeffe 3fffdab0 401012b9
<<<stack<<<
--------------- CUT HERE FOR EXCEPTION DECODER ---------------
���u�����Server started
Please enter passcode
i tried changing serial baud rate and i cant really find anything related to what i am facing on the internet
I am trying to merge 3 separate DataLogger codes in to one. they work fine individually; however I can get all 3 to work together, can anyone help?
#include <SPI.h>
#include <SD.h>
#include "RTClib.h"
RTC_DS1307 rtc;
int sensor = A0;
int sensorInput;
double temp;
int led = 13;
int sensorMotion = A1;
int state = LOW;
int val = 0;
const char* filename = "DataLogger.csv";
File file;
void setup() {
Serial.begin(9600);
#ifndef ESP8266
while (!Serial);
#endif
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
Serial.flush();
abort();
}
if (! rtc.isrunning()) {
Serial.println("RTC is NOT running, let's set the time!");
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
pinMode(10, OUTPUT);
if (!SD.begin(10)) {
Serial.println("Error : Push the reset button");
for (;;);
}
file = SD.open(filename, FILE_WRITE);
if (file.size() == 0) {
file.println("Brightness value per seconds");
file.flush();
}
}
DateTime time = rtc.now();
val = digitalRead(sensor); // read sensor value
if (val == HIGH) { // check if the sensor is HIGH
digitalWrite(led, HIGH); // turn LED ON
delay(500); // delay 100 milliseconds
if (state == LOW) {
Serial.println(String("Motion detected
")+","+time.timestamp(DateTime::TIMESTAMP_TIME)+","+time.timestamp(DateTime::TIMESTAMP_DATE));
file.println(String("Motion detected
")+","+time.timestamp(DateTime::TIMESTAMP_TIME)+","+time.timestamp(DateTime::TIMESTAMP_DATE));
file.flush();
state = HIGH; // update variable state to HIGH
}
}
else {
digitalWrite(led, LOW); // turn LED OFF
delay(500); // delay 200 milliseconds
if (state == HIGH){
Serial.println("Motion stopped!");
state = LOW; // update variable state to LOW
}
}
}
void loop() {
measure();
delay(1000);
DateTime time = rtc.now();
sensorInput = analogRead(A0);
temp = (double)sensorInput / 1024;
temp = temp * 5;
temp = temp - 0.5;
temp = temp * 100;
delay(1000);
Serial.println(String(temp)+","+time.timestamp(DateTime::TIMESTAMP_TIME)+","+time.timestamp(DateTime::TIMESTAMP_DATE));
file.println(String(temp)+","+time.timestamp(DateTime::TIMESTAMP_TIME)+","+time.timestamp(DateTime::TIMESTAMP_DATE));
file.flush();
}
void measure() {
DateTime time = rtc.now();
int lightvalue = analogRead(A0);
Serial.println(String(lightvalue)+","+time.timestamp(DateTime::TIMESTAMP_TIME)+","+time.timestamp(DateTime::TIMESTAMP_DATE));
file.println(String(lightvalue)+","+time.timestamp(DateTime::TIMESTAMP_TIME)+","+time.timestamp(DateTime::TIMESTAMP_DATE));
file.flush();
}
I'm writing a code to take pictures if the distance is more than a certain distance after measuring the distance.
And send the distance data to Thingspeak, Store the photos on the SD card.
However, the program keeps stopping in the middle.
Serial moniter capture
Distance measurement and Thingspeak server data transfer / camera shooting were developed separately.
The two source codes worked normally independently.
But when the two codes are combined, there is an error.
Parts for Use : Arduino Uno, esp8266 wifi module, TTL Serial JPEG Camera with NTSC Video, 2Y0A21 Infrared Distance Sensor, Micro SD card adapter
#include <SoftwareSerial.h>
#include <stdlib.h>
#include <Adafruit_VC0706.h>
#include <SPI.h>
#include <SD.h>
#define DEBUG true
#define chipSelect 10
const int distancePin = 0;
String apiKey = "39R00EYW0BTKK5JJ";
SoftwareSerial esp8266(2, 3); //TX/RX
#if ARDUINO >= 100
SoftwareSerial cameraconnection = SoftwareSerial(4, 5); //TX/RX
#else
NewSoftSerial cameraconnection = NewSoftSerial(4, 5);
#endif
Adafruit_VC0706 cam = Adafruit_VC0706(&cameraconnection);
int defaultDistance = 0;
int temp = 0;
void ThingspeakSendData(String alarmData);
void Snapshots();
void setup() {
#if !defined(SOFTWARE_SPI)
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
if (chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
#else
if (chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
#endif
#endif
Serial.begin(9600);
Serial.println("VC0706 Camera snapshot test");//the program keeps stopping in the middle.
if (cam.begin()) {
Serial.println("Camera Found:");
}
else {
Serial.println("No camera found?");
return;
}
char *reply = cam.getVersion();
if (reply == 0) {
Serial.print("Failed to get version");
}
else {
Serial.println("-----------------");
Serial.print(reply);
Serial.println("-----------------");
}
cam.setImageSize(VC0706_640x480);
uint8_t imgsize = cam.getImageSize();
Serial.print("Image size: ");
if (imgsize == VC0706_640x480) Serial.println("640x480");
if (imgsize == VC0706_320x240) Serial.println("320x240");
if (imgsize == VC0706_160x120) Serial.println("160x120");
esp8266.begin(9600);
sendData("AT+RST\r\n", 2000, DEBUG); //reset module
sendData("AT+CWMODE=1\r\n", 1000, DEBUG); //dual mode로 설정
sendData("AT+CWJAP=\"0sangsiljangnim\",\"123456788\"\r\n", 5000, DEBUG);
// 2Y0A21
analogReference(DEFAULT);
pinMode(distancePin, INPUT);
// distancePin 2Y0A21
int raw = analogRead(distancePin);
int volt = map(raw, 0, 1023, 0, 5000);
int distance = (21.61 / (volt - 0.1696)) * 1000;
defaultDistance = distance;
Serial.println("Default : " + defaultDistance);
}
void loop() {
// distancePin 2Y0A21
int raw = analogRead(distancePin);
int volt = map(raw, 0, 1023, 0, 5000);
int distance = (21.61 / (volt - 0.1696)) * 1000;
Serial.println(distance);
if (distance < defaultDistance)
{
String alarmData = "1";
esp8266.listen();
ThingspeakSendData(alarmData);
cameraconnection.listen();
Snapshots();
}
else if (distance == defaultDistance)
{
String alarmData = "0";
esp8266.listen();
ThingspeakSendData(alarmData);
}
delay(3000);
}
void ThingspeakSendData(String alarmData) {
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += "184.106.153.149";
cmd += "\",80";
esp8266.println(cmd);
if (esp8266.find("Error")) {
Serial.println("AT+CIPSTART error");
return;
}
String getStr = "GET /update?api_key=";
getStr += apiKey;
getStr += "&field1=";
getStr += String(alarmData);
getStr += "\r\n\r\n";
// Send Data
cmd = "AT+CIPSEND=";
cmd += String(getStr.length());
esp8266.println(cmd);
if (esp8266.find(">")) {
esp8266.print(getStr);
}
else {
esp8266.println("AT+CIPCLOSE");
// alert uesp8266
Serial.println("AT+CIPCLOSE");
}
}
String sendData(String command, const int timeout, boolean debug) {
String response = "";
esp8266.print(command);
long int time = millis();
while ((time + timeout) > millis()) {
while (esp8266.available()) {
char c = esp8266.read();
response += c;
}
}
if (debug) {
Serial.print(response);
}
return response;
}
void Snapshots() {
Serial.println("Snap in 3 secs...");
delay(3000);
if (!cam.takePicture())
Serial.println("Failed to snap!");
else
Serial.println("Picture taken!");
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
return;
}
char filename[13];
strcpy(filename, "IMAGE00.JPG");
for (int i = 0; i < 100; i++) {
filename[5] = '0' + i / 10;
filename[6] = '0' + i % 10;
if (!SD.exists(filename)) {
break;
}
}
File imgFile = SD.open(filename, FILE_WRITE);
uint16_t jpglen = cam.frameLength();
Serial.print("Storing ");
Serial.print(jpglen, DEC);
Serial.print(" byte image.");
int32_t time = millis();
pinMode(8, OUTPUT);
byte wCount = 0;
while (jpglen > 0) {
uint8_t *buffer;
uint8_t bytesToRead = min(32, jpglen);
buffer = cam.readPicture(bytesToRead);
imgFile.write(buffer, bytesToRead);
if (++wCount >= 64) {
Serial.print('.');
wCount = 0;
}
jpglen -= bytesToRead;
}
imgFile.close();
time = millis() - time;
Serial.println("done!");
Serial.print(time); Serial.println(" ms elapsed");
}
I am trying to set the timer after which the audio will automatically played once but it is not playing anything just a noise but when i run the audio program separately it work perfectly good
This is my code please help me out where i am doing wrong.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SD.h>
#include <TMRpcm.h>
#include <SPI.h>
int timer1_counter;
#define SD_ChipSelectPin 4
TMRpcm tmrpcm;
unsigned long time_now = 0;
LiquidCrystal_I2C lcd(0x27, 16, 2);
const byte ledPin = 13;
const byte interruptPin1 = 2;
const byte interruptPin2 = 3;
int counter2 = 0;
volatile byte state = LOW;
int count = 0;
int limit = 0;
bool TimerFlag = false;
int deviceTime = 0;
int set = 5;
bool soundplayflag = false;
void setup()
{
lcd.begin();
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(interruptPin1, INPUT_PULLUP);
pinMode(interruptPin2, INPUT_PULLUP);
pinMode(set, INPUT_PULLUP);
lcd.backlight();
lcd.setCursor(1,0);
lcd.print("Please Select:");
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = 31250; // compare match register 16MHz/256/2Hz
TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts(); // enable all interrupts
// initialize timer1
}
ISR(TIMER1_COMPA_vect) // timer compare interrupt service routine
{
if (soundplayflag == true)
{
counter2 = counter2+1;
Serial.println(counter2/2);
}
}
void loop()
{
//unsigned long currentMillis = millis();
int up = digitalRead(interruptPin1);
int down = digitalRead(interruptPin2);
int setbutton = digitalRead(set);
delay(230);
if (up == 0)
{
Serial.println("Entering up");
count++;
if (count >= 0) {
lcdprint(count);
}
}
else if (down == 0)
{
Serial.println("Entering down");
count--;
if (count >= 0) {
lcdprint(count);
}
}
else if (setbutton == 0)
{
Serial.println("Entering set");
soundplayflag=true;
deviceTime = count;
}
if (deviceTime > 0)
{
if (deviceTime == counter2)
{
soundplayflag=false;
Serial.println("Hello world");
PlaySound();
counter2 = 0;
}
}
}
int lcdprint(int a)
{
lcd.clear();
lcd.setCursor(1,0);
lcd.print("Please Select:");
lcd.setCursor (7,1);
lcd.print(a);
Serial.println(a);
lcd.setCursor (10,1);
lcd.print("Min");
}// end of lcdprint(int a)
void PlaySound()
{
for (int i = 0; i < 10; i++)
{
tmrpcm.setVolume(5);
tmrpcm.play("3.wav");
delay(1000);
}// end of for loop
}// end of void PlaySound()
my expected output is it should play the sound when i set the time
It seems TMRpcm uses Timer1, which conflicts with your TIMER1_COMPA_vect. That would explain why it's working if you run nothing else.
Maybe try to use #define USE_TIMER2?
My goal is to transfer a speed value from an encoder from a slave Arduino to a master Arduino via SPI. I am currently getting zeros on the master side serial print and I'm not sure what I am doing wrong. I have increased the amount of time to wait several times to see if it was a processing time issue but I had it waiting for 100mS with still no change. I know an unsigned int is 4 bytes and I am unsure if a union is the best option in this case seeing I might be overwriting my data due to the separate interrupts but I am unsure. I thought to use a struct since I'll have to move to transferring an array of floats and ints over SPI from various sensors including this encoder later. Below is my code and thank you for any help received:
Slave
#include "math.h"
#define M_PI
byte command = 0;
const int encoder_a = 2; // Green - pin 2 - Digital
const int encoder_b = 3; // White - pin 3 - Digital
long encoder = 0;
int Diameter = 6; // inches
float previous_distance = 0;
unsigned long previous_time = 0;
void setup (void)
{
Serial.begin(115200);
pinMode(MOSI, INPUT);
pinMode(SCK, INPUT);
pinMode(SS, INPUT);
pinMode(MISO, OUTPUT);
// turn on SPI in slave mode
SPCR |= _BV(SPE);
// turn on interrupts
SPCR |= _BV(SPIE);
pinMode(encoder_a, INPUT_PULLUP);
pinMode(encoder_b, INPUT_PULLUP);
attachInterrupt(0, encoderPinChangeA, CHANGE);
attachInterrupt(1, encoderPinChangeB, CHANGE);
}
// SPI interrupt routine
ISR (SPI_STC_vect)
{
union Data{
float f;
byte buff[4];}
data;
byte c = SPDR;
data.f = assembly_speed();
command = c;
switch (command)
{
// no command? then this is the command
case 0:
SPDR = 0;
break;
// incoming byte, return byte result
case 'a':
SPDR = data.buff[0];
break;
// incoming byte, return byte result
case 'b':
SPDR = data.buff[1];
break;
// incoming byte, return byte result
case 'c':
SPDR = data.buff[2];
break;
// incoming byte, return byte result
case 'd':
SPDR = data.buff[3];
break;
}
}
void loop (void)
{
// if SPI not active, clear current command
if (digitalRead (SS) == HIGH)
command = 0;
}
void encoderPinChangeA()
{
encoder += digitalRead(encoder_a) == digitalRead(encoder_b) ? -1 : 1;
}
void encoderPinChangeB()
{
encoder += digitalRead(encoder_a) != digitalRead(encoder_b) ? -1 : 1;
}
float distance_rolled()
{
float distance_traveled = (float (rotation()) / 8) * PI * Diameter;
return distance_traveled;
}
int rotation()
{
float eigth_rotation = encoder / 300;
return eigth_rotation;
}
float assembly_speed()
{
float current_distance = (float (rotation()) / 8) * PI * Diameter;
unsigned long current_time = millis();
unsigned long assemblySpeed = (((current_distance - previous_distance) /
12) * 1000) / (current_time - previous_time); // gives ft/s
previous_distance = current_distance;
previous_time = current_time;
return assemblySpeed;
}
Master
#include <SPI.h>
void setup (void)
{
pinMode(MOSI, OUTPUT);
pinMode(MISO, INPUT);
pinMode(SCK, OUTPUT);
pinMode(SS, OUTPUT);
Serial.begin (115200);
Serial.println ();
digitalWrite(SS, HIGH);
SPI.begin ();
SPI.setClockDivider(SPI_CLOCK_DIV8);
}
byte transferAndWait (const byte what)
{
byte a = SPI.transfer (what);
delayMicroseconds(10000);
return a;
}
union Data
{
float f;
byte buff[4];
}
data;
void loop (void)
{
digitalWrite(SS, LOW);
transferAndWait ('a');
data.buff[0] = transferAndWait ('b');
data.buff[1] = transferAndWait ('c');
data.buff[2] = transferAndWait ('d');
data.buff[3] = transferAndWait (0);
digitalWrite(SS, HIGH);
Serial.print("data.f = ");Serial.print(data.f);Serial.println(" Ft/s");
delay(200);
}