texts: Talking to Eurotherm 2416 temperature controller over modbus rs232

texts:
I am trying to implement the modbus library written by smarmengol to read process values and to set new setpoints (e.g. temperature) on a Eurotherm controller. The Arduino sketch looks like this:

/**
 *  Modbus master example 2:
 *  The purpose of this example is to query several sets of data
 *  from an external Modbus slave device.
 *  The link media can be USB or RS232.
 *
 *  Recommended Modbus slave:
 *  diagslave http://www.modbusdriver.com/diagslave.html
 *
 *  In a Linux box, run
 *  "./diagslave /dev/ttyUSB0 -b 9600 -d 8 -s 1 -p none -m rtu -a 1"
 *  This is:
 *      serial port /dev/ttyUSB0 at 9600 baud 8N1
 *      RTU mode and address @1
 */

#include <ModbusRtu.h>
#include <SoftwareSerial>

SoftwareSerial mySerial (3,5);

uint16_t au16data[16]; //!< data array for modbus network sharing
uint8_t u8state; //!< machine state
uint8_t u8query; //!< pointer to message query

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus master(0); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram[2];

unsigned long u32wait;

void setup() {
  // telegram 0: read registers
  telegram[0].u8id = 1; // slave address
  telegram[0].u8fct = 3; // function code (this one is registers read)
  telegram[0].u16RegAdd = 1; // start address in slave
  telegram[0].u16CoilsNo = 1; // number of elements (coils or registers) to read
  telegram[0].au16reg = au16data; // pointer to a memory array in the Arduino

  // telegram 1: write a single register
  telegram[1].u8id = 1; // slave address
  telegram[1].u8fct = 6; // function code (this one is write a single register)
  telegram[1].u16RegAdd = 2; // start address in slave
  telegram[1].u16CoilsNo = 250; // (Setpoint) number of elements (coils or registers) to read
  telegram[1].au16reg = au16data+4; // pointer to a memory array in the Arduino

  Serial.begin(9600);
  master.begin( &mySerial, 9600); // baud-rate at 9600

  master.setTimeOut( 5000 ); // if there is no answer in 5000 ms,roll over
  u32wait = millis() + 1000;
  u8state = u8query = 0;
}

void loop() {
  switch( u8state ) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1:
    master.query( telegram[u8query] ); // send query (only once)
    u8state++;
    u8query++;
    if (u8query > 2) u8query = 0;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 1000;
    }
    break;
  }
   Serial.print(au16data[O]);

  au16data[4] = analogRead( 0 );

}

I can read process values with telegram[0] very well (temperature and/or setpoint), but I cannot change the setpoint with telegram[1]. If I run the code, it puts the current temperature to serial monitor but resets manually changed setpoints to zero. Where is the error? Should I write the value for the setpoint as HEX or DEC? What does the last command do actually?

Thank you!


texts: How to handle a ESP8266 webserver only to the access point?

texts:
I'm developing a application that needs to be somewhat secure, so to configure the parameters it handles a GPIO interrupt (from a button) to open a server, that lets you configure it. The problem is that it is configured to send an email, so it is connected to the wifi.

With this in mind, I need to detect the source of the connection so I can serve the html only to the access point connections.

Is it possible?


texts:
How can we get a timer interrupt at a specific time or date?
For example: I want to make a project with an Uno and I'm using sleep mode and the wake-up source is timer2, as per the ATMega328p datasheet.
I want to turn on an LED, for example every day at 3pm, and the chip is in sleep mode on other times of the day.
So, how can I set the timer?
I think I have to use CTC mode of timer2 and set the OCR amount but I'm not sure how to do it.
There's a project on (Link) this link on the Arduino site that is perfect for this project, but when I compile it, it gives me an error saying that it can't be compiled for the Uno.


texts: Can the 2nd MCU on the UNO R3 be used for keyboard emulation?

texts:
Following on from What's the 2nd ICSP header for in Arduino Uno R3? I was wondering how this could be hacked to our advantage.

For example, could that firmware be rewritten to have the UNO recognised as a mouse/keyboard input? Could this be done after the boot loader process and leave the uploading process in tact?

Given the limited IO, it seems it's functions might be limited. Plus I have no idea how much code is space is available.


texts: LCD write a line at bottom without lcd.setCursor and without deleting any char above already there?

texts:
lcd.cursor and lcd.noCursor won't work for what I want to use it for since it seemed to be "global" sort of speak and follow lcd.setCursor which I don't want it to but it is otherwise exactly what I want to be done; just to put a line at the very bottom and also remove the line whenever I want to but without removing the entire char above.

Just like lcd.cursor do but as said it won't work in the code since the line has to reside where it is even if lcd.setCursor is used elsewhere but then the cursor line follow to that other point which I don't want and such a controllable cursor that sits at the place even if lcd.setCursor is used elsewhere. But the char there first and then the line of vice versa doesn't matter just as long as there it a line. And I cant create custom chars with a line under them since its numbers from 0 - 9 and so many custom chars can't be made.

It's fully possible to write to the bottom row though and I thought it would be possible to do something with lcd.createChar by not no write anything at all at the bytes rows but the lowest one, but that surprisingly failed. This is what I tested:

byte line[8] = {

  B,
  B,
  B,
  B,
  B,
  B,
  B,
  B11111,
};

And that writes on the lowest row as expected, but strangely enough STILL deletes any char that is written above even if nothing should have been written there as I see it.

The test here put out pretty much garbage and pretty much delete the char written but something still remain but the line is written at top instead of bottom and I guess it all goes out of the normal bounds in the registry or something:

#include <LiquidCrystal.h>
LiquidCrystal lcd(40, 42, 28, 26, 24, 22);

byte line[1] = {

  B00000,
};

byte noline[1] = {

  B11111,
};

byte sure[8] = {   //It didn't like to use "square" as name by whatever the reason

  B00000,
  B00000,
  B01110,
  B01110,
  B01110,
  B01110,
  B00000,
  B00000,
};

void setup() {

  lcd.createChar(0, line);
  lcd.createChar(1, noline);
  lcd.createChar(2, sure);

  lcd.begin(20, 4);
  lcd:clear:
}

void loop() {

  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(2));
  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(1));
  delay(500);
  lcd.setCursor(0, 0);
  lcd.write(byte(0));

}

Any tips on how to do the same with create.Char or any other simple way? I mean the lcd.cursor and lcd.noCursor can do it, how do that do it then? It's an ordinary 20X4 LCD if that would matter.


texts: Why are commands executing on their own?

texts:
This is the program I have used. It's working fine. But I don't known why sometimes it operates on its own. It is used to control a welding machine (Arduino is isolated from earthing). When there is a little vibration the code executes a command. This is the code:

int a = 9;  //right actuator forward relay 1
int b = 12; //right actuator reverse relay 2 (orange 10)
int c = 10; //left actuator forward relay 4
int d = 11; //left actuator reverse relay 3
int x = 0;
int y = 0;
const int stepPin = 8; // HIGH =DOWN; LOW == UP
const int dirPin = 7;

void setup() {
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  pinMode(4, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  Serial.begin(9600);
  digitalWrite(b, HIGH);
  digitalWrite(d, HIGH);
  delay(2000);
  digitalWrite(b, LOW);
  digitalWrite(d, LOW);
  delay(1000);
  Serial.println("press the foot swtich"); // Serial Monitor for Debugging
}

void loop() {
  int Val = digitalRead(5); //   Actuator 1 Clamping
  int ValR = digitalRead(6);//   Actuator 2 Clamping
  int ValS = digitalRead(4);//Stepper Motor anticlockwise
  int ValM = digitalRead(2);//Stepper Motor Clockwise
  if (Val == LOW && x == 0  ) {
    Serial.print("Val000=");
    Serial.println(Val);
    digitalWrite(c, HIGH);
    delay(1750);
    digitalWrite(c, LOW);
    x = 1;
    Val = digitalRead(5);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (Val == LOW && x == 1  ) {
    digitalWrite(d, HIGH);
    digitalWrite(b, HIGH);
    delay(2000);
    digitalWrite(d, LOW);
    digitalWrite(b, LOW);
    x = 0;
    Val = digitalRead(5);
    Serial.println("fwd");
    y = 0;
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValR == LOW && y == 0 ) {
    digitalWrite(a, HIGH);
    delay(1350);
    digitalWrite(a, LOW);
    y = 1;
    ValR = digitalRead(6);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValR == LOW && y == 1 ) {
    digitalWrite(b, HIGH);
    delay(1200);
    digitalWrite(b, LOW);
    y = 0;
    ValR = digitalRead(6);
    Serial.println("fwd");
    Serial.print("Val=");
    Serial.println(Val);
    delay(500);
  }
  if (ValS == HIGH) {
    Serial.println(Val);
    Serial.println("up");
    digitalWrite(dirPin, HIGH);
    // Enables the motor to move in a particular direction
    // Makes 100 pulses for making half cycle rotation
    for (int x = 0; x < 100; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);
    }
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
  }
  if (ValM == LOW) {
    Serial.println("down");
    Serial.println(ValR);
    digitalWrite(dirPin, LOW);
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
    for (int x = 0; x < 100; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(1000);
    }
    // Enables the motor to move in a particular direction
    // Makes 200 pulses for making one full cycle rotation
  }
}


texts: MySQL Connector/Arduino issues - not connecting

texts:
So I was going to make a project with the MySQL Connector/Arduino; a temperature log. I started out by experimenting with the example code from the website linked above. Not once did I manage to actually connect to the server; the mysql_connect() function always returns false. After several hours of intense googling, innumerable irritated noises and more, I decided to ask here on Stack Exchange.

Here is my current code:

#include "SPI.h"
#include "Ethernet.h"
#include "sha1.h"
#include "mysql.h"

byte mac_addr[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x69, 0xAC };
byte ip_addr[] = { 192, 168, 10, 127 };
byte dns_addr[] = { 192, 168, 10, 1 };
byte gateway_addr[] = { 192, 168, 10, 1 };
byte netmask[] = { 255, 255, 255, 0 };
IPAddress server_addr(192, 168, 2, 100);

Connector my_conn; // The Connector/Arduino reference

char user[] = "";
char password[] = ""; //the credentials are correct in my code
char INSERT_SQL[] = "INSERT INTO test_arduino.hello VALUES ('Hello, MySQL!');";

void setup() {
  Serial.begin(115200);
  Ethernet.begin(mac_addr, ip_addr, dns_addr, gateway_addr, netmask);     //Yes, I know this is way more than necessary, but just to play it safe
  delay(1000);
  Serial.print("IP: ");
  Serial.println(Ethernet.localIP()); // debugging
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password)) //connect to database
  {
     delay(500);
     my_conn.cmd_query(INSERT_SQL);
     Serial.println("Query Success!");
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
}

Any help is greatly appreciated.

Rasmus

EDIT: Looks like I'm not even getting through to reaching the server and attempting to log in. I enabled the general query logs, yet I get nothing when trying to connect. Also, I can ping both the Arduino and the MySQL server from this computer. I guess that rules out a faulty shield and network setup.


texts: Read battery voltage from battery which is powering arduino

texts:
I have a 5V arduino pro micro. I want to power it with a 3.7V lipo.

Should I use a step up module to convert it to 5V?

