I am currently involved in a project which needs to have 4 led's and one stepper motor to be turned on/off independently over wifi.
Just to mention Im using an Uno r3, official Wifi shield and official motor shield.
I have the 4 led's working on pins A2-A5 or in my code pins (16-19) leaving free all digital pins and have set up my stepper motor to pins 9,8,6,5. When i go to the ip address i can turn off/on each LED independently but with the stepper motor it either judders and does not move or nothing at all.
I have posted my code so far below, would really appreciate any help or advice. Thanks
/*
WiFi Web Server LED Blink
A simple web server that lets you blink an LED via the web.
This sketch will print the IP address of your WiFi Shield (once connected)
to the Serial monitor. From there, you can open that address in a web browser
to turn on and off the LED on pin 9.
This example is written for a network using WPA encryption. For
WEP or WPA, change the Wifi.begin() call accordingly.
Circuit:
* WiFi shield attached
* LED attached to pin 9
created 25 Nov 2012
by Tom Igoe
*/
#include <SPI.h>
#include <WiFi.h>
#include <Stepper.h>
char ssid[] = "username"; // your network SSID (name)
char pass[] = "password"; // your network password
int keyIndex = 0;
int delaylegnth = 7;
int state = 0;
int x = 0;
// your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
Serial.begin(9600); // initialize serial communication
pinMode(16, OUTPUT); // set the LED pin mode
pinMode(17, OUTPUT); // set the LED pin mode
pinMode(18, OUTPUT); // set the LED pin mode
pinMode(19, OUTPUT); // set the LED pin mode
//establish motor direction toggle pins
pinMode(5, OUTPUT); //CH A -- HIGH = forwards and LOW = backwards???
pinMode(6, OUTPUT); //CH B -- HIGH = forwards and LOW = backwards???
//establish motor brake pins
pinMode(9, OUTPUT); //brake (disable) CH A
pinMode(8, OUTPUT); //brake (disable) CH B
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while(true); // don't continue
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin(); // start the web server on port 80
printWifiStatus(); // you're connected now, so print out the status
}
void loop() {
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("new client"); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
String currentLine2 = "";
String currentLine3 = "";
String currentLine4 = "";
String currentLine5 = "";
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// the content of the HTTP response follows the header:
client.print("Click here turn the LED on pin 4 on<br>");
client.print("Click here turn the LED on pin 4 off<br>");
client.print("Click here turn the LED on pin 5 on<br>");
client.print("Click here turn the LED on pin 5 off<br>");
client.print("Click here turn the LED on pin 6 on<br>");
client.print("Click here turn the LED on pin 6 off<br>");
client.print("Click here turn the LED on pin 2 on<br>");
client.print("Click here turn the LED on pin 2 off<br>");
client.print("Click here turn the Stepper<br>");
// The HTTP response ends with another blank line:
client.println();
// break out of the while loop:
break;
}
else { // if you got a newline, then clear currentLine:
currentLine = "";
currentLine2 = "";
currentLine3 = "";
currentLine4 = "";
currentLine5 = "";
}
}
else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c;
currentLine2 += c;
currentLine3 += c;
currentLine4 += c;
currentLine5 += c;
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
digitalWrite(16, HIGH); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
digitalWrite(16, LOW); // GET /L turns the LED off
}
if (currentLine2.endsWith("GET /A")) {
digitalWrite(17, HIGH); // GET /A turns the LED on
}
if (currentLine2.endsWith("GET /B")) {
digitalWrite(17, LOW); // GET /B turns the LED off
}
if (currentLine3.endsWith("GET /C")) {
digitalWrite(18, HIGH); // GET /A turns the LED on
}
if (currentLine3.endsWith("GET /D")) {
digitalWrite(18, LOW); // GET /B turns the LED off
}
if (currentLine4.endsWith("GET /E")) {
digitalWrite(19, HIGH); // GET /A turns the LED on
}
if (currentLine4.endsWith("GET /F")) {
digitalWrite(19, LOW); // GET /B turns the LED off
}
}
if (currentLine5.endsWith("GET /G")) { //stepper motor
// for(int x; x < 500; x++) {
// state=digitalRead(0);
// if (state == LOW){
digitalWrite(9, LOW); //ENABLE CH A
digitalWrite(8, HIGH); //DISABLE CH B
digitalWrite(5, HIGH); //Sets direction of CH A
analogWrite(A0, 255); //Moves CH A
// }
// else{
delay(delaylegnth);
digitalWrite(9, HIGH); //DISABLE CH A
digitalWrite(8, LOW); //ENABLE CH B
digitalWrite(6, LOW); //Sets direction of CH B
analogWrite(A1, 255); //Moves CH B
delay(delaylegnth);
digitalWrite(9, LOW); //ENABLE CH A
digitalWrite(8, HIGH); //DISABLE CH B
digitalWrite(5, LOW); //Sets direction of CH A
analogWrite(A0, 255); //Moves CH A
delay(delaylegnth);
digitalWrite(9, HIGH); //DISABLE CH A
digitalWrite(8, LOW); //ENABLE CH B
digitalWrite(6, HIGH); //Sets direction of CH B
analogWrite(A1, 255); //Moves CH B
delay(delaylegnth);
// }
// }
}
}
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
// print where to go in a browser:
Serial.print("To see this page in action, open a browser to http://");
Serial.println(ip);
}
Related
void loop() // run over and over
{
while (!mySerial.available()); // stay here so long as COM port is empty
receivedChar = mySerial.read();
if (receivedChar == '1')
{
digitalWrite(LED, HIGH);
for (int i=0; i<500; i++)
{
digitalWrite(buz, HIGH);
delayMicroseconds(500);
digitalWrite(buz, LOW);
delayMicroseconds(500);
}
}// if it's a 1 turn LED on
if (receivedChar == '2')
{
digitalWrite(LED, LOW);
} // if it's a 2 turn LED off
} // if it is a 3 flash the LED
here "forloop" is not looping please help for this
EDIT with completely new answer:
Ok, I hope I understand your problem better. If you want to have the LED blinking until you receive a corresponding other command, you can do something like this (not explicitly tested):
Another edit: from your comment on the question I seem to understand that you want to toggle on and off the blinking whenever you are sending 1? If that that's the case, you can maybe add another boolean to the check which you toggle when you send a 1.
void loop() // run over and over
{
static bool active = false;
static char receivedChar = '0';
if (mySerial.available()) {
receivedChar = mySerial.read();
// if you received a 1, change the state of the 'active' boolean
if (receivedChar == '1')
{
active = !active;
}
}
// only perform the action on receiving 1
// only when also the boolean is set to the correct value
if (receivedChar == '1' && active)
{
digitalWrite(buz, HIGH);
delay(100);
digitalWrite(buz, LOW);
delay(100);
}// if it's a 1 turn LED on
if (receivedChar == '2')
{
digitalWrite(LED, LOW);
} // if it's a 2 turn LED off
} // if it is a 3 flash the LED
declaring receivedChar as static should keep its value the same for the next iteration of loop. This means that the loop will run and if you sent a 1 it will always enter the if (receivedChar == '1') condition and switch the LED on and off with whatever delay you choose and then simply repeat this until you send another character, e.g. 2 at which point he will enter condition if (receivedChar == '2'), switches off the LED and will simply go back to if (receivedChar == '2') until you send something else again.
Does this help?
Yet another edit:
with an arduino and a LED connected to pin 3, the following sketch does what you are asking:
Send 1 over the serial port, the LED starts blinking. Send another 1, the blinking stops. If you send a 2, the blinking also stops.
If this sketch does not show the behavior described above, then you are doing something in your code that you are not disclosing.
int LED = 3;
// the setup routine runs once when you press reset:
void setup() {
Serial.begin(9600);
// initialize the digital pin as an output.
pinMode(LED, OUTPUT);
}
void loop() // run over and over
{
static bool active = false;
static char receivedChar = '0';
if (Serial.available()) {
receivedChar = Serial.read();
// if you received a 1, change the state of the 'active' boolean
if (receivedChar == '1')
{
active = !active;
}
}
// only perform the action on receiving 1
// only when also the boolean is set to the correct value
if (receivedChar == '1' && active)
{
digitalWrite(LED,HIGH);
delay(100);
digitalWrite(LED, LOW);
delay(100);
}// if it's a 1 turn LED on
if (receivedChar == '2')
{
digitalWrite(LED, LOW);
active = false;
} // if it's a 2 turn LED off
} // if it is a 3 flash the LED
I would recommend to use String and append the single characters and use Serial.available() > 0 with a short delay as loop condition. I hope that this is going to help you.
int led = 13;
void setup(){
pinMode(led, OUTPUT);
Serial.begin(9600);
Serial.flush();
}
void loop()
{
String receivedChars = "";
while (Serial.available() > 0){
receivedChars += (char) Serial.read();
delay(5);
}
if (receivedChars == "1"){
digitalWrite(led, HIGH);
}
else if (receivedChars == "2"){
digitalWrite(led, LOW);
}
}
EDIT Seeing the discusion in other answers, seems like you want to make a LED blink when received a 1 and stop blinking when received a 2. First you should edit the original question, because sometimes you write digitalWrite(LED, HIGH) and sometimes it's digitalWrite(buz, HIGH). That's confusing if you are using the same LED in the same pin.
Then I would suggest this code.
boolean blink = false;
byte state = 0;
void loop()
{
if (mySerial.available()) // there is some data to read
{
receivedChar = mySerial.read();
switch (receivedChar)
{
case '1':
blink = true;
break;
case '2':
blink = false;
digitalWrite(LED, LOW); //turn off LED
break;
}
}
if (blink)
{
state ^= 1; //switch bit using xor operator
digitalWrite(PED, state);
}
delay(500);
}
Hope it's easy to understand. If not, feel free to ask.
OLD POST: Are you sure it's not looping? May be if (receivedChar) condition is always false? Send some debugging info through serial port to check it.
Also, the loop() function is an infinite loop, there's no need to add one more. Just check if (mySerial.available()).
Seems like you want to make some sound while the LED is on, you can use the Tone function for that.
I would suggest something like this:
void loop()
{
if (mySerial.available()) // there is some data to read
{
receivedChar = mySerial.read();
if (receivedChar == '1')
{
mySerial.println("Received a 1"); // for debugging
digitalWrite(LED, HIGH);
tone(buz, 1000, 500);
}
if (receivedChar == '2')
{
mySerial.println("Received a 2"); // for debugging
digitalWrite(LED, LOW);
}
}
}
So i have rewritten my code. when I press the button connected on pin 2 it makes pin 13 HIGH and it sends a signal via a transceiver to a receiver (type of transceiver and receiver is irrelevant). I connected a wire from the receiver(where pin 13 makes it HIGH) to pin 7 on the arduino. Also I connected a LED to pin 8 to indicate when pin 7 is HIGH.
My main focus is to calculate the time it took from pressing the button until pin 7 is made HIGH on the Arduino. I am using a Arduino Leonardo( also irrelevant information).
This is my code :
int buttonState;
int buttonPin = 2;
int LbuttonState; // last button state
int pin13 = 13;
int pin7state;
int pin7 = 7;
int Lpin7state; // last pin 7 state
int pin8 = 8;
long startTimeKeeper;
long endTimeKeeper;
long elapsedTime;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
pinMode(pin13, OUTPUT);
pinMode(pin7, INPUT);
pinMode(pin8, OUTPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if(buttonState == HIGH && LbuttonState == LOW) {
startTime(); // start the time
digitalWrite(pin13, HIGH);
LbuttonState = buttonState;
} else if(buttonState == HIGH && LbuttonState == LOW) {
digitalWrite(pin13, LOW);
} else if(buttonState == LOW && LbuttonState == HIGH) {
digitalWrite(pin13, LOW);
LbuttonState = buttonState;
} else//(buttonState == LOW && LbuttonState == LOW)
digitalWrite(pin13, LOW);
pin7state = digitalRead(pin7);
if(pin7state == HIGH && Lpin7state == LOW) {
stopTime(); // stop the time
digitalWrite(pin8, HIGH);
Lpin7state = pin7state;
} else if(pin7state == HIGH && Lpin7state == HIGH) {
digitalWrite(pin8, HIGH);
} else if(pin7state == LOW && Lpin7state == HIGH) {
digitalWrite(pin8, LOW);
Lpin7state = pin7state;
} else//(pin7state == LOW && Lpin7state == LOW)
digitalWrite(pin8, LOW);
}
void startTime() {
startTimeKeeper = millis();
}
void stopTime() {
endTimeKeeper = millis();`enter code here`
elapsedTime = endTimeKeeper - startTimeKeeper;
Serial.print(elapsedTime);
}
I would suggest using interrupts, especially since the Leonardo supports interrupts triggered on state changes of both of your chosen pins.
If I understand the core of the problem correctly, you want the time elapsed between a falling edge (HIGH to LOW) from your button press on pin 2 to a rising edge (LOW to HIGH) on pin 7. If I misinterpreted that and your button is actually active-high, just change the final parameter of attachInterrupt(interrupt, ISR, mode) to RISING.
After these are setup, our specified interrupt service routine (ISR) functions will be called whenever the specified state or state change occurs. We want to do minimal work in these ISRs since no other ISR can be triggered while one is running. Recording a start or stop time would be fine.
However, interrupts cannot use millis() or micros() directly because those functions themselves use interrupts. To work around that constraint, we'll toggle a simple flag of our own in each ISR--to indicate that it was triggered--then poll for that flag value in the main loop, where we'll do our timer start/stop actions. I subbed-in micros() for better accuracy since the time between a button press and a signal received should be small (never on the order of minutes, anyway).
#define ULONG_MAX 0xFFFFFFFFUL
unsigned long startTimeKeeper, stopTimeKeeper, elapsedTime;
volatile boolean buttonFlag = false, signalFlag = false;
void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(7, INPUT);
pinMode(13, OUTPUT);
pinMode(8, OUTPUT);
// Int.2 corresponds to pin 2
attachInterrupt(2, buttonPressed, FALLING);
// Int.4 corresponds to pin 7
attachInterrupt(4, signalReceived, RISING);
}
void loop() {
// Loop until the buttonPressed ISR sets this flag
if (buttonFlag) {
// Record the start time
startTimeKeeper = micros();
// Do nothing until the signal flag is set by the ISR
while (!signalFlag);
// Record the end time
stopTimeKeeper = micros();
// Normal case - stop time is apparently after start time
if (stopTimeKeeper > startTimeKeeper)
elapsedTime = stopTimeKeeper - startTimeKeeper;
// Overflow case - stop time is apparently before start time
else
elapsedTime = stopTimeKeeper + (ULONG_MAX - startTimeKeeper);
Serial.print(elapsedTime);
signalFlag = buttonFlag = false;
}
}
// Very lightweight ISRs
void buttonPressed() {
buttonFlag = true;
}
void signalReceived() {
signalFlag = true;
}
Since we immediately begin waiting for the signalReceived() ISR to activate signalFlag after we register a button press, we don't have to worry too much about debouncing the switch in this case.
In general, you'll want to debounce your switches, either with physical circuitry or software counters. Check out this tutorial to get started with software, or look here for information on building debounce circuits.
Using Arduino + Sparkfun SM5100B + Cellular Shield.
I need the following code to loop trough a set of mobile numbers with about a minute delay for each. If the Arduino receives a positive/'yes' message I need this to break the loop and end it. If it receives a 'no' or a negative message I need it to continue its loop.
Right now, I have it successfully compiling, but while it delays correctly in the loop and prints the correct messages in the serial monitor, it actually only sends a test message to the first number along with the AT commands to send to the next number (in the text message received by the first number) in this code I have included the receive message code yet, as I would like to get the loop working first before I try to break it.
//THis code is sending both messages to first number
#include <GSM.h>
#define PINNUMBER ""
const int buttonPin = 4;
const int ledPin1 = 13;
const int ledPin2 = 12;
int buttonState = 0;
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;
// char array of the telephone number to send SMS
const char* number1 = "xxxxxxxxxxxxx"; // enter any two mobile numbers here in international format
const char* number2 = "xxxxxxxxxxxxx";
// char array of the message
char txtMsg[200]="test";
// connection state
boolean notConnected = true;
void setup()
{
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(buttonPin, INPUT);
// initialize serial communications
Serial.begin(9600);
Serial.println("SMS Messages Sender");
// Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_READY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
}
void loop()
{
buttonState = digitalRead(buttonPin);
{
sendSMS();
}
}
void sendSMS()
{
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, LOW);
if(buttonState == HIGH) {
buttonState = 1;
};
if (buttonState == 1) {
digitalWrite(ledPin2, HIGH);
delay(1000);
Serial.print("Message to mobile number: ");
Serial.println(number1);
// sms text
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
// send the message
sms.beginSMS(number1);
sms.print(txtMsg);
Serial.println("\nFirst Message Sent\n");
digitalWrite(ledPin2, LOW);
delay (60000);
digitalWrite(ledPin2, HIGH);
delay(1000);
Serial.print("Message to mobile number: ");
Serial.println(number2);
// sms text
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
// send the message
sms.beginSMS(number2);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nSecond Message Sent\n");
digitalWrite(ledPin2, LOW);
}
}
Change GSM_sms;
to
GSM_smsone;
GSM_smstwo;
use
smsone.beginSMS(number1);
smsone.print(txtMsg);
smsone.endSMS();
smstwo.beginSMS(number2);
smstwo.print(txtMsg);
smstwo.endSMS();
for sending the sms.
#include <GSM.h>
#define PINNUMBER ""
const int buttonPin = 4;
const int ledPin1 = 13;
const int ledPin2 = 12;
int buttonState = 0;
// initialize the library instance
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS smsone;
GSM_SMS smstwo;
// char array of the telephone number to send SMS
const char* number1 = "xxxxxxxxxxxxx"; // enter any two mobile numbers here in international format
const char* number2 = "xxxxxxxxxxxxx";
// char array of the message
char txtMsg[200] = "test";
// connection state
boolean notConnected = true;
void setup()
{
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(buttonPin, INPUT);
// initialize serial communications
Serial.begin(9600);
Serial.println("SMS Messages Sender");
// Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes
while (notConnected)
{
if (gsmAccess.begin(PINNUMBER) == GSM_READY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
}
void loop(){
buttonState = digitalRead(buttonPin);
{
sendSMS();
}
}
void sendSMS()
{
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, LOW);
if (buttonState == HIGH) {
buttonState = 1;
};
if (buttonState == 1) {
digitalWrite(ledPin2, HIGH);
delay(1000);
Serial.print("Message to mobile number: ");
Serial.println(number1);
// sms text
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
// send the first message
smsone.beginSMS(number1);
smsone.print(txtMsg);
smsone.endSMS();
Serial.println("\nFirst Message Sent\n");
digitalWrite(ledPin2, LOW);
delay (60000);
digitalWrite(ledPin2, HIGH);
delay(1000);
Serial.print("Message to mobile number: ");
Serial.println(number2);
// sms text
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
// send the second message
smstwo.beginSMS(number2);
smstwo.print(txtMsg);
smstwo.endSMS();
Serial.println("\nSecond Message Sent\n");
digitalWrite(ledPin2, LOW);
}
}
So I hacked at a getFlow function for the Arduino sketch I am working on, and I am getting output of the function in the console of the iPhone, but when I hook up the computer to the Arduino, and open the serial monitor I don't see any output from the getFlow4 function. I am using a Swiss flow SF800 flowmeter / flowsensor.
/*
* kegboard-clone-4-KegCop
* This code is public domain
*
* This sketch sends a receives a multibyte String from the iPhone
* and performs functions on it.
*
* This Arduino sketch is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Public License
* along with this sketch. If not, see <http://www.gnu.org/licenses/>.
*
* Examples:
* http://arduino.cc/en/Tutorial/SerialEvent
* http://arduino.cc/en/Serial/read
* http://stackoverflow.com/questions/16532586/arduino-sketch-that-responds-to-certain-commands-how-is-it-done/
* http://davebmiller.wordpress.com/2011/01/18/arduino-flowmeter/
* http://forum.arduino.cc/index.php?topic=52003.0
* http://arduino.cc/en/Reference/AttachInterrupt
*
* TODO:
* - eventually get code working with the SF800 flow sensor / flowmeter
*
*/
// flow_A LED
int led = 4;
// relay_A
const int RELAY_A = A0;
// string / serial event variables
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
boolean valve_open = false;
// FLOWMETER SHIT
// flowmeter 0 pulse (input) = digital pin 2
// https://github.com/Kegbot/kegboard/blob/master/arduino/kegboard/kegboard_config.h
// which pin to use for reading the sensor? kegboard-mini shield has digital pin 2 allocated
// the SF800 outputs 5400 pulses per litre
// The hall-effect flow sensor (SF800) outputs approximately 5400 pulses per second per litre/minute of flow
int sensorInterrupt = 0; // changed from byte
int sensorPin = 2; // changed from byte
int sensorPinState = 0; // variable for storing state of sensor pin
// read RPM
int rpmcount = 0;
int rpm = 0;
unsigned long lastmillis = 0;
void setup() {
// initialize serial
// Serial.flush(); // flush the serial buffer on setup.
Serial.begin(115200); // open serial port, sets data rate to 9600bps
Serial.println("Power on test");
inputString.reserve(200);
valve_open = false;
// relay for solenoid cut off valve
pinMode(RELAY_A, OUTPUT);
// flowmeter shit
pinMode(sensorPin, INPUT);
digitalWrite(sensorPin, HIGH); // Need to set these HIGH so they won't just tick away
// The Hall-effect sensor is connected to pin 2 which uses interrupt 0.
// Configured to trigger on a RISING state change (transition from HIGH
// state to LOW state)
attachInterrupt(0, rpm_fan, RISING);
}
void open_valve() {
digitalWrite(RELAY_A, HIGH); // turn RELAY_A on
valve_open = true;
}
void close_valve() {
digitalWrite(RELAY_A, LOW); // turn RELAY_A off
valve_open = false;
}
void flow_A_blink() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for one second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
void flow_A_blink_stop() {
digitalWrite(led, LOW);
}
void flow_A_on() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
}
void flow_A_off() {
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
}
// flowmeter shit
void getFlow4() {
// Serial.println("im here");
// Serial.println(sensorPin);
sensorPinState = digitalRead(sensorPin);
// Serial.println(sensorPinState);
if (millis() - lastmillis >= 1000){ //Uptade every one second, this will be equal to reading frecuency (Hz).
detachInterrupt(0);//Disable interrupt when calculating
rpm = rpmcount * 60; // Convert frecuency to RPM, note: this works for one interruption per full rotation. For two interrups per full rotation use rpmcount * 30.
Serial.print("RPM =\t"); //print the word "RPM" and tab.
Serial.print(rpm); // print the rpm value.
Serial.print("\t Hz=\t"); //print the word "Hz".
Serial.println(rpmcount); //print revolutions per second or Hz. And print new line or enter.
rpmcount = 0; // Restart the RPM counter
lastmillis = millis(); // Uptade lasmillis
attachInterrupt(0, rpm_fan, RISING); //enable interrupt
}
if(sensorPinState == LOW) {
flow_A_off();
Serial.println("don't blink");
}
if(sensorPinState == HIGH) {
flow_A_on();
Serial.println("blink damnit");
}
if(stringComplete) {
if(inputString.equals("{close_valve}\n")) {
// Serial.println("close vavle.");
close_valve();
}
return;
}
}
void rpm_fan(){
rpmcount++;
}
/*
* Main program loop, runs over and over repeatedly
*/
void loop() {
if(stringComplete) {
// Serial.println(inputString);
if(inputString.equals("{open_valve}\n")) {
// Serial.println("inputString equates :)");
open_valve();
}
if(inputString.equals("{close_valve}\n")) {
// Serial.println("close vavle.");
close_valve();
}
if(valve_open) {
// Serial.println("valve_open = true");
inputString = "";
stringComplete = false;
getFlow4();
}
// clear the string:
inputString = "";
stringComplete = false;
}
//Serial.println("over and over");
}
/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
while(Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
// Serial.println(inputString.length());
}
}
So I'm trying to count the pulses of a swiss flow SF800 flow sensor / meter in my current Arduino project, but I'm currently not getting any data printed out to the console. My Arduino sketch looks like the following,
// global variables should be identified with _
// flow_A LED
int led = 4;
// relay_A
const int RELAY_A = A0;
// variables from sketch example
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
// FLOWMETER SHIT
// flowmeter 0 pulse (input) = digital pin 2
// https://github.com/Kegbot/kegboard/blob/master/arduino/kegboard/kegboard_config.h
// which pin to use for reading the sensor? kegboard-mini shield has digital pin 2 allocated
# define FLOWSENSORPIN 2
int rpmcount = 0;
int rpm = 0;
unsigned long lastmillis = 0;
void setup() {
// initialize serial
Serial.begin(9600); // open serial port, sets data rate to 115200bps
inputString.reserve(200);
pinMode(RELAY_A, OUTPUT);
// flowmeter shit
pinMode(FLOWSENSORPIN, INPUT);
digitalWrite(FLOWSENSORPIN, HIGH); // Need to set these HIGH so they won't just tick away
attachInterrupt(0, rpm_fan, FALLING); // interrupt is attached, is on pin two(2).
}
void open_valve() {
digitalWrite(RELAY_A, HIGH); // turn RELAY_A on
// Serial.println("Valve Open");
Serial.write("{valve_open}");
}
void close_valve() {
digitalWrite(RELAY_A, LOW); // turn RELAY_A off
// Serial.println("Vavle Closed");
Serial.write("{valve_close}");
}
void flow_A_blink() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for one second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
void flow_A_blink_stop() {
digitalWrite(led, LOW);
}
// flowmeter shit
void getFlow() {
Serial.println("reached getFlow function");
if(millis() - lastmillis == 1000) { // Update every one second, this will be equal to reading frequency (Hz).
detachInterrupt(0); // Disable interrupt when calculating
rpm = rpmcount * 60; // Convert frequency to RPM, note: this works for one interruption per full rotation.
Serial.print("RPM =\t"); // print the word "RPM and tabl.
Serial.print(rpm); // print the rpm value
Serial.print("\t Hz=\t"); // print the word "Hz".
Serial.println(rpmcount); // print revolutions per second or Hz. And print new line or enter.
rpmcount = 0; // Restart the RPM counter
lastmillis = millis(); // Update lastmillis
attachInterrupt(0, rpm_fan, FALLING); // enable interrupt
}
}
void rpm_fan() { // this code will be executed every time the interrupt 0 (pin2) gets low.
rpmcount++;
}
/*
* Main program loop, runs over and over repeatedly
*/
void loop() {
if(stringComplete) {
// Serial.println(inputString);
if(inputString.equals("{open_valve}\n")) {
// Serial.println("opening valve.");
open_valve();
getFlow();
}
if(inputString.equals("{close_valve}\n")) {
// Serial.println("close vavle.");
close_valve();
}
// clear the string:
inputString = "";
stringComplete = false;
}
}
/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
while(Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
// Serial.println(inputString.length());
}
}
The following code changes seem to be printing the RPM and Hz values now.
// flow_A LED
int led = 4;
// relay_A
const int RELAY_A = A0;
// variables from sketch example
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
// FLOWMETER SHIT
// flowmeter 0 pulse (input) = digital pin 2
// https://github.com/Kegbot/kegboard/blob/master/arduino/kegboard/kegboard_config.h
// which pin to use for reading the sensor? kegboard-mini shield has digital pin 2 allocated
# define FLOWSENSORPIN 2
int rpmcount = 0;
int rpm = 0;
unsigned long lastmillis = 0;
void setup() {
// initialize serial
Serial.begin(9600); // open serial port, sets data rate to 115200bps
inputString.reserve(200);
pinMode(RELAY_A, OUTPUT);
// flowmeter shit
pinMode(FLOWSENSORPIN, INPUT);
digitalWrite(FLOWSENSORPIN, HIGH); // Need to set these HIGH so they won't just tick away
attachInterrupt(0, rpm_fan, FALLING); // interrupt is attached, is on pin two(2).
}
void open_valve() {
digitalWrite(RELAY_A, HIGH); // turn RELAY_A on
// Serial.println("Valve Open");
Serial.write("{valve_open}");
}
void close_valve() {
digitalWrite(RELAY_A, LOW); // turn RELAY_A off
// Serial.println("Vavle Closed");
Serial.write("{valve_close}");
}
void flow_A_blink() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for one second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
void flow_A_blink_stop() {
digitalWrite(led, LOW);
}
// flowmeter shit
void getFlow() {
// Serial.println("reached getFlow function");
if(millis() - lastmillis >= 1000) { // Update every one second, this will be equal to reading frequency (Hz). Using >= should be safter
// Serial.println("reached inside if statement");
detachInterrupt(0); // Disable interrupt when calculating
rpm = rpmcount * 60; // Convert frequency to RPM, note: this works for one interruption per full rotation.
Serial.print("RPM =\t"); // print the word "RPM and tabl.
Serial.print(rpm); // print the rpm value
Serial.print("\t Hz=\t"); // print the word "Hz".
Serial.println(rpmcount); // print revolutions per second or Hz. And print new line or enter.
rpmcount = 0; // Restart the RPM counter
lastmillis = millis(); // Update lastmillis
attachInterrupt(0, rpm_fan, FALLING); // enable interrupt
}
}
void rpm_fan() { // this code will be executed every time the interrupt 0 (pin2) gets low.
rpmcount++;
}
/*
* Main program loop, runs over and over repeatedly
*/
void loop() {
if(stringComplete) {
// Serial.println(inputString);
if(inputString.equals("{open_valve}\n")) {
// Serial.println("opening valve.");
open_valve();
}
if(inputString.equals("{close_valve}\n")) {
// Serial.println("close vavle.");
close_valve();
}
// clear the string:
inputString = "";
stringComplete = false;
}
getFlow();
}
/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
while(Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inChar == '\n') {
stringComplete = true;
}
// Serial.println(inputString.length());
}
}