Serial.Available not working on Arduino nano - arduino

I have a serial application that runs from a nano into a current loop driver.
Now if I connect the Tx straight to the Rx the led is set to HIGH but if I link the Tx/Rx to the current loop board the LED isnt set at all. I have even added a serial to usb monitor to confirm that the current loop board is returning the same hex as is being passed. Any suggestions?
int timeout = 0;
void setup() {
// put your setup code here, to run once:
pinMode(13, OUTPUT);
Serial.begin(4800,SERIAL_8E1);
//Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
//delay(10000);
byte inByte1 = 0xF1;
byte inByte2 = 0x10;
byte inByte3 = 0xB0;
//if(timeout == 0)
//{
Serial.write(inByte1);
Serial.write(inByte2);
Serial.write(inByte3);
//}
//timeout = timeout+1;
//if(timeout == 50)
//{
// timeout=0;
//}
//delay(80);
byte inByte4 = 0xE1;
//Serial.println(Serial.available());
while (!Serial.available()) {
//timeout =0;
//byte inChar = Serial.read();
//Serial.println(inChar);
//digitalWrite(13, HIGH);
//if(inChar == inByte4)
//{
// digitalWrite(13, HIGH);
//}
Serial.write(inByte1);
Serial.write(inByte2);
Serial.write(inByte3);
delay(80);
}
while (Serial.available()) {
//timeout =0;
//byte inChar = Serial.read();
//Serial.println(inChar);
digitalWrite(13, HIGH);
//if(inChar == inByte4)
//{
// digitalWrite(13, HIGH);
//}
}
}
String ReadResult(Stream &serial)
{
int serialState = 0;
String content = "";
char character;
long interval = 10000;
//unsigned int timeout = 0;
unsigned long currentMillis = millis();
long previousMillis = millis();
while ( !serial.available() && serialState != 1) {
currentMillis = millis();
if(currentMillis - previousMillis > interval){
serialState = 1;
}
}
//timeout = 0;
//while (serial.available()) {
// character = serial.read();
// content += character;
//}
return content;
};

The driver that I was feeding to was not returning thecorrect voltage

Related

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

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();
}

Implementing the function interrupt with if statements

I want to implement the function interrupt () but I don't know exactly how..In this case there is 2 for loops which can be seen in the code:I want whenever one of the 2 buttons is pressed the process inside the loop to be interrupted immediately:
void loop() {
int brightButton = digitalRead(K1);
int ldrStatus = analogRead(ldrPin);
if (brightButton == LOW && ldrStatus >= 200)
{
for (int i = 0; i < 10; i++)
{
digitalWrite(greenLed, HIGH);
tone(buzzer,400);
delay(500);
noTone(buzzer);
delay(500);
}
}
else {
digitalWrite(greenLed, LOW);
}
int tempButton = digitalRead(K2);
int valNTC = analogRead(NTC);
if (tempButton == LOW && valNTC > 512)
{
for (int i = 0; i <10; i++)
{
digitalWrite(redLed, HIGH);
tone(buzzer,450);
delay(300);
noTone(buzzer);
delay(1000);
}
}
else {
digitalWrite(redLed, LOW);
}
}
Example code from the Arduino manual:
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}
void loop() {
digitalWrite(ledPin, state);
}
void blink() {
state = !state;
}
Note that this will interrupt the for loop and return to it once the interrupt service routine is finished.
If you want to abort the for loop check the pin state in every loop cycle and break if you want to leave the for loop or return if you want to leave loop().
Of course this is not "immediately".

Three Xbee synchronization blinking