I also want to measure the voltage of the battery.

How can I do this?

Because I read that the power source also the reference voltage is so I cant measure it with an analog pin right?

I also use a lipo charging module to charge the battery.

Thanks for helping!


texts: Fingerprint sensor Arduino IDE code errors (Arduino Uno)

texts:
This code is for a fingerprint sensor. I keep getting the "function definition is not allowed before '{' token" error on the Arduino IDE. Any further corrections would also be immensely appreciated.

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

void setup()
{
  Serial.begin(9600);
  while (!Serial);  // For Yun/Leo/Micro/Zero/...
  delay(100);
  Serial.println("fingertest");
  pinMode(12, OUTPUT);

  // set the data rate for the sensor serial port
  finger.begin(57600);

  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1) { delay(1); }

  finger.getTemplateCount();
  Serial.print("Sensor contains "); Serial.print(finger.templateCount); Serial.println(" templates");
  Serial.println("Waiting for valid finger...");
}

void loop()                     // run over and over again

{
  getFingerprintIDez();
  delay(50);            //don't ned to run this at full speed.
  digitalWrite(12, LOW);
}

uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      return p;
    default:
      Serial.println("Unknown error");
      return p;

  // OK success!

  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;

  // OK converted!
  p = finger.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
    Serial.println("Did not find a match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  // found a match!
  Serial.print("Found ID #"); Serial.print(finger.fingerID);
  Serial.print(" with confidence of "); Serial.println(finger.confidence);

  return finger.fingerID;
}

// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;

  // found a match!

  digitalWrite(12, HIGH);
  delay(3000);
  digitalWrite(12, LOW);

  Serial.print("Found ID #"); Serial.print(finger.fingerID);
  Serial.print(" with confidence of "); Serial.println(finger.confidence);
  return finger.fingerID;
}

Here is the circuit diagram-

This program works for products like- https://www.flyrobo.in/finger_print_sensor
.The wire connection is as follows- fingerprint sensor white wire - pin 3, yellow wire - pin 2, red wire - “+5v” , black wire - “GND” servo wire - pin 4

Any and all help is appreciated.


texts:
int i, j;
char data;
int flag=0;

void loop()
{
if(Serial.available() > 0){
    data  = Serial.read();
    flag=0;
  }

  if (data == 'd' && 'b') {
    digitalWrite(cONOF, HIGH);
  } else if (data == 't' && 'w') {
    digitalWrite(cONOF, LOW);
  }

  if (data == 'y' && 'w') {
    digitalWrite(start, HIGH);
    delay(2000);
    digitalWrite(start, LOW);
  }

  if (data == 'e' && 'r' && 'h' && 'i') {
    for (i=0;i<10;i++) {
      digitalWrite(horn, HIGH);
      delay(100);
      digitalWrite(horn, LOW);
      delay(100);
    }
    for (j=0;j<10;j++) {
      digitalWrite(horn, HIGH);
      delay(500);
      digitalWrite(horn, LOW);
      delay(500);
    }
    digitalWrite(horn, LOW);
  }

}

I want to read data from the USART where the messages have more than one character. I tried the code above but it doesn't work well. For example, I want to send the message 'db' to turn the output on, but just sending 'd' also turns it on, how do I fix this?


texts: What is the most efficient voltage divider for Arduino?

texts:
I need to make voltage divider, so I could read a battery voltage up to 14.4 V. Could I use very high resistance resistors for that, so the current would be very low (to not to discharge battery)?
On the Internet there are examples with 500 - 2000 ohm resistors, but could I use hundreds of thousands to reduce the current to minimum? Would Arduino's analog input still read the value?


texts: Dragino Lora shield for Arduino sensor use

texts:
I am new to arduino and lora technology and i have dragino lorashield for arduino Uno and dragino gateway. I have also MQ-3 gas sensor and I want to detect the alcohol value and to send it to the gateway using the lorashield after that the gateway should send the data to ThingSpeak platform.
Currently the code for my MQ-3 sensor is as below. I would like to ask you for some help as I dont know how to write the code for the dragino and to send it to the gateway. Thanks in advance!

void setup() {
 Serial.begin(9600);
}
void loop() {
 float sensor_volt;
 float RS_gas; // Get value of RS in a GAS
 float ratio; // Get ratio RS_GAS/RS_air
 int sensorValue = analogRead(A0);
 sensor_volt=(float)sensorValue/1024*5.0;
 RS_gas = (5.0-sensor_volt)/sensor_volt; // omit *RL
 /*-Replace the name "R0" with the value of R0 in the demo of First
Test -*/
 ratio = RS_gas/0.01; // ratio = RS/R0
 /*-------------------------------------------------------------------
----*/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 delay(1000);
}

The code is working fine when I am using only the arduino. How do I modify it to use lora and to send the data to the gateway?


texts:
Atmel studio 7 with Arduino Uno:
Just upgraded to Atmel studio 7 and my target platform is the Arduino Uno.

I can't get past the start procedure: Firstly on starting up I get Sequence contains no elements (first image below). Then after pressing enter and entering the the Sketch File and Arduino IDE Path fields, the Board and Device fields remain empty (second image below).

I'm unable to select or update any of these two fields (Board and Device) - any assistance is appreciated.


texts:
I am onto a project where a need more memory. I saw the 23LC1024 chips are very popular with the Arduino DUE.

A very helpful person told me he did some timing tests on the 23LC1024 and a page read/write of 32 bytes costs about 100 μs.

I am interested in real time audio manipulation application (using the Arduino Due's ADCs and DACs).

This time of 100μs per 32 bytes seems a lot for the application, though i am not sure.

Are there benchmarking tests of the Arduino DUE for the time it takes to read/write to its memory, so i can compare with this chip and decide what to do?


texts:
I would like to use a CNY70 with arduino that is not 5v but 3.3v powered. On the web there most tutorials use 5v and 200 + 10k resistors (e.g. here and here). So as far as I understand for 3.3v I would have to use lower ones.

Can someone explain how those 200 or 10k were calculated? How could I use CNY70 with 3.3v (if it's possible at all) ?


texts: What's the relation between arduino standard library and esp8266 library?

texts:
Can I only use the Arduino standard library, without touching any esp8266 related header files?

I tried to connect to WiFi , succeeded with ESP8266WiFi.h header, but failed with  Arduino library WiFi.h.

I follow this https://www.arduino.cc/en/Tutorial/ConnectWithWPA WiFi connecting tutorial but the board seems to reboot repeatly (I don't understand the error of course. I know nothing about hardware).

My board is ESP8266 V3 ESP-12N F NodeMcu Lua CP2102


texts: Counting the number of pulses in a second

texts:
For my speedometer application, I want to count the number of pulses occurring every second and convert it to speed. So for that, I need to count the number of pulses occurring at a given input pin for one second. This count is used to convert to speed. The count should go to zero and start over after every second. But I don't get how to set a limit of one second and start over every second. So far I have come up to this:

int count = 0;
float lasttime = 0;
float currenttime = 0;
const int speedpin = 52;

void setup()
{
    Serial.begin(115200);
    pinMode(speedpin, INPUT);
}

void loop()
{
    currenttime = millis();
    if (currenttime - lasttime <= 1000)
    {
        if (digitalRead(speedpin == HIGH))
        {
            count = count + 1;
        }
        else
        {
            count = count;
        }
    }
    else
    {
        count = 0;
    }
    Serial.println(count);
}


texts: Error in I2C Communication Between Arduino and Raspberry Pi

texts:
The code below sends data to Raspberry Pi every 20 millisecond. The code works fine but sometimes python throws an error. Why this is happening? Should I give more time between writeData?
Error:
> Traceback (most recent call last):   File "rpi-I2C.py", line 33, in
> <module>
> writeData("360")   File "rpi-I2C.py", line 12, in writeData
> bus.write_i2c_block_data(address,0x00,byteValue) OSError: [Errno 121] Remote I/O error

Python code:
import smbus
import time
# for RPI version 1, use bus = smbus.SMBus(0)
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

#http://www.raspberry-projects.com/pi/programming-in-python/i2c-programming-in-python/using-the-i2c-interface-2
def writeData(value):
    byteValue = StringToBytes(value)
    bus.write_i2c_block_data(address,0x00,byteValue)
    #first byte is 0=command byte.. just is.
    return -1

def StringToBytes(val):
        retVal = []
        for c in val:
                retVal.append(ord(c))
        return retVal

while True:
    print("sending test")
    writeData("left")
    time.sleep(0.02)

    #print('Sending OPEN-00-00');
    writeData("right")
    time.sleep(0.02)

    #print('Sending WIN-12-200');
    writeData("360")
    time.sleep(0.02)

Arduino code:
#include <Wire.h>
#define SLAVE_ADDRESS 0x04

volatile boolean receiveFlag = false;
char temp[32];
String command;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  // define callbacks for i2c communication
  Wire.onReceive(receiveEvent);
  Serial.begin(115200);
  Serial.println("Ready!");
}

void loop() {
  if (receiveFlag == true) {
    Serial.println(temp);
    receiveFlag = false;
  }
}

void receiveEvent(int howMany) {
  for (int i = 0; i < howMany; i++) {
    temp[i] = Wire.read();
    temp[i + 1] = '\0';  //add null after ea. char
  }

  //RPi first byte is cmd byte so shift everything to the left 1 pos so temp contains our string
  for (int i = 0; i < howMany; ++i)
    temp[i] = temp[i + 1];
    receiveFlag = true;
  }


texts:
Is it possible to let a led blink, for example 5 times with Arduino?
Should I use a For loop?
Something like this works within the setup loop, but it will run continuesly in the void loop. So my led keeps blinking.
  for (int i = 0; i <= 5; i++) {
    led HIGH
    delay(500);
    led LOW
    delay(500);
  }

Also the blink sequence has to be triggered, and have a reset after it is done.
The complete code is to big to share, but it runs a bit like the following:
There is a "bankValue", it is filled by a user, and counts back to zero.
If it's zero, then blink 5 times.
After the blink, the leds are off.
The sketch is waiting for a new user, who will fill the bankValue again and the ledblink should again be initiated.


texts: The SoftwareSerial library has a built-in Overflow function, but the Serial library does not.  Is there a simple way to check for a data buffer overflow on a hardware serial port?


texts: BLDC motor erroneous running with digital potentiometer

texts:
I am using this digital potentiometer http://www.farnell.com/datasheets/31917.pdf to control a BLDC motor with Arduino Mega. When I am running the below code, the motor runs at the lowest speed when I am setting i = 0 in forward() function.
const int CS = 10;
const int INC = 9;
const int UD = 8;

void setup() {
  pinMode(CS, OUTPUT);
  pinMode(INC, OUTPUT);
  pinMode(UD, OUTPUT);
  digitalWrite(CS, HIGH);
  digitalWrite(INC, HIGH);
  digitalWrite(UD, HIGH);
}

void forward() {
  for (int i = 0; i <= 100; i += 10) {
    setResistance(i);
    delay(10);
  }
}

void loop() {
  forward();
}

void setResistance(int percent) {
  digitalWrite(UD, LOW);
  digitalWrite(CS, LOW);
  for (int i = 0; i < 100; i++) {

    digitalWrite(INC, LOW);
    delayMicroseconds(1);
    digitalWrite(INC, HIGH);
    delayMicroseconds(1);
  }

  digitalWrite(UD, HIGH);
  for (int i = 0; i < percent; i++) {
    digitalWrite(INC, LOW);
    delayMicroseconds(1);
    digitalWrite(INC, HIGH);
    delayMicroseconds(1);
  }

  digitalWrite(CS, HIGH);
}

The problem is when I set the value of i in the forward() function to 70 or 80 the motor runs sometimes at a much faster speed but other times when I upload the code with the 70/80/any value other than 0, the motor doesn't move at all. When i is set to 0, the motor runs every time at a super slow speed but for other values it sometimes moves at a faster speed, other times it doesn't move at all.
I am not sure what is causing this issue. Please help.


texts: Problem with while loops while detecting frequency of a signal

texts:
I just started to use the unusual part of Arduino language (avr) like interrupts, accessing registers, etc in Arduino IDE. I wrote a program to calculate the frequency of a digital signal using external interrupts.

The following code is to calculate timeperiod of a digital signal, the output of the color sensor (TCS3200) which depends on the color filter choosen via S2 and S3 pins, as in the code. That is, color sensor produces 50% duty cycle square pulses of frequency dependent on the power of the light incident on it. So when sensor faces red color, output signal's frequency in red color mode (by setting S2, S3 pins) is more than the frequency in blue and green modes. Thus we can detect the likeliness of the color which it faces w.r.t  R,G,B.

When this code is uploaded in the Arduino, it failed to print the values as expected in the serial monitor i.e. its stuck in while loops. But when Serial.print(e) statement in the while loops are uncommented, it is able to print the required time periods. I am unable to figure out the problem here, which is making Arduino to be inside the while loop when no statements are in it.

// INT0 interupt is used i.e. digital pin 2
int ti=0,tim=0,e=0,S2=4,S3=5;

void Interruptinit() //initializing interrupt INT0
{
  cli();
  EICRA =  0x02; //Control register
  EIMSK =  0x01; //Mask register
  sei();
}

void setup()
{
  pinMode(2,INPUT);
  digitalWrite(2,HIGH); //enabling pull up register
  pinMode(S2,OUTPUT);
  pinMode(S3,OUTPUT);
  Interruptinit();
  Serial.begin(9600);
}

ISR(INT0_vect)
{
  tim=micros()-ti;
  ti=micros();
  e++;
}

void loop()
{
  digitalWrite(S2,0); digitalWrite(S3,0); //switching over red filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e) //waiting till interrupt is addressed 2 times
  ;
  Serial.print("red:");
  Serial.print(tim);

  digitalWrite(S2,0); digitalWrite(S3,1); //switching over blue filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e)
  ;
  Serial.print(" blue:");
  Serial.print(tim);

  digitalWrite(S2,1); digitalWrite(S3,1); //switching over green filtered photodiodes
  e=0;
  while(e<2)
  //Serial.print(e)
  ;
  Serial.print(" green:");
  Serial.println(tim);

}


texts: Wiring diagram for Arduino to prevent relay firing on reboot

texts:
I'm starting to explore using an Arduino to control a couple of switches programatically. I have read somewhere about relays firing during reboot due to floating inputs/outputs during the reboot phase.

What is the best way to ensure that a relay will not fire on a reboot?

Is there a simple wiring diagram to explain it? I am using an Arduino Uno and a Relay Module.

Any assistance would be greatly appreciated.


texts:
I'm trying to get Neo-6M module to work with Arduino Uno, but it just isn't transmitting any data. It is getting 3.3V.
I've tried measuring the Amps and I got zero, so I'm afraid that the module could be broken.

Neo-6M wiring:

Arduino wiring (power):

Arduino wiring (data):

Arduino code:

#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup()
{
  Serial.begin(9600);
  ss.begin(GPSBaud);

  Serial.println(F("DeviceExample.ino"));
  Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
  Serial.print(F("Testing TinyGPS++ library v. "));     Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
}

void loop()
{
  // This sketch displays information every time a new sentence is correctly encoded.
  while (ss.available() > 0)
    if (gps.encode(ss.read()))
      displayInfo();

  if (millis() > 5000 && gps.charsProcessed() < 10)
  {
    Serial.println(F("No GPS detected: check wiring."));
    while(true);
  }
}

void displayInfo()
{
  Serial.print(F("Location: "));
  if (gps.location.isValid())
  {
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.print(gps.location.lng(), 6);
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Date/Time: "));
  if (gps.date.isValid())
  {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid())
  {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.println();
}


texts: Thingspeak Library returns 0 using ESP8266 on Arduino

texts:
I have tried using the thingspeak-arduino library and tested some of the examples:

#include <WiFi.h>
#include <WiFiClient.h>
#include <SPI.h>
#include <ThingSpeak.h>
char ssid[] = "Benok4G";    //  your network SSID (name)
char pass[] = "password";   // your network password
WiFiClient  client;

unsigned long myChannelNumber = 344468;
const char * myReadAPIKey = "xxxxxxxxx";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  WiFi.begin(ssid, pass);
  ThingSpeak.begin(client);
}

void loop() {
  // put your main code here, to run repeatedly:
  float voltage = ThingSpeak.readFloatField(myChannelNumber, 1, myReadAPIKey);

  Serial.print("Latest voltage is: ");
  Serial.print(voltage);
  Serial.println("V");

  delay(30000);
}

When i run this code, I get this on the Serial Monitor.

Why is it 0.00? It's supposed to be 24.0

http://184.106.153.149/channels/344468/fields/1/last

Did I do something wrong? I am very frustrated because I've tried a lot of methods already just to fetch the data from ThingSpeak to my Arduino using ESP8266. I can send but when receiving I am really lost and confused.


texts: How do I interpret the esp8266 "boot mode" message?

texts:
Everytime the chips resets, we get the reason and the next boot mode.

ets Jan  8 2013,rst cause:XXX, boot mode:(YYY,ZZZ)

For XXX we can check the meaning here.

For YYY and ZZZ I am not sure but I know it has something to do with this. I think YYY stands for abc where a = MTDO, b = GPIO0 and c = GPIO.

For my ESP12E I am getting boot modes like boot mode:(1,7), thus after the reset, the code doesn't start again. It just "hangs there" forever.

I feel that it is starting the UART routine, because 1 = 001, meaning GPIO2 is at HIGH and the others are at LOW.

But maybe what I want, for it to start the setup() and loop() routines all over again is to activate the "SPI" by setting the MTDO pin to LOW and the other two to HIGH.

Can someone explain me better what are these 3 boot modes and how can I interpret the boot mode?


texts: Which board's bootloader is on the microcontroller?

texts: Currently I'm doing a project that needs an Atmega2560 standalone MCU. After I burned the bootloader with this method: http://www.gammon.com.au/bootloader . I set the Board as "Arduino/Genuino Mega or Mega 2560" and the Processor as "ATmega2560 (Mega 2560)". But, it just stuck at "uploading" and this message pop up: "avrdude: stk500v2_ReceiveMessage(): timeout". So, I'm guessing I'm choosing a wrong board. Is there a way to check which board to select in the Tool tab?


texts: digispark - 2 pin push button to iterate through an hashmap

texts:
I'm trying to create a project with my digispark where i can iterate through an hashmap, when i press the push button the digispark writes via digikeyboard the values from an hashmap. Each time i press the button it's supposed to write the first value, then i press the push button again and in the same line it cleans what was written in the first value and writes the second value and so on. when the last value is reached it goes again to the first value if the button is pressed.
Right now i'm trying to put the iterator to work preperlly, this is the code i have:

#include "DigiKeyboard.h"
#include "HashMap.h"

HashMap<String, String> hashMap;
int i = 0;

void setup() {
   //setup hashmap
  hashMap.put("key0","test0");
  hashMap.put("key1","test1");
  hashMap.put("key2","test2");
  hashMap.put("key3","test3");
  hashMap.put("key4","test4");

  DigiKeyboard.sendKeyStroke(0);
  pinMode(0, INPUT);
}
void loop() {
  int sensorValue = digitalRead(0);
      while(sensorValue ==1 and i < hashMap.count())
      {
        delay(100);
        DigiKeyboard.println( hashMap.valueAt(i));
        i++;
      }
}

when i plug the digispark it prints automatically the first and the second value ("test0" "test1") and every time i press the button i get nothing.

This is my configuration:
http://cdn.instructables.com/FZA/0UN8/HI3TXV8D/FZA0UN8HI3TXV8D.LARGE.jpg

Can anyone help me please?


texts:
when reading RFID(MIFARE) information using Arduino mega and display in serial monitor it works fine. But, when printing on 2004LCD only one information(Value) displays correctly. The other information Item Name display a decimal number. Could someone help on this?
 void Price(){
      block = 4;
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Authentication failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      status = mfrc522.MIFARE_Read(block, buffer1, &len);  // ***Note down buffer1 within the bracket
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Reading failedl: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
             //Display price information...
      for (uint8_t i = 0; i < 16; i++)
      {
        if (buffer1[i] != 32) // if buffer1[i] not equal to 32
        {
          Serial.write(buffer1[i]);  //Price
         //lcd.write(buffer1[i]);
          Value = buffer1[i];
          }
       }
      Serial.print("/=");
      Serial.println(" ");
      sscanf(buffer1,"%d",&Value);
      lcd.setCursor(0,1);
      lcd.println(Value);

     }
    //==========================================================
    void Item(){ //----- Get & Display Item information
        block = 1;
     status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Authentication failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      status = mfrc522.MIFARE_Read(block, buffer2, &len);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Reading failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      for (uint8_t i = 0; i < 16; i++) { //
         Serial.write(buffer2[i]);       // Display Item
         lcd.write(buffer2[i]);
         Item_Name=buffer2[i];
        }
        sscanf(buffer2,"%s",&Item_Name);
       //sprintf(buffer2,"%d",&Item_Name);
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print(Item_Name);// displays numbers instead of "Fresh Milk 1Lt
     }


texts:
I'm building a wireless QLab Go button based on an ESP8266-01. There is a web UI to connect to a wireless network and setup the IP address of the computer running QLab. When a button is pressed, the ESP is meant to send an OSC message to that computer.

In fact, this works. But only a few times. After, let's say pressing five times the button, the ESP becomes unresponsive. The blue LED flashes, but apparently the OSC message is not sent. Also, the webserver is unreachable.

Also remarkable: my FTDI232 doesn't always communicate with the serial monitor of the Arduino IDE... Any ideas on what might be wrong here?

#define FIRMWARE "v0.4.3"
#define VERBOSE
//#define LOAD_DEFAULTS

#define BUTTONPIN 2

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
#include <OSCMessage.h>

#include "globals.h"

void setup() {
  EEPROM.begin(128);

  #ifdef VERBOSE
    Serial.begin(9600);
    Serial.println("--------------------");
    Serial.println("QLab Spacebar Button");
    Serial.print("Firmware Version: ");
    Serial.println(FIRMWARE);
  #endif

  #ifdef LOAD_DEFAULTS
    #ifdef VERBOSE
      Serial.println("Load Default Settings:");
    #endif

    saveSettings();
    startHotSpot();
  #else
    // If we cant load settings from EEPROM, start the hotspot
    if (!loadSettings()) {
      startHotSpot();
    }
  #endif

  // Start hotspot if we're in standAlone mode otherwise we start the wifi
  if (standAlone == 1) {
    startHotSpot();
  } else {
    startWifi();
    allowHotSpot = 0; // Dont allow hotspot to run after this initial setup - must restart device to start it again
  }

  // Start WebServer
  startWebServer();

  // Start listening for UDP packets
  qUDP.begin(qlab_port);

  pinMode(BUTTONPIN, INPUT);
  attachInterrupt(BUTTONPIN, spacebar, RISING);
}

void loop() {
  webServer.handleClient();
}

void spacebar() {
  #ifdef VERBOSE
    Serial.println("Received a click -- will send OSC message now!");
  #endif
  OSCMessage msg("/go");
  qUDP.beginPacket(qlab_address,qlab_port);
  msg.send(qUDP);
  qUDP.endPacket();
  msg.empty();
  delay(500); //Safety measure: you can't press the spacebar twice
}

(Most of the other code is in other files, I think this is the only relevant part)

The wiring diagram for the ESP is as follows: (I don't know how to draw it so I'll just try to write it down...)

Gnd->Gnd
Tx -> Rx
Rx -> Tx
CH_PD -> 3.3v
Vcc -> 3.3v
GPIO2 -- 10k ohm resistor to 3.3v
      \_ Gnd (this is meant to be a button: pulled to Gnd when pressed)


texts:
here i am doing some project with the help of Arduino UNO with External EEPROM (24LC256),
 All i want to create table and wants to  store all  data into  24LC256 External EEPROM,there are many library for internal EEPROM to create table with limited data as per size of arduino EEPROM but i have huge data to store so have to use External eeprom to do, so  i can't find any proper library for doing that.!

can anyone tell me how to do that...

any suggestion..Please help me..

thanking you..


texts:
I am having some issues with a simple circuit. I would expect this circuit to light up this LED constantly when the Arduino is plugged in. I have the Blink tutorial sketch loaded, but I don't think that should matter with the pins I am using.

This is what I think I have going on: Arduino 5V Power --> BB power --> 100 Ohm resistor --> BB line 25 --> this LED --> BB line 30 --> BB Ground --> Arduino Ground

Please check out this picture for confirmation:

Thanks in advance for any help that you can provide!


texts: Arduino Nano not responding with yellow led blinking fast

texts:
Update: I started playing with a genuine Deumilanove and exactly same problem happened to it - d13 led blinking, but avrdude says stk500_recv(): programmer is not responding

I uploaded a largish sketch ~15kb to Arduino Nano v3.0 (clone) and that left the board in an unusable state. When connected to USB, a power LED goes on immediately and 1-2 seconds later the yellow "L" starts blinking really fast.
Here's the board I use, it's a cheap clone, but it worked really well before today.

Now, when I try to upload a new sketch I get an error:

avrdude: stk500_recv(): programmer is not responding

I tried making and ISP programmer out of genuine Duemilanove, using nano's ISP pins and tried following official instructions (didn't use any capacitors/resistors).
Either way when I click "Burn Bootloader" result is the same error:

avrdude: stk500_getsync(): not in sync: resp=0x15

I have connected "debug" leds to D7,8,9 and heartbeat fades in and out in idle, others stay dark.
When I click "Burn Bootloader" all leds go dark then it does few quick blinks on 7, then similar pattern for 8, and then heartbeat resumes. Sometimes this sequence is repeated twice.

I also tried editing preferences.txt to bypass bootloader, but that didn't help.

How do I restore this board or do a low level reset?
It seems to be in some failure mode, with pin 13 oscillating, but I don't know what that means.


texts:
I'm new to gyroscope and accelerometer and am working on my project to control servo with Arduino Uno R3 based on the reading from InvenSense MPU6050 6DOF gyroscope and accelerometer. I've found the a same sheet of code from different websites.

Website 1_http://www.projehocam.com/wp-content/uploads/mpu6050-2-servo.txt

Website 2_http://www.instructables.com/files/orig/FLY/GZAL/IDIN48PC/FLYGZALIDIN48PC.ino

And from this part of the code, I couldn't understand the servo.write part...

    #ifdef OUTPUT_READABLE_YAWPITCHROLL
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        Serial.print("ypr\t");
        Serial.print(ypr[0] * 180/M_PI);
        Serial.print("\t");
        Serial.print(ypr[1] * 180/M_PI);
        myservoY.write(int(ypr[1] * -180/M_PI)+90);   // Rotation around Y
        Serial.print("\t");
        Serial.println(ypr[2] * 180/M_PI);
        myservoX.write(int(ypr[2] * 180/M_PI)+90);   // Rotation around X
    #endif

Why is the operation (int(ypr[1] * -180/M_PI)+90) ??


texts: MAX7219 powered on via digital pin set to HIGH is not working good (I < 25mA)

texts:
I'm using 7-segment 8-digits MAX7219 eBuy module in my battery-supplied ATMega168P project to output some readings. MAX7219 in powerdown mode draws ~150uA (as stated in the datasheet) which is too much for me, because the rest of the circuit draws less than 1uA is sleep mode. So I decided to power off Vcc line for MAX7219 before entering sleep, and power it on just after wakeup.

Current draw for the software-dimmed display module is only 15..19 mA in my case, which is far less than 40mA pin maximum for ATMega168P, so I connect display Vcc line to one of digital pins and power it on at setup():

void setup()
{
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
}

However, display module works only 1..3 seconds after starting, then switches off. I checked display Vcc — 4.9V, but the display is off. (I turned off enterng to sleep mode for a while)

This display module doesn't have capacitors C3 and C4 between Vcc and GND (but there's a placeholder for it), recommended in some sources. I solder two capacitors of 100nF and 4,7uF in parallel. It helps only a little: after 1..2 seconds of normal working display shows only digit #0 and in much higher brightness than I set (see the photo).