I'm doing synchronization blinking with three XBee module and Arduino Uno,
the first is master, second is slave/master and the other one is a slave.
The master is going to give the command for both slave/master and slave to blinking, and when the master is switch off, the slave/master will taking over his job giving the command to blinking.
But the slave/master didn't go so well because of the coding didn't right.
Can anyone take a look at my coding and show me what is wrong with my coding.
Master Coding =
#include <SoftwareSerial.h>
#define Dout 2
#define Din 3
//#define LED 9
SoftwareSerial XBee(Dout, Din);
//char XBee_message;
int MasterSignalSent = 0;
const long interval = 2500;
unsigned long previousMillis = 0;
void setup() {
Serial.begin(9600);
XBee.begin(9600);
pinMode(13, OUTPUT);
}
void loop(){
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
Serial.println(currentMillis);
previousMillis = currentMillis;
{
delay(1500);
SendMasterSignal();//+
MasterSignalSent = 1;
delay(1000);
SendSyncSignal();//-
BlinkLed();
MasterSignalSent = 0;
}
}
}
void SendMasterSignal()
{
Serial.println("SendingMasterSignal. . .");
XBee.write('+');
}
void SendSyncSignal()
{
Serial.println("SendingSyncSignal. . .");
XBee.write('-');
}
void BlinkLed()
{
digitalWrite(13, HIGH);
delay(250);
digitalWrite(13, LOW);
//delay(2200);
}
Slave/Master Coding =
#include <SoftwareSerial.h>
#define Dout 2
#define Din 3
SoftwareSerial XBee (Dout, Din);
const long interval = 2500;
unsigned long previousMillis = 0;
int MasterSignalReceived = 0;
int ReceiveSyncSignal = 0;
int MasterSignalSent = 0;
char XBee_signal;
void setup() {
Serial.begin(9600);
XBee.begin(9600);
pinMode(13, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
while(XBee.available()){
XBee_signal = XBee.read();
Serial.println(XBee_signal);
delay(1500);
if (MasterSignalReceived == 0)
{
BecomeMaster();
}
else if (MasterSignalReceived == 1)
{
if (XBee_signal = '-'){
BlinkLed();
(MasterSignalReceived = 0);
}
else{
digitalWrite(13, LOW);
}
}
}
}
}
void BecomeMaster()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
Serial.println(currentMillis);
previousMillis = currentMillis;
{
delay(1500);
SendMasterSignal();
MasterSignalSent = 1;
delay(2500);
SendSyncSignal();
BlinkLed();
MasterSignalSent = 0;
}
}
}
void SendMasterSignal()
{
XBee.write('+');
Serial.println("SendMasterSignalDone");
}
void SendSyncSignal()
{
XBee.write('-');
Serial.println("SendSyncSignalDone");
}
void BlinkLed()
{
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
}
The slave is waiting for the command to blinking but the slave/master didn't send any command as the coding write when the master switches off.

Problem with interruptions in Arduino Uno

I work with interruptions in Arduino UNO. In this project, I want to when the Door is opened the LED blink 10 times, and when the door is closed again, stop blinking the LED and exit the function. But in this code the LED only turn on and off once and it does not flash again.
My other problem is that, when the door is opened or closed, sometimes the opened or closed word appears several times in the Series monitor.
const byte LED_Red = 13;
const byte DOOR_SENSOR = 2; // magnetic door sensor pin
volatile int SensorState = LOW; // 0 close - 1 open wwitch
void setup()
{
Serial.begin(9600);
pinMode(LED_Red, OUTPUT);
pinMode(DOOR_SENSOR, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(DOOR_SENSOR), DoAction, CHANGE);
}
void DoAction()
{
SensorState = digitalRead(DOOR_SENSOR);
if (SensorState == HIGH) {
Serial.println("Opened");
blinkLED(10, 500);
}
else {
Serial.println("Closed");
}
}
void blinkLED(int repeats, int time)
{
for (int i = 0; i < repeats; i++) {
if (SensorState == HIGH) {
digitalWrite(LED_Red, HIGH);
delay(time);
digitalWrite(LED_Red, LOW);
delay(time);
}
else
return;
}
}
void loop()
{
}
You can't simply put a delay() on an interrupt's function. You need to just set a flag when the door is opened and based on that start blinkLED inside the main loop.
I also recommend you to use millis() function for an unblocking delay inside blinkLED function (e.g when you want to stop blinking while the door is closed).
const byte LED_Red = 13;
const byte DOOR_SENSOR = 2; // magnetic door sensor pin
// flag to check door is opened
volatile bool isOpened = false;
//flag to check already blinked
volatile bool isBlinked = false;
void setup()
{
Serial.begin(9600);
pinMode(LED_Red, OUTPUT);
pinMode(DOOR_SENSOR, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(DOOR_SENSOR), DoAction, CHANGE);
}
void DoAction()
{
if (digitalRead(DOOR_SENSOR) == HIGH)
{
//Serial.println("Opened");
isOpened = true;
}
else
{
isOpened = false;
isBlinked = false;
//Serial.println("Closed");
}
}
void blinkLED(int repeats, int time)
{
byte LEDState = LOW;
unsigned long delay_start = millis();
for (int i = 0; i < 2 * repeats; i++)
{
//Toggle LED state
if (LEDState == HIGH)
LEDState = LOW;
else
LEDState = HIGH;
// set value
digitalWrite(LED_Red, LEDState);
// some unblocking delay
while (millis() - delay_start < time)
{
// return if door is closed
if (!isOpened)
{
// turn off LED
digitalWrite(LED_Red, LOW);
return;
}
}
delay_start = millis();
}
isBlinked = true;
}
void loop()
{
// Check isBlinked beacue don't want to blink again until door is closed
if (isOpened && !isBlinked)
{
blinkLED(10, 500);
}
}

Openhab doesn't change the status of switch from manual overide