I may only suggest my cheap multimeter is wrong and the display draws much more, but I dont know how to check it. Rset is 10k on this module, btw.

Why does it happen?
Is there a way to solve the issue without using a transistor / MOSFET / relay (I suppose it should obviously help).

EDIT: If the display is powered directly by controller Vcc it works correctly as expected. It's current draw is 15..20mA.


texts:
I am learning Arduino and pardon me if this is nooby. I am trying to make an LED glow when the tilt switch is tilted. The LED should not glow if the tilt is in normal position. The circuit and the code are in the attached image.

Based on my understanding of the code, I thought that when the tilt switch pin 5 is passed with HIGH signal from 5V the IF condition gets satisfied and tje LED on pin 13 would glow.

But it does not happen. The LED just glows before I tilt the tilt switch. Could you please clarify/correct my mistake. Thank you.

Attaching the code below as per suggestion

int ledPin = 13;
int switchPin = 5;

void setup() {
  pinMode(ledPin,OUTPUT);
  pinMode(switchPin,INPUT);
}

void loop() {
  Serial.begin(9600);
  if (digitalRead(switchPin) == HIGH) {
    digitalWrite(ledPin,HIGH);
    Serial.print("we are here");
  }
  if (digitalRead(switchPin) == LOW) {
    digitalWrite(ledPin,LOW);
    Serial.print("there");
  }
}


texts:
I currently have a project that uses a few Xbee S1 modules to report temperature measurements to a computer. I'm thinking about reworking the project to use the newer Arduino Uno WiFi R2 boards.

Is there an existing library that will allow me to create a mesh network for a number of Wifi R2's (about 20+)? I know there's a Mesh Library for the ESP8266 I'd be curious if I could either use this library or if one exits for the native board


texts:
I have ran across a couple of different event libraries that are available on the AVR and Andruino but I am not sure which one is the best option. What I would like to do is design my program in a event driven style but not sure how to go about this.

I have a project that I need to keep lightweight but also in this program I have several actions that can be happening at any given time i.e. Digital Inputs being triggered and I need to run code whenever these events happen.

I found the QP Framework that looked promising but I wanted to get some feedback from some others that might of used this type of library before and might be able to provide some examples and maybe some experiences.

Another site I found here and lists all sorts of different libs


texts: Serial Port not recognized by Arduino IDE

texts:
I’m attempting to connect with a Adafruit Huzzah Feather ESP8266 board. I’m running a 2018 mbp with Mojave. I loaded the Silabs driver (CP210) to connect with the onboard UART on Huzzah board. I got the Arduino IDE 1.8.8 installed and loaded the 2.5.0 ESP8266 library (I also tried library 2.4.2).

The serial port appears  in the IDE (SLAB_USBtoUART). It also appears when I run the /dev/tty.* command and in About this Mac. From the IDE when I try to Get Board Info. Nothing. I get the message “Native serial port, can’t obtain info”. Everything seems good, except nothing from the IDE. I pulled up CoolTerm, set it the port and hit the reset on the Huzzah. I see data after hitting reset.

I run the Huzzah board from a powered USB hub through one of the USB-C ports. Tried different combinations, no luck.

I have a very old WIn7 machine, loaded everything like on my mbp, there I can get board info. I would run the IDE on it, except the machine is sooo slow. I would very much like to get it working on my mac. It seems so close, but no cigar.


texts:
I have two files, the first file is a library that I use to handle push buttons and initialize it and the second is where I handle my code and change LED state when push button is pressed, but my code doesn't work, I'm using Atmega32A micro-controller.

my library code:

#ifndef ButtonLibrary
#define ButtonLibrary

#ifndef numberOfButtons
#define numberOfButtons 2
#endif

#ifndef bit_is_clear
#define bit_is_clear(sfr, bit)   (!(_SFR_BYTE(sfr) & _BV(bit)))
#endif

#include <avr/io.h>

char ButtonPressed(int buttonnumber, unsigned char pinofbutton, unsigned char portbit, int confidencelevel);
void initialize_button(int pinofbutton, unsigned char port, unsigned char datadirection);
void initialize_led(int pinofled, unsigned char port, unsigned char datadirection);
void change_led_state(int pinofled, unsigned char port);

char pressed[numberOfButtons];
int pressed_confidence_level[numberOfButtons];
int released_confidence_level[numberOfButtons];

void initialize_button(int pinofbutton, unsigned char port, unsigned char datadirection)
{
    datadirection &= ~(1 << pinofbutton);
    port |= 1 << pinofbutton;
}

void initialize_led(int pinofled, unsigned char port, unsigned char datadirection)
{
    datadirection |= 1 << pinofled;
    port &= ~(1 << pinofled);
}

void change_led_state(int pinofled, unsigned char port)
{
    port ^= (1 << pinofled);
}

char ButtonPressed(int buttonnumber, unsigned char pinofbutton, unsigned char portbit, int confidencelevel)
{
    if(bit_is_clear(pinofbutton, portbit))
    {
        pressed_confidence_level[buttonnumber] ++;
        released_confidence_level[buttonnumber] = 0;
        if(pressed_confidence_level[buttonnumber] > confidencelevel)
        {
            if(pressed[buttonnumber] ==0)
            {
                pressed[buttonnumber] = 1;
                return 1;
            }
            pressed_confidence_level[buttonnumber] = 0;
        }
    }
    //button isn't pressed
    else
    {
        released_confidence_level[buttonnumber] ++;
        pressed_confidence_level[buttonnumber] = 0;

        if(released_confidence_level[buttonnumber] > confidencelevel)
        {
            pressed[buttonnumber] = 0;
            released_confidence_level[buttonnumber] = 0;
        }
    }
    return 0;
}
#endif

my main code:

#define F_CPU 1000000UL

#include <stdio.h>
#include <stdlib.h>
#include <avr/io.h>
#include <util/delay.h>
#include "ButtonLibrary.h"

int main(void)
{
    initialize_button(PIND4, PORTD, DDRD);
    initialize_button(PIND3, PORTD, DDRD);
    initialize_led(PINC7, PORTC, DDRC);
    initialize_led(PINC6, PORTC, DDRC);

    while(1)
    {
        if(ButtonPressed(0, PIND, 3, 500) == 1)
        {
            change_led_state(PINC6, PORTC);
        }
        if(ButtonPressed(1, PIND, 4, 500) == 1)
        {
            change_led_state(PINC7, PORTC);
        }
    }
}

when I press the push button nothing happens, I think there is something wrong in my initialize functions or change_led_state function but I don't know it.


texts: Why map Arduino pins 2 and 3 to Rx and Tx instead of using the build in Rx and Tx pins?

texts:
In many examples I see the following:

#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

// set up a new serial object
SoftwareSerial mySerial (rxPin, txPin);

what is the benefit of mapping pins 2 and 3 like this? Why not just use the built in RX (pin 0) and TX (pin 1) pins? I'm using a standard Arduino Uno.


texts: Unable to make a really basic sketch work

texts:
I've been learning how to encapsulate my code within functions, and one of the examples I worked on is a simple INPUT_PULLUP button. When I upload the sketch from the arduino website everything works, so I know it's not a hardware issue. However, with the code below the button will just not go LOW.
I just don't see what the issue is, and I'm feeling really hopeless that I can't even get the simple thing done. I would be grateful for any advice.
int button_pin = 2;
int button_state = 0;

void setup() {
  Serial.begin(9600);
  pinMode(button_pin, INPUT_PULLUP);
}

void loop() {
  Button();
}

void Button() {
  // Read button(s)
  button_state = digitalRead(button_pin);
  if (button_state = LOW) {
    Serial.println(button_state);
  };
};


texts:
I am trying to use a class in .ino file. The code is:
  .ino file

#include <LED.h>

int Pin1 = 13;
int Pin2 = 12;
int Pin3 = 11;
LED led;
void setup() {
  pinMode(Pin1,OUTPUT);
  pinMode(Pin2,OUTPUT);
  pinMode(Pin3,OUTPUT);
  digitalWrite(Pin1,LOW);
  digitalWrite(Pin2,LOW);
  digitalWrite(Pin3,LOW);
}

void loop() {
  led.on(Pin1);
  delay(2);
  led.on(Pin2);
  delay(2);
  led.on(Pin3);
  delay(2);
}

.h file

#ifndef LED_h
#define LED_h

class LED{
public:
    void on(int);
    void off(int);
};

#endif

.cpp file

#include <stdio.h>
#include <Arduino.h>
#include "LED.h"

void LED::on(int PIN){
    digitalWrite(PIN,HIGH);
}

void LED::off(int PIN){
    digitalWrite(PIN,LOW);
}

Arduino compiler picks the object declaration error:

LEDC:6: error: 'LED' does not name a type
LEDC.ino: In function 'void loop()':
LEDC:17: error: 'led' was not declared in this scope

How should I declare objects in Arduino then?

The way that I am putting the files in folders is like the attached image:


texts:
I'm making a project for school where I'm using flex sensors and converting that into words on an LCD (similar to the signing glove if you're familiar with that).
I ran into a problem since the Arduino I'm using doesn't have enough pins for all of my flex sensors and my LCD monitor.

I'm considering getting another Arduino with more pins but I might not have time to order it since my project is due in a couple of days. I was thinking about connecting two arduinos but I'm not sure if that would work (first year coding/engineering student) Any other suggestions as to how I can create more pins?

Your input is greatly appreciated!

The Arduino I'm using is a sparkfun redboard (it only has 6 analog pins and a separate place to plug in the LCD monitor which I connected to where it says ISP f you look on the link you will see what I'm talking about SparkFun RedBoard - Programmed with Arduino).

I'm using four flex sensors

LCD:


texts: How to filter data of ultrasonic sensor using arduino

texts:
I am working on a project that uses ultrasonic HC-SR04 sensor to measure distance. I've connected the sensor to the Arduino Uno board, I am also using Arduino IDE to program the Arduino. The problem is that I am not getting stable readings, there is the presence of some noise in the readings. How should I filter out this noise.

Circuit connections are as follows:

Ultrasonic sensor | Arduino
VCC                 5V
GND                 GND
Trigger             12 (digital)
Echo                11 (digital)

I am using new ping to measure distance.


texts: How to implement setSyncProvider and verify it is working with PC

texts:
I'm trying to retrieve / synchronize time from PC using this Time lib function:

setSyncProvider( requestSync);  //set function to call when sync required

It sends ASCII BEL (07) character to PC, but I'm getting no response using Serial.available. What am I missing?

Do I have to run a specific app on the PC to get a response? The docs do not specify that.


texts: Using signal strength feature of nRF24L01 module

texts:
This is a walkie-talkie project and this circuit really worked, voice can be transmitted from one nRF module to another nRF. Additionally, I want to observe how well the signal strength is, by lighting up an LED.

They talked about a test.RPD function here in order to do that. But it is said that we can't use this with nRF24L01, but can use only with nRF24L01P (I don't know what is the difference).

  Test whether a signal (carrier or otherwise) greater than
  or equal to -64dBm is present on the channel. Valid only
  on nRF24L01P (+) hardware. On nRF24L01, use testCarrier().
  Useful to check for interference on the current channel and
  channel hopping strategies.
  @return true if signal => -64dBm, false if not
  */

Can't we use it in nRF24L01 really?

If I cannot use this how can I use the testCarrier function to light up an LED (as Bright, Low and Off) as mentioned in the quote?

If I can use this, what changes in the code should be done? (The member TmrhProjects talked about it a little)

He also hints to this code.

bool rpd = radio.testRPD();

while (radio.available()) {
  signalStrength = rpd + 1;
  radio.read, etc...
}

Should we write the above code in the RF24.h file or should we write it directly into the Arduino's main sketch?


texts: Use of two external power sources for a power cell - charger

texts:
I have a SparkFun Power Cell - LiPo Charger/Booster and want to use the external 5V charge capability. Now my question:

Can I directly hook up a DC jack (for a 5V power supply) and an inductive charging circuit to the external charge pins of the Sparkfun Power Cell LiPo Charger Module or should I use a slide switch so that either the power supply via the dc jack or the inductive charging module can power the Sparkfun Power Cell LiPo Charger? I prefer the first option, but I have concerns that the inductive charging module is damaged when for example the power supply is hooked up...

Have anybody experience with an similar setup?
Thank you in advance for your answers.


texts: AnalogRead too slow... Faster alternative?

texts:
For a program that I'm working on, I want to get an accurate reading from a noisy pressure sensor.  So, the idea that I have is to do a thousand AnalogRead commands on the same port very quickly and then average them.  The pressure readings become very precise, however, the program that I am running becomes very slow.  I need my program to be orders of magnitude faster.

I'm sure that there's a faster way to do AnalogRead commands, especially because I am requesting the same port over and over.  Maybe there's a way that I can take lower resolutions of readings and then average those?  I don't know.  Can anyone help me?  I am an amateur Arduino user looking to learn.

I have done a little bit of research on my own and had trouble finding concrete examples.


texts:
I am working with sensors on Arduino and would like to filter the sensor's output to a certain band of frequencies.

I found many examples online on how to implement simple digital low-pass filters in Arduino code, but not for band pass filters.

Is it even possible to achieve this in the scope of an Arduino program?
If anyone can share some tutorial for this, that would be much appreciated.


texts: L298N, HC-05 Simple Bluetooth remote car not running in Arduino

texts:
Arduino board type used in this session is Arduino Uno R3 DIP/SMD CH340

Below is the description of wiring and code in Arduino to assemble a Bluetooth RC car using android smartphone:

Tested the motor dc result both of wheel works (can spin forward and or backward). power direct from the battery.
Tested HC-05 bluetooth moduled. The phone can paired the bluetooth module.
Tested out1 out2 out3 and out4 on L298N using direct power from the battery the wheel spinning (forward and or backward).
The code for the Bluetooth rc simple car used below as described.

The car failed to move (forward, backward, turn left/right). how to make the motor dc and or the motor stepper works remotely. thank you

    #include
    SoftwareSerial mySerial(12, 13); // RX, TX
    #define m1 3
    #define m2 5
    #define m3 9
    #define m4 10

int data=0,kec=0;
boolean forward=true;

int fast[11]={0,80,100,120,140,160,180,200,220,240,255};

void setup()
{
  pinMode(m1,OUTPUT);
  pinMode(m2,OUTPUT);
  pinMode(m3,OUTPUT);
  pinMode(m4,OUTPUT);

  mySerial.begin(9600);
 }

void motorOut(unsigned char lpwm, unsigned char rpwm, boolean arrow){
   if(arrow==false){
      digitalWrite(m3,HIGH);
      digitalWrite(m1,LOW);
      analogWrite(m4,255-lpwm);
      analogWrite(m2,rpwm);
   }
   else{
     digitalWrite(m3,LOW);
     digitalWrite(m1,HIGH);
     analogWrite(m4,lpwm);
     analogWrite(m2,255-rpwm);
  }
}

void loop(){
  if(mySerial.available()>0){
    data=mySerial.read();
    if (data =='0') { kec=0;}
      else if (data =='1') { kec=1;}
        else if (data =='2') { kec=2;}
          else if (data =='3') { kec=3;}
            else if (data =='4') { kec=4;}
             else if (data =='5') { kec=5;}
              else if (data =='6') { kec=6;}
                else if (data =='7') { kec=7;}
                  else if (data =='8') { kec=8;}
                    else if (data =='9') { kec=9;}
                      else if (data =='q') {kec=10;}

  //S= Stop
 if (data == 'S')
 { motorOut(0,0,false); }

//F=Forward
if (data=='F')
{ motorOut(fast[kec],fast[kec],true); }

//I=turn right forward
if (data=='I')
{ motorOut(fast[kec],((fast[kec])/2),true);}

//G=turn left forward
if (data=='G')
{ motorOut(((fast[kec])/2),fast[kec],true); }

//R=turn right
if(data=='R')
{ motorOut(fast[kec],0,true); }

//L=turn left
if(data=='L')
{ motorOut(0,fast[kec],true); }

//B=back
if(data=='B')
{ motorOut(fast[kec],fast[kec],false); }

//H=turn left back
 if (data=='H')
   { motorOut(((fast[kec])/2),fast[kec],false); }

//turn right back
   if (data=='J')
    { motorOut(fast[kec],((fast[kec])/2),false); }
  }
}


texts:
I want to use a hall effect sensor with a timer (millis). The count should reset after 1 second and print out the given count.

const int Hallsensor=3;
int HallValue;
int LastHallValue;
int Hcount =0;
unsigned long timer = 0;
unsigned long start_time = 0;