I have just made an account because of this particular problem I'm having with OpenHAB. I was following a tutorial from this https://openhardwarecoza.wordpress.com/2015/03/29/openhab-mqtt-arduino-and-esp8266-part-3-hardware-arduino-with-ethernet-shield/ site but since the reply there didn't help me. I decided to go to this site.
I have successfully installed OpenHAB and use it. When I turn the switch off and on from both the HTTP page and android device, It works just fine. But when I tried to manual override using a push button on an Arduino. It didn't update the state of the switch in both of them. I'm using windows with OpenHAB version 1.71
The Openhab server notices that there is an update of the state from the push button, but the button in the HTTP page and android device didn't change at all.
I have tested the connection using MQTTlens and it works just fine.
Below is my code
items configuration
Group All
Switch mqttsw1 "Switch 1" (all) {mqtt=">[mymosquitto:/arduino/l1/com:command:off:0],>[mymosquitto:/arduino/l1/com:command:on:1],<[mymosquitto:/arduino/l1/state:state:default]"}
Switch mqttsw2 "Switch 2" (all) {mqtt=">[mymosquitto:/arduino/l2/com:command:off:0],>[mymosquitto:/arduino/l2/com:command:on:1],<[mymosquitto:/arduino/l2/state:state:default]"}
Number temp "Temperature [%.1f °C]" <temperature> {mqtt="<[mymosquitto:/arduino/temp/state:state:default]"}
Number hum "Humidity [%.1f &#37]" <temperature> {mqtt="<[mymosquitto:/arduino/hum/state:state:default]"}
Sitemap configuration
sitemap dolphin label="Main Menu"
{
Frame label="Switch" {
Switch item=mqttsw1 label="Switch 1"
Switch item=mqttsw2 label="Switch 2"
}
Frame label="Weather" {
Text item=temp
Text item=hum
}
The Arduino Code
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <DHT.h>
const int butt1 = 3;// the pin that the pushbutton is attached to
const int butt2 = 2;
const int ledPin1 = 5;
const int ledPin2 = 4;
int ledState1 = HIGH;
int buttonState1;
int lastButtonState1 = LOW;
int ledState2 = HIGH;
int buttonState2;
int lastButtonState2 = LOW;
long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 60000; // READING INTERVAL
int t = 0; // TEMPERATURE VAR
int h = 0; // HUMIDITY VAR
#define DHTPIN 24 // SENSOR PIN
#define DHTTYPE DHT11 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xEF };
IPAddress ip(192, 168, 1, 103);
IPAddress server(192, 168, 1, 100);
void callback(char* topic, byte* payload, unsigned int length);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println();
Serial.println("Callback");
Serial.print("Topic = ");
Serial.println(topic);
Serial.print("Payload = ");
for (int i=0;i<length;i++){
Serial.print((char)payload[i]);
}
Serial.println();
if (strcmp(topic,"/esp1/l1/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/state","1");
}
}
if (strcmp(topic,"/esp1/l2/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/state","1");
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
client.subscribe("/esp1/#");
client.publish("conn","Connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void push1() {
int reading1 = digitalRead(butt1);
buttonState1 = reading1;
if (buttonState1 == HIGH) {
ledState1 = !ledState1;
if (ledState1 < 1)
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/com","0");
client.publish("/esp1/l1/state","0");
}
else
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/com","1");
client.publish("/esp1/l1/state","1");
}
}
}
void push2() {
int reading2 = digitalRead(butt2);
buttonState2 = reading2;
if (buttonState2 == HIGH) {
ledState2 = !ledState2;
if (ledState2 < 1)
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/com","0");
client.publish("/esp1/l2/state","0");
}
else
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/com","1");
client.publish("/esp1/l2/state","1");
}
}
}
void temp() {
h = (int)dht.readHumidity();
t = (int)dht.readTemperature();
char temp[2];
char hum[3];
sprintf(hum, "%d", h);
sprintf(temp, "%d", t);
client.publish("/esp1/temp/state", temp);
client.publish("/esp1/hum/state", hum);
}
void setup() {
// put your setup code here, to run once:
pinMode(butt1, INPUT);
pinMode(butt2, INPUT);
// initialize the LED as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
Serial.begin(9600);
Ethernet.begin(mac, ip);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
pinMode(26, OUTPUT); // sets the digital pin as output
pinMode(22, OUTPUT); // sets the digital pin as output
digitalWrite(26, HIGH); // sets +5v for the sensor
digitalWrite(22, LOW); // sets gnd for the sensor
h = (int)dht.readHumidity();
t = (int) dht.readTemperature();
if (client.connect("arduinoClient")) {
client.publish("conn","Connected");
client.subscribe("/esp1/#");
}
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
currentMillis = millis();
if (currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
previousMillis = currentMillis;
temp();
}
int reading1 = digitalRead(butt1);
int reading2 = digitalRead(butt2);
if (reading1 != buttonState1) {
push1();
}
if (reading2 != buttonState2){
push2();
}
client.loop();
}
If there are anybody who can help me I would be very grateful. Thank you for your attention !
Best Regards,
Aldi
If I remember correctly you should post back a status of ON or OFF instead of 1 or 0.
Could you change your arduino code to publish back ON and OFF and test that?
e.g.
client.publish("/esp1/l1/state","ON");

Resources