void setup() {
  pinMode(Hallsensor, INPUT);
  Serial.begin(9600);
  counting = true;
  start_time = millis();
}

void loop() {
  LastHallValue = HallValue;
  timer = millis();
  if((timer - start_time) >= 1000) {
    HallValue = digitalRead(Hallsensor);
    if (HallValue == LOW and LastHallValue == HIGH) {
      Hcount++;
      Serial.println(Hcount);
    } else {
      if(counting == true) {
        Serial.print("Count is");
        Serial.println(Hcount);
        counting = false;
      }
    }
  }
}


texts:
I am trying to implement a web server in ESP8266 that will handle simple HTTP GET requests by initiating an operation (e.g. move a stepper motor to the requested position) and return a response when the operation is finished (i.e. when the motor has reached the target position). This may take a few seconds, but during that time  the main loop should run normally so that both the TCP stack can work and the stepper library can actually move the motor (it works in the background). This means I cannot wait for the operation to complete within the handler. I have to start the operation in the handler, return without sending back a response and when the operation is done (i can poll for that in the main loop) then send the response.

I have been looking at https://github.com/me-no-dev/ESPAsyncWebServer but I'm not sure if such a scenario is supported. Has anynone done anything similar? Is it even possible?

One solution I was thinking was to store the request in a global variable (or queue) before exiting the handler and use it when the operation finishes. But will the request survive outside of the handler? And is it even possible to send the response outside the handler?


texts: MemoryFree library showing Irregular Behaviour..!

texts:
I simply burned the code written below but it is showing me irregular behaviour.. as in output's last paragraph, free memory increases after a runtime allocation, how it is possible? The output is attached :

#include <MemoryFree.h>
String str="rajat";
int flag=0;
void setup()
{
  // put your setup code here, to run once:

  Serial.begin(9600); Serial.println(freeMemory(), DEC);  // print how much RAM is available.
  Serial.println("Lets Start");
}

void loop()
{
    Serial.println("");
    Serial.println("Rajat0");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat1");
    str=str+"rjt";
    Serial.println(str);
    Serial.println("Rajat2");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat3");
    Serial.println("");
      delay(1000);
}


texts: How can I make std::cout write to Serial?

texts:
I'm using an Arduino MKR WiFi 1010, a SAMD ARM Cortex M3 board. I rely on the standard library a lot, using things like std::vector<> and std::string. I also want to use std::cout. I've managed to do this on an UNO R3 using the ArduinoSTL library, but that library neither works nor is necessary on the MKR WiFi 1010, because it has all the standard library stuff built in to the platform.

However, on MKR WiFi 1010, I cannot get std::cout to produce any output. I'm guessing its not really hooked up to anything.

I want std::cout to write to Serial (which is aliased to SerialUSB which is of type Serial_).

Is there a way of making std::cout write to the Serial stream?


texts: Compiling source with Arduino.h with avr-g++

texts:
How should I include the Arduino libraries when I'm compiling from the the command line? I tried to do it like this:

avr-g++ -g -Os -Wall -mcall-prologues -mmcu=atmega328p -fno-exceptions -o blink.obj blink.cpp -L. -lutil -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" -I"D:\Projects\Arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores"

but it returns undefined reference to the function that I am trying to use.

Arduino version: 1.8.2


texts: Fried 2 MKR Wifi 1010 after plugging them to a solar panel

texts:
I fried 2 MKR Wifi 1010 after powering them using a solar panel.
Here is the diagram:

Both were working fine as long as I used the LiPo battery and/or my macbook (using USB) as power sources. They were correctly detected and I could upload sketches.
Once I plugged the Solar panel + Voltage regulator to the MicroUSB port of the arduino and waited for the solar panel to be selected as the power source by the board, then it would not be recognized by the IDE anymore.
First board is not recognized by MacOS and Arduino IDE. Double tap Reset button has no effect on the "L" LED that remains turned off.
Second board is recognized by MacOS (By looking at System Information > USB) but not by Arduino IDE. When it is powered up, CHRG blinks a few seconds, then "L" LED pulses indefinitely. Double tap Reset button just turns off the LED while the button is pressed, but goes back to pulsing on release.
The sensor connected to the I2C pins is able to deal with both 3.3V and 5V, so it should work when getting 5V from USB and 3.3V from battery.
What could have damaged these 2 boards ?
Edit:
The voltage regulator operates at DC 9V - 36V (not sure why it is also labelled as 24V/12V) and outputs 5.2V / 6A.
I measured the output voltage once when the sun was hitting the panel and it was 5.2V.
The full product description is available at https://www.jzk-jzk.com/products/24v-12v-to-5v-5a-power-buck-module-dc-dc-step-down-power-supply-converter-with-led


texts: Arduino Leonardo(Atmega32u4) - Detecting if USB is connected to a computer?

texts:
The closest thing I can find is if(Serial) but that only returns true if there's a serial port open.

The function I want, ideally, should:

Return true if plugged into a computer

Return false if plugged into a USB power bank

Return false if not plugged in at all(Running off of its own lithium cell)


texts: Can't read from DHT sensor when motor is running

texts:
I've been following this tutorial and I've run into some weird problems. When my motor starts running, I get "Failed to read from DHT sensor" on my serial window, meaning that readHumidity() and readTemperature() functions are returning NaNs.

This only happens while the motor is running. Once I stop the motor even momentarily, the DHT sensor starts working again.

Does anyone know why this is happening? I'm using a genuine UNO and a RHT03 sensor and some 5.9V motor (TD599839).

I've attached a diagram I made of my circuit in fritzing -


texts:
i'm trying to make a digital dice to play catan with, here's what i have so far

#include <LiquidCrystal.h>
#include <DFR_LCD_Keypad.h>

// this is factory config shield initialisation
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// initialise the keypad
DFR_LCD_Keypad keypad(A0, &lcd);
int lcd_key     = 0;
int abc_key_in;
int read_LCD_buttons;
int  diceOne;
int  diceTwo;
#define btnSELECT 4
int read_LCD_buttons()
{
  abc_key_in = analogRead(0);
if (abc_key_in < 790) return btnSELECT;}
const int button = 4;
const int BUTTON4LOW = 400;
const int BUTTON4HIGH = 650;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Press to dice");
  pinMode (A0, INPUT);
  i
}

void loop() {
  int reading =  analogRead (A0);

  lcd_key = read_LCD_buttons();

 if (reading<BUTTON4LOW && reading<BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

  if (diceOne + diceTwo == 7) {
    lcd.clear();
    lcd.setCursor(7, 0);
    lcd.print("7");
    lcd.setCursor(3, 1);
    lcd.print("The pirate");

      if (diceOne + diceTwo == 3,2,1,5,4,6) {
          lcd.clear();
          lcd.setCursor(7, 0);
          lcd.print("fish");
      }
      }
  }
}
}

and im running into a error code saying

Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"

demo_simple:15: error: 'int read_LCD_buttons()' redeclared as different kind of symbol
 int read_LCD_buttons()
                      ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:11:5: note: previous declaration 'int read_LCD_buttons'
 int read_LCD_buttons;
     ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'int read_LCD_buttons()':
demo_simple:15: error: 'int read_LCD_buttons()' redeclared as different kind of symbol
 int read_LCD_buttons()
                      ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:11:5: note: previous declaration 'int read_LCD_buttons
 int read_LCD_buttons;
     ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void setup()':
demo_simple:28: error: 'i' was not declared in this scope
   i
   ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void loop()':
demo_simple:34: error: 'read_LCD_buttons' cannot be used as a function
   lcd_key = read_LCD_buttons();
                              ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: At global scope:
demo_simple:58: error: expected declaration before '}' token
 }
 ^
exit status 1
'int read_LCD_buttons()' redeclared as different kind of symbol


texts:
I am trying to create a bluetooth adapter which allows me to connect my keyboard + mouse via bluetooth and act as an HID device on my computer via USB. I want to be able to switch between operating systems, and use grub without having to use a wired keyboard (similar to the logitech unifying adapter)

Diagram:

Keyboard/mouse --BT--> Audrino --USB/HID--> Computer

I dont know the name of this type of device to search, but I have looked into bt hid proxy and have run into a dead end.

I have heard you can make this with a Arduino pro (I currently have an uno)


texts:
I'm building a control system for three sump pumps using a single Arduino and a set of relays.  I have float sensors for each one, and need the Arduino to trigger the relays when the float sensors are triggered.  Sensor 1 triggers pump 1, sensor 2 triggers pump 2, etc.

Simple enough, but I also need each pump to remain on for 30 seconds after its float sensor returns to normal.  This throws me for a loop since I need the other pumps and sensors to function during this delay time.  I quickly found that the blocking delay() function is no longer feasible.

How can I trigger the relays, keep them on for 30 seconds after the sensors return to normal, but all the while still monitor and control the other sensors/relays?  Would a non-blocking timer solution work?  Would I have to delve into interrupts?


texts: Send text according to an ultrasonic measurement, on battery

texts:
I have this big bucket where I would like to install an arduino on the top of the bucket where it would calculate the % of the bucket being filled up with water. Then, every day at night the arduino will send a text message (via SIM card) to the server where it would collect data for that bucket.

As far as a beginner point of view, I can understand that I will need:

an Arduino Board
PING))) Ultrasonic Distance Sensor
Battery pack that would allow to run the board for a year?
and the Arduino GSM Shield (integrated antenna) OR the GSM/GPRS Module M10?

My question is:
What arduino board do I need for my setup?
How long will 2 large or 4 AA batteries lasts for receiving a value from the ultrasonic sensor once a day and sending that value to a server? The point of the instrument is to be as small as possible.


texts:
I thought I had the Millis() command sorted but i'm stumped on the one. Aim is to get 2 led's alternately dimming, they work great with delay(); of course....but i can't figure where i'm going wrong with Millis().
Please have a look and point out what i've got wrong.
Thanks
Doug

int LED3 = 5;
int LED4 = 6;

// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED3=0;
unsigned long previousMillisLED4=0;

int intervalLED3 = 500;
int intervalLED4 = 500;

void setup() {
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);

      digitalWrite(LED3,LOW);
      digitalWrite(LED4,LOW);

}

void loop() {
  //unsigned long currentMillis = millis();
      for(int P=0;P<6;P++){
        //if ((unsigned long)(currentMillis - previousMillisLED3) >= intervalLED3) {
            analogWrite(LED3, 127);
            analogWrite(LED4, 254);
        delay(500);
              //previousMillisLED3 = currentMillis;

      //if ((unsigned long)(currentMillis - previousMillisLED4) >= intervalLED4) {
            analogWrite(LED3, 254);
            analogWrite(LED4, 127);
       delay(500);
             //previousMillisLED4 = currentMillis;
      }
}

Sorry, problems inputting code, but its all there.
I realize that there are some closing brackets missing in the LOOP() section for millis but it is set for delay() to show that it works.


texts: one Arduino with RS485 and Ethernet shields: does this work?

texts:
I'm planning to wire a few Arduinos together via RS485, and have one of them act as a hub that collects information from the others and presents it via http on an Ethernet connection.

For instance an Aduino MKR with ETH shield and 485 shield. Can I expect these to work together? My worry is having 2 shields that potentially need lots of bandwidth, timing issues etc.


texts:
I am working on a UAV and we are currently exploring inertial measurement units or IMUs. The two options that we have come across are:

Using an Arduino Uno and a 9 DOF IMU like this one
Using an ArduIMU chip like this one

Ignoring the cost aspect and assuming the same microprocessor on board, what would be the pros and cons of either of these approaches?

Keep in mind that performance is very important for a UAV controller as ESCs require 60 Hz or higher refresh rates for stable flight.


texts: Serial.read() keeps returning the same value over and over

texts:
This code keeps on returning 'S' with the Serial.read().

#include <Servo.h>
#define trig 10
#define echo 9
int pinMotorRN=3;
int pinMotorRP=4;
int pinMotorLN=5;
int pinMotorLP=6;
long distance;
long duration;
Servo myservo;
void setup() {
  pinMode(pinMotorRP, OUTPUT);
  pinMode(pinMotorRN, OUTPUT);
  pinMode(pinMotorLP, OUTPUT);
  pinMode(pinMotorLN, OUTPUT);
  Serial.begin(9600);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  myservo.attach(8);
}
void loop() {
  Lid();
  while(Serial.available() == 0);
  char val = Serial.read() ;//reads the signal
  delay(1);
  Serial.println(val);
  if(val == 'F'){
    Forward();
  }
  else if(val == 'B'){
    Backward();
  }
  else if(val == 'R'){
    Left();
  }
  else if(val == 'L'){
     Right();
  }
  else
    Stop();
}
void Stop()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, HIGH);
}
void Backward()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, LOW);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, LOW);
}
void Right()
{
  digitalWrite(pinMotorRP, HIGH);
  digitalWrite(pinMotorRN, LOW);
  digitalWrite(pinMotorLP, LOW);
  digitalWrite(pinMotorLN, HIGH);
}
void Left()
{
  digitalWrite(pinMotorRP, LOW);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, HIGH);
  digitalWrite(pinMotorLN, LOW);
}
void Forward()
{
  digitalWrite(pinMotorRP, LOW);
  digitalWrite(pinMotorRN, HIGH);
  digitalWrite(pinMotorLP, LOW);
  digitalWrite(pinMotorLN, HIGH);
}
void Lid(){
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  distance = duration*0.034/2;
  distance = 11;
  if(distance <= 10){
    myservo.write(180);
    delay(2000);
  }
  else
    myservo.write(0);
}


texts: Upload s sketch to a 5v Pro-Micro board as 3.3V by mistake

texts:
I have 2 types of Pro-Micro(as shown here), both 5v, micro-usb, which worked as expected, until, accidentally were flashed as 3.3v using the Arduino IDE.
At first I thought that the fact it stoped working right after, has nothing to do with that error, but since again, did the same mistake, I understand that this is no coincidence.
After doing so, boards seemed to be powered on ( leds are ON ), but are not found under port in the Arduino IDE.
Are they really can be destroyed by such an error ?


texts: Creating WebServer ip:port on esp8266 module

texts:
I creating Clever House with wifi. For this I'm using ESP8266 as module connected to Arduino. They communicate with SoftwareSerial. And there's a problem with global webserver on ESP8266. That I think to do it I must do this:

1.Create Webserver on another port(Neither 80 nor 443) Or Host will be in this model: https://ip:port/

2.Open port forwarding for port.

3.Almost done.

So how can I do it with AT commands?


texts: Is it possible to digitally stop a moving motorbike using an Arduino module?

texts:
I am working on a bike protection project that is supposed to be part of my CS syllabus. Although I got most of the things worked out, there is one thing that bugs me; that is to how to stop a moving bike using an Arduino built into the bike, possibly from a remote system, like another Arduino or Android app.

Is it possible to do it using an Arduino and some other modules maybe?


texts: How to connect 5V sensors to 3.3V digital input (Due)?

texts:
I'm completely new with Arduino and microcontrollers in general.

I have several 5V sensors, and need 3.3V because that's the max for the Due. Is it possible to use a resistor to connect it to the Arduino? Do I have to measure the current from the sensor and calculate the needed resistor like this?

$$\frac{5.0 - 3.3}{\text{Measured current}}$$
(5.0 - 3.3)/(Measured current)


texts: How many modules can an Arduino Nano v3 support (in code)?

texts:
I'm planning to use an Arduino Nano v3 for a simple project plus some devices like capacitive touch buttons, an LCD display and a Bluetooth module on an I²C. Will these devices require (like classes or function in programming) that might take up the entirety of the 30KB space?

Devices:
HC-SR04 Distance Sensor
TTP229 Capacitive touch sensor
LCD1602+HD44780 LCD Display
HC-06 Bluetooth module


texts: CIPSEND Shows 404 error using aeduino + esp8266+01

texts:
I am trying  to save data in the data base with the get method. my url works fine when used with browser but when tried with esp shows page not found expection.
Arduino Code

SoftwareSerial ESP8266(10, 11); // Rx,  Tx

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);

  ESP8266.println("AT+RST");
  delay(1000);
  ESP8266.print("AT+CWQAP\r\n");
  delay(2000);
  unsigned char check_connection=0;
  unsigned char times_check=0;
  Serial.println("Connecting to Wifi");

  while(check_connection==0)
  {
    Serial.print(".");
  ESP8266.print("AT+CWJAP=\"********\",\"*******\"\r\n");
  ESP8266.setTimeout(5000);
 if(ESP8266.find("WIFI CONNECTED\r\n")==1)
 {
 Serial.println("WIFI CONNECTED");
 break;
 }
 times_check++;
 if(times_check>3)
 {
  times_check=0;
   Serial.println("Trying to Reconnect..");
  }
  }
  delay(5000);
}

void loop() {

  // put your main code here, to run repeatedly:
   String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += "homeautomationinternal.xyz"; // api.thingspeak.com
  cmd += "\",80";
  ESP8266.println(cmd);
  if(ESP8266.find("Error")){
    Serial.println("AT+CIPSTART error");
    return;
  }
  String getStr = "GET /auto/addlightvalueuseruno?userid=aravind";
  //getStr += String(temp_f);
  getStr +="&";
  getStr +="value=1";
  //getStr += String(humidity);
  getStr +=" HTTP/1.1\r\nHost: homeautomationinternal.xyz";
  getStr += "\r\n\r\n";
  // send data length
  cmd = "AT+CIPSEND=";
  cmd += String(getStr.length());
  ESP8266.println(cmd);
  ESP8266.setTimeout(2000);
  if(ESP8266.find(">")){
    ESP8266.print(getStr);
   Serial.println(cmd);
  }
  else{
    ESP8266.println("AT+CIPCLOSE");
    // alert user
    Serial.println("AT+CIPCLOSE");
  }
   Serial.println(getStr);
  delay(5000);

}```

and the serial monitor data is

```AT+CIPSTART="TCP","www.homeautomationinternal.xyz",80

CONNECT

OK
 AT+CIPSEND=98

OK
>
busy s...

Recv 98 bytes

SEND OK

+IPD,1245:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>404 - File or directory not found.</title>

Server Error

<fieldset>

404 - File or directory not found.

The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

 </fieldset>

CLOSED

my website runs on iis server..

please help me with the arduino code and error which I am getting in the serial.monitor and how to resolve it.


texts: Recommendations For High Capacity Microcontrollers

texts: For a new project I'm working on, I'm turning an old Casio Personal Mini into a Speak & Spell (with possibly other functions). However, the speech library I plan on using is Talkie, and it takes up quite a bit of program space. I've been trying to look around for some microcontrollers I could use that have high program storage capacity, but I really don't know much about what I should look for, nor how to find ones that are compatible with the Arduino boot loader. Would any of you have any good suggestions? I'd probably need one with over 256KB of program storage.


texts: What is the Proper Voltage to supply an enough Current to the Arduino

texts:
I'm just confused about the supply that I should use in driving my arduino. Is it okay to use a 3.7V with a 1000mAh to supply it?

I will be using a Lilypad Arduino.

Your replies would be a big help to me.

Cheers!


texts: card.init(SPI_FULL_SPEED,SD_CS_PIN) returns false for Arduino Mega

texts:
I am working with a music shield, I have got my code from this site https://www.waveshare.com/Music-Shield.htm it works fine with arduino UNO but when I try to use it on MEGA it give me errors, Well I found that the problem is with this line

card.init(SPI_FULL_SPEED,SD_CS_PIN)

in uno SD_CS_PIN=10 I tried to change it to 53 based on this map

SPI   Uno   Mega
SS   10   53
MOSI   11   51
MISO   12   50
SCK   13   52

which is available on https://forum.arduino.cc/index.php?topic=165170.30 but still it returns false. What other options do I have to make it work on MEGA?

Thing that I am trying

#define SD_CS_PIN=10
#define VS_XRESET A0
#define VS_DREQ   A1
#define VS_XDCS   A2
#define VS_XCS    A3
void VS10XX::init(void)
{
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  pinMode(53, OUTPUT);

  pinMode(VS_XRESET, OUTPUT);
  pinMode(VS_DREQ, INPUT);
  pinMode(VS_XDCS, OUTPUT);
  pinMode(VS_XCS, OUTPUT);
  digitalWrite(VS_XDCS, HIGH);
  digitalWrite(VS_XCS, HIGH);

  reset();
}

In setup I added used this code but still does not work

void setup()
{
  Serial.begin(115200);
  pinMode(53, OUTPUT);//setting pin 53 to input
  player.begin();
}

the error code when I attempt to init sd card is 0 which says

/** timeout error for command CMD0 */


texts: What features of the Arduino framework will fail if I use my own infinite loop in favor of the standard loop()?

texts:
I have a strong urge to replace the framework-provided loop() function with my own like so:

__attribute__((always_inline)) inline void fastLoop()
{
}

void setup()
{
   // Performing setup here...
   Serial.begin(115200);

   // Now looping
   for(;;)
      fastLoop();
}

This way, my loop is inlined and I'm saving quite a few cycles - avoiding not only Arduino housekeeping costs, but also the function call cost which even for a void function has to be at least 6 cycles on AVR (>=2 for RCALL and 4 for RET).

This is the framework code for calling loop() from main():

for (;;) {
    loop();
    if (serialEventRun) serialEventRun();
}

My question is: what does this serialEvent stuff do? What features of the framework will stop working properly with my own loop?

Assuming my loop has observable side effects as required by the C++ standard, of course (otherwise it can be optimized out).


texts:
I have a push button wired to my Arduino but it seems to be triggering randomly.

I have one pin of the button connected to pin 2 on the arduino and the other connected to ground.

void setup() {
    Serial.begin(9600);

    pinMode(2, INPUT);
}

void loop() {
    Serial.println(digitalRead(2));
}

I expect it to print 1 continuously and go to 0 when I press the button down but sometimes it shows 0 even when I don't touch it.


texts: How to find a clear frequency when use SI4463

texts:
I use RH_RF24 to control SI4463, and success to send some simple data. But I know maybe there will be disturb . So, I want a way to avoid disturb.

First, whether there is a way that choose a best(clear) frequency in some range after scan all frequency in the range at beginning ? If have, what is the way ? If giving a detail example, it's really best.

Second, is there any simple and reliable way of frequency hopping ?  Because I want use it in my model airplane, I hope it is anti-interference. About frequency hopping, I really know nothing.

Thanks for any answer.


texts: Which sensor i can use to transmit some values from Arduino Uno to phone using bluetooth?

texts:
I want to transmit some values from arduino uno to my phone using bluetooth.
Which sensor i can use?I want to see some options because i'm a little bit uncertain.Thanks to all which can give me an advice !  :)


texts: Formula for current through shift register

texts:
Hi

I am programmer that just started learning electronics and Arduino. I built this simple circuit on Autodesk Circuits earlier. Originally I used 220 ohm resistors. Then when I ran the simulation and turned on more than 4 of the leds the simulator warned that I exceeded the max current for the shift register.

I then upgraded to 560 ohm resistors which solved the problem.

What I would like to know is how can I calculate the current through the shift register for each n-number of leds I turn on? That way I can calculate the right resistor that I need before I burn out my electronics.

Thanks for the help on this.


texts: Help with simple gradually brighter flickering led

texts:
im a newcomer for arduino and sorry for any grammar error.
So what im trying to do is replicating a flickering effect found on spacecraft thruster when they about to take off where the fire bursting from dim to bright with flickering,similiar to afterburner on aircraft model which use neopixel led but this time only using common led.
I could mimic the flickering on the led with various  brightness level using the simple analogWrite,the problem is i cant really merge them since i use delay which is affecting how fast the flickering effect is and i need 1 sequence of flickering to stay a while before going next to brighter flickering and so on.
My code is quite too simple

    Int led = 9;
    void setup () {
    pinMode (led, OUTPUT);
    }

    void loop() {
    {analogWrite (led, random (10,15));
    delay (30);}

    }

Im thinking adding a new line with higher random led states (ex. 50,100) should be okay,but then the delay which affect the flickering speed are too short and making both line merging useless since its will go to the brightest in no time.
Is there's any way to hold the first dim line for an amount of time then continue to the next brighter line and so on without affecting the filckering delay?
Any help will be appreciated

Thank you!


texts:
I had an Arduino UNO (ATmega168) standalone working, but I need more pins, and I decided to use the ATmega2560, I was searching for some schematics, and none of them shown an ATmega2560 standalone, only the full Arduino, with the FTDI, power transformers... etc integrated. So taking parts from those designs, I made this, but I don't know if it's enough or I need Something more:

Note: VCC2 is connected to 5V.


texts: I am using atmega 128 for a smart vehicle tracker. I am trying to use watchdog timer for this controller.But problem is that I have found the maximum watchdog reset time is 2 seconds. I need watchdog reset time 8 seconds. Now what can I do ?


texts: How to program ATmega4809 from Raspbeery GPIO

texts:
From this tutorial  I'm able to nicely program an ATmega328 using SPI raspberry GPIO pins. However, when I try the same steps with  ATmega4809, avrdude seems not having instructions and outputs the following:
program enable instruction not defined for part "ATmega4809"

So, how do I program ATmega4809 chip from Raspberry?


texts: error: 'analogRead' was not declared in this scope

texts:
I am using Codeblocks with arduino IDE to simulate the control of a stepper motor, and the errors "'analogRead' was not declared in this scope" and "'A0' was not declared in this scope" keep popping. The code follows:

#include <Stepper.h>

const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0;  // number of steps the motor has taken

void setup() {
}

void loop()
{
    int sensorReading = analogRead(A0); //ERROR

    int motorSpeed = map(sensorReading, 0, 1023, 0, 100);

    if (motorSpeed > 0)
    {
        myStepper.setSpeed(motorSpeed);
        myStepper.step(stepsPerRevolution / 100);
    }
}

EDIT: Sorry I forgot to mention it clear, but I do not own a board, that's why I'm trying to simulate it on PC.


texts:
I have LED Cube Project, and I want to activate the LED with My Android apps (Bluetooth). The LED Cube used A0-A5 and D0-D13 Pins, and the Bluetooth need RX and TX (D0, D1).

Where I can put the RX and TX (for Bluetooth HC-05) while D0, D1, and all analog and digital pins are used by the LED?


texts:
I have designed and 3d printed a clock.

I am controlling the clock using a Arduino sketch running on a Attiny2313. The stepper motor I am using is a 12v 1:12 ratio stepper. The total number of steps per revolution are 288.

The problem I am facing is that I am unable to get the time right. I have got the steps per revolution of the minute ring bang on, but some how the motor gains 10/11 minutes every 24 hours.

I have used a lot of the code from the stepper motor library. I am not using the stepper motor library as the code gets larger than what can fit into the 2k attiny memory.

Any help is appreciated.

int number_of_steps = 288;
int motor_pin_1 = 9;
int motor_pin_2 = 10;
int motor_pin_3 = 11;
int motor_pin_4 = 12;
int ledpin = 13;
int delayTime = 4;
int buttonPin = 4;
int buttonState = 0;
int enablepin = 8;
int whatspeed = 40;
int last_step_time =0;
int step_number = 0;
[color=red]int blinkDelay = 939; [/color]
int step_delay = 60L * 1000L / number_of_steps / whatspeed;
int step_direction = 0;
void setup() {

 pinMode(motor_pin_1, OUTPUT);
 pinMode(motor_pin_2, OUTPUT);
 pinMode(motor_pin_3, OUTPUT);
 pinMode(motor_pin_4, OUTPUT);
 pinMode(buttonPin,INPUT);
 pinMode(ledpin, OUTPUT);
 pinMode(enablepin,OUTPUT);

}

void loop() {
 buttonState = digitalRead(buttonPin);
 if (buttonState ==HIGH){
   enablemotor();
   movestep(20);
   digitalWrite(ledpin,HIGH);
 }
 else{
   digitalWrite(ledpin,LOW);

   for (int xx = 0; xx<59;xx ++){

     enablemotor();
     movestep(42);
     //delay(100);
     motoroff();
     blinkk();
   }
   enablemotor();
   movestep(89);//85;

   motoroff();
   blinkk();
  //delay(3000);
 }
}

void enablemotor(){
 digitalWrite(enablepin,HIGH);
}

void movestep(int steps_to_move){
 int steps_left = abs(steps_to_move);

 if (steps_to_move > 0) {
   step_direction = 1;
 }
 if (steps_to_move < 0) {
   step_direction = 0;
 }

 while(steps_left > 0) {
   // if (millis() - last_step_time >= step_delay ) {
   //last_step_time = millis();
   if ( step_direction == 1 ){
     step_number++;
     delay(step_delay);
     if (step_number == number_of_steps) {
       step_number = 0;
     }
   }
   else {
     if (step_number ==0){
       step_number = number_of_steps;
     }
     step_number--;
   }
   steps_left--;

   stepmotor(step_number % 4);

   //}
 }
}

void stepmotor(int thisStep){

 switch (thisStep) {
 case 0:    // 1010
   digitalWrite(motor_pin_1, HIGH);
   digitalWrite(motor_pin_2, LOW);
   digitalWrite(motor_pin_3, HIGH);
   digitalWrite(motor_pin_4, LOW);
   break;
 case 1:    // 0110
   digitalWrite(motor_pin_1, LOW);
   digitalWrite(motor_pin_2, HIGH);
   digitalWrite(motor_pin_3, HIGH);
   digitalWrite(motor_pin_4, LOW);
   break;
 case 2:    //0101
   digitalWrite(motor_pin_1, LOW);
   digitalWrite(motor_pin_2, HIGH);
   digitalWrite(motor_pin_3, LOW);
   digitalWrite(motor_pin_4, HIGH);
   break;
 case 3:    //1001
   digitalWrite(motor_pin_1, HIGH);
   digitalWrite(motor_pin_2, LOW);
   digitalWrite(motor_pin_3, LOW);
   digitalWrite(motor_pin_4, HIGH);
   break;
 }

}

void blinkk(){
 for (int i = 0 ; i<30;i++){
   buttonState = digitalRead(buttonPin);
   if (buttonState ==HIGH){
     break;
   }
   else{
     digitalWrite(ledpin, HIGH);   // set the LED on
     delay(blinkDelay);  // 968           // wait for a second
     digitalWrite(ledpin, LOW);    // set the LED off
     delay(blinkDelay); //968
   }
 }
}

void motoroff(){
 digitalWrite(enablepin,LOW);
 digitalWrite(motor_pin_1, LOW);
 digitalWrite(motor_pin_2, LOW);
 digitalWrite(motor_pin_3, LOW);
 digitalWrite(motor_pin_4, LOW);


texts: How to improve date-time control from RTC?

texts:
I want to run cameras at a remote site from external batteries as long as possible. I need power-miser Arduino to switch battery power on/off at set intervals (e.g. 5 min) during daytime only. I am a beginner with Arduino and electronics.

Have set up 'breadboard' arduino with mosfet module for switching the power supply and RTC module, both from Freetronics (http://www.freetronics.com.au/collections/modules/products/real-time-clock-rtc-module#.V-i-S8knuPs). Following their recommendation I'm using RTC library here: http://rweather.github.io/arduinolibs/index.html

I need to refine the crude hour-based script below. Weatherley library returns separate objects e.g date.day, time.hour etc. Is there a simple way to convert to date-time object? Then calculate sunrise and sunset times based on latitude?

  #include <JeeLib.h> //  power saving library
  ISR(WDT_vect) { Sleepy::watchdogEvent(); } // Setup jeelip watchdog
  #include <SoftI2C.h> // rweather lib for RTC module
  #include <DS3232RTC.h> //rweather lib for RTC module
  SoftI2C i2c(A4, A5); // assign pins to SDA and SCL
  DS3232RTC rtc(i2c);
  RTCTime time;
  int gatePin = 12;   //  mosfet Gate connected to digital pin
  int startHour = 6; // want to replace with sunrise time
  int endHour = 19; // want to replace with sunset time

void setup()
{
 pinMode(gatePin, OUTPUT);   //  output pin for mosfet module
}

void loop()
{ // main loop starts here
  rtc.readTime(&time);  //get current time
  if (time.hour >= startHour && time.hour < endHour) // check daytime
  {   // if condition begins here
      while(time.hour < endHour ) // daytime operating period

      {   //  while loop (day) begins here
      digitalWrite(gatePin, HIGH);   // turn on gate for power supply
      Serial.flush(); //needed before sleepy
      Sleepy::loseSomeTime(30000); // low power wait
      digitalWrite(gatePin, LOW);    // turn off gate for power supply
      Serial.flush(); // needed before sleepy
      for (int i=0; i <= 3; i++){
        Sleepy::loseSomeTime(65000); // low power wait
        } // end for loop
      rtc.readTime(&time);
      } // end while loop (day)
      } //  if condition (daytime) ends here
else
  { // else condition (night time) starts here
    while (time.hour >= endHour || time.hour < startHour )
    { // while loop (night) begins here
    for (int i=0; i <= 59; i++){
    Serial.flush(); // needed before sleepy
    Sleepy::loseSomeTime(65000); // low power wait
    } // end for loop
    rtc.readTime(&time);
    } // while loop (night) ends here
// need to refine timing else hour-long wait periods can run past the end of night period
  } // else condition (night) ends here
} //  main loop ends here

I will be very grateful for advice, many thanks in advance!

EDIT: Part of my original question could be answered - see below about time-date format without using RTC. Issues with RTC appear harder than I expected. I think they will need a new question later.