Waking Raspberry Pi on time schedule using Sleepy Pi I'm have a Sleepy Pi and am having extreme difficulties trying to program a wake/sleep cycle. Sleepy Pi is an Arduino board with a RTC. My ultimate goal is for a time-lapse project.

I have the Raspberry Pi programmed and operational to take a picture on boot, my trouble is coming from trying to program the Arduino board to actually do it's job.

I would like the Sleepy Pi to wake at 8am, 9am, 10am, ..., 3pm, 4pm, and 5pm, each for 5 minutes, then go back to sleep. I've been working with the SleepyPi, Time, TimeAlarms, LowPower, and DS1374RTC libraries in the Arduino IDE. However, I cannot find any examples on how to put everything to sleep until a specific time comes around. Also, in several of my tests, it seems that the clock actually stops when the Sleepy Pi is asleep!

Here is what I've been working with (and this is non-working). It's probably completely wrong.

#include "SleepyPi.h"
#include <Time.h>
#include <TimeAlarms.h>
#include <LowPower.h>
#include <DS1374RTC.h>
#include <Wire.h>

// Set the status LED pin constant
const int LED_PIN = 13;

void setup()
{
  // Configure "Standard" LED pin
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN,LOW); // Switch off LED

  // Start with the Pi off
  SleepyPi.enablePiPower(false);

  // Set our communication rate
  Serial.begin(9600);

  // Set up our boot times
  Alarm.alarmRepeat(8,0,0, startPiUp);
  Alarm.alarmRepeat(9,0,0, startPiUp);
  Alarm.alarmRepeat(10,0,0, startPiUp);
  Alarm.alarmRepeat(11,0,0, startPiUp);
  Alarm.alarmRepeat(12,0,0, startPiUp);
  Alarm.alarmRepeat(13,0,0, startPiUp);
  Alarm.alarmRepeat(14,0,0, startPiUp);
  Alarm.alarmRepeat(15,0,0, startPiUp);
  Alarm.alarmRepeat(16,0,0, startPiUp);
  Alarm.alarmRepeat(17,0,0, startPiUp);
}

void loop()
{
  // Tick the alarm clock every second
  SleepyPi.enableWakeupAlarm();
  Alarm.delay(1000);

  // Cut Power if we detect Pi not running
  bool pi_running;
  pi_running = SleepyPi.checkPiStatus(true);
  if(pi_running == false){
    SleepyPi.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
  }

  // Flash the LED
  digitalWrite(LED_PIN,HIGH);
  delay(1000);
  digitalWrite(LED_PIN,LOW);
}

// Function to tell the Pi to boot up
void startPiUp()
{
  // Turn the Pi on
  SleepyPi.enablePiPower(true);

  // Turn on the LED to signal we're here
  digitalWrite(LED_PIN,HIGH);

  // Keep the Pi on for 5 minutes
  delay(300000);

  // Start a shutdown
  digitalWrite(LED_PIN,LOW);
  SleepyPi.piShutdown(true);
}

I also cannot find a good way to "debug" things. I've been trying to use the LED flashes as a "I'm here" echo, but have been unsuccessful with this as well.

NOTE: I do not have enough reputation on this site yet to create new tags. Someone with over 150, please tag this with raspberry-pi and sleepy-pi. Thank you.

I have the same problem and  I just saw that they fixed a bug in a library used by SleepyPi

More specific, the RTC library file DS1374RTC.cpp reads since March: '2015
(which is after the question was asked)

  Releases
    ========
    V1_0 - 10 Aug 2013 - Initial release
    V1_1 - 11 Mar 2015 - Mod:    Added "ackAlarm" and "ackRTCOSF" functions to aid Alarm use
  - Bugfix: Changed the way the "SetAlarm(tmElements_t   &tm)" was updating the Alarm time. It wasn't mapping correctly

They also added a new example to wake up the Pi: WakePeriodicallySimple.ino


FlexyStepper: set current position leads to reach the old target I'm using the FlexyStepper library.Unfortunately there's no way to write an issue to the author so I'm going to ask my question here.

The documentation says about the setCurrentPosition*() functions:

  set current position of the motor in millimeter, this does not move the motor

But I see a different behavior.
Looking at the code, it seems it just update the current position, leaving unchanged the target position. This leads to an expected movement of the motor. Example:

set the target position to, say: 1000
the motor reach that position
set the current position to, say: 1500
now the motor come back to 1000

Instead, I want the current position from now is 1500, but because it has already reached the target, it shouldn't move further.

Of course a workaround is to set both current position and target to the same value.

I wonder if I'm wrong about the documentation or this might be considered a bug.

The point of setCurrentPosition() is to calibrate the stepper. It would normally be used in association with a limit switch of some form.

If you set the motor to go to 1000 and then tell it that the motor is actually at 1500 then of course it will then try and go back to 1000 - you have told it that is where you want it, but you also told it that's not where it is.

The normal usage would be:

Step the motor constantly in one direction until it hits a limit switch or similar
Set the current position to whatever that actual position is
Start going to actual positions that are relative to that reference point.

For example

Move the motor anti-clockwise
Motor triggers limit switch
Stop moving the motor
Set the current position to 0
Start using the motor normally


Ardunio Mega/ATmega2560: Using Port F or K for both analog inputs and digital outputs On an ATmega2560, can ports have some pins used for analog inputs but others as digtial i/o? Specifically, I only need to use 3-5 analog inputs but have many digital inputs. I would like to use the remaining 3-5 pins as digital outputs if possible.
Additionally, does it make a difference if the port in question is Port F vs. Port K? For Port F, the datasheet seems to imply that all 8 of the pins are analog only if the ADC is enabled:

Port F serves as analog inputs to the A/D Converter.
Port F also serves as an 8-bit bi-directional I/O port, if the A/D Converter is not used.

For Port K, however, the datasheets port description does not have the distinction:

Port K serves as analog inputs to the A/D Converter.
Port K is a 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit).

It seems that this is definitely possible for the Arduino Uno/ATmega328P ADC port (except for the ADC6/7 pins for 32-pin form factors), but I can't seem to find anything confirming for the Arduino Mega/ATmega2560 or distinguishing between whether this is done on Port F or Port K

On an ATmega2560, can ports have some pins used for analog inputs but others as digtial i/o?

Yes, the ADC MUX controls the selection of the pin that is connected to the converter. This is independent of the digital pin control.

Cheers!

PS: See the Arduino core source code for further details on the ADC MUX control registers.


Will an Arduino Uno be able to read 3x incremental encoders? Encoders are quadrature 600ppr encoders with X2 counting. Therefore 1200 counts per revolution for each encoder. Is there an edge rate limit? I currently have one encoder hooked up using code with interrupts.

Here is an example of some code I used to read two encoders using pin change interrupts.  This is possible to do with one ISR since they all share a common port.  The key is it has to be short.  As long as you can keep all 6 pins from your encoder on the same port, this should be easy to extend to 3 encoders.  It might even work for four on one port.  Or you can make a use a second port and get 3 or 4 more depending on which chip you have.

volatile uint8_t lastPortRead = 0;

volatile int32_t leftCounter = 0;
volatile int32_t rightCounter = 0;

ISR(PCINT2_vect){

    uint8_t portRead = PINC;

    uint8_t whoFired = portRead ^ lastPortRead;
    uint8_t pinsDiff = portRead ^ (portRead << 1); // Will have bits 5 or 7 set if pins on right motor or left motor are diff.  Cleared if same.

    if (whoFired & LEFT_INT_MASK) {
        if (pinsDiff & LEFT_INT_MASK) {
            leftCounter++;
        } else {
            leftCounter--;
        }
    }
    if (whoFired & RIGHT_INT_MASK) {
        if (pinsDiff & RIGHT_INT_MASK) {
            rightCounter++;
        } else {
            rightCounter--;
        }
    }

    lastPortRead = portRead;
}


char buffer to String in Arduino UNO String getAPIData()
{
  char res_buffer[450];
  int numdata = inet.httpGET("myserver.com", 80, "/call.php?id=1&q=1&code=1001", res_buffer, 450);
  String result = String(res_buffer);
  Serial.println(result);
  Serial.println(numdata);
  return result;
}

Output on Serial:

15:52:07.208 ->
15:52:07.208 -> 393

But, When I print the buffer by loop I got the below output:

HTTP/1.1 200 OK
Date: Mon, 16 Sep 2019 06:28:59 GMT
Server: Apache
X-Powered-By: PHP/7.2.20
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Set-Cookie: PHPSESSID=5b21eeac22dcf61f2e4d2efd579d437c; path=/
Upgrade: h2,h2c
Connection: Upgrade, close
Vary: Accept-Encoding,User-Agent
Content-Type: text/html; charset=UTF-8

-1

I am not sure why the char buffer is not converting to String in Arduino UNO.

Any known issues ? Please suggest if any correction required.

Do not use String. And especially do not use String in the way you are using it.

You can read more about why not here.

Instead stick to just using char* buffers.

The correct way of doing what you want is to define the buffer outside your function and then pass that buffer to the function to be populated:

int getAPIData(char *buf, int maxlen) {
  return inet.httpGET("myserver.com", 80, "/call.php?id=1&q=1&code=1001", buf, maxlen);
}

Then you call it with:

char *my_buffer[450];
getAPIData(my_buffer, 450);
Serial.println(my_buffer);


Getting error ets jan 8 2013,rst cause:4,boot mode(1,6) wdt reset I'm working on a project to send ultrasonic sensor data to my webserver. For that I'm using ESP8266  WiFi module, 3.3V regulator IC by giving input volt of 5v from aduino uno.

I successfully uploaded a code but in serial monitor I got an error

ets jan 8 2013,rst cause:4,boot mode(1,6) wdt reset.

Please, tell what does it mean?

Here is my code. Guide me if I made something wrong. Thanks in  advance.

Note:
Before sending sensor values I successfully send a raw data  manually to webserver, i.e string data, but when I try to send sensor values, I got an error.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "VENTURE 11";
const char* pass = "12345678";

WiFiClient clientx;
const int trigPin = 8;  //Digital port D5
const int echoPin = 9;  //Digital port D6

long duration;
float distance;
float Mdistance;
float MAX_HEIGHT = 0;

void setup() {

  Serial.begin(115200);                                  //Serial connection
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT);

  WiFi.begin("VENTURE 11", "12345678");   //WiFi connection
  Serial.println("Setup iniated");
  while (WiFi.status() != 3) {  //Wait for the WiFI connection completion
    delay(500);
    Serial.println("Waiting for connection");
    Serial.print("WIFI STATUS : ");
    Serial.println(String(WiFi.status()));
  }
  Serial.println(String(WiFi.status()));
}

void loop() {
  Serial.println(String(WiFi.status()));
  if (WiFi.status() != 3)
  {
    WiFi.begin("VENTURE", "12345678");   //WiFi connection
    while (WiFi.status() != 3)
    {
      Serial.println("Waiting for connection");
    }
  }
  else
  {
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);

    // Calculating the distance
    distance = (duration * 0.034) / 2;

    if (MAX_HEIGHT == 0) {
      //MAX_HEIGHT = distance;
      Serial.print("Max height has been set to ");
      //Serial.print(distance);
      Serial.println(" cm");
      Serial.println("Waiting for 5 seconds...");
      delay(5000);
    } else {
      Serial.print("Distance:\n");
      Serial.print(distance);
      Serial.print("cm\n");
      Serial.print("Distance:\n");
      Serial.print(distance / 100);
      Serial.print("m\n");
      delay(1000);

    }

    HTTPClient http;
    String Data = "x=" + (String)distance + "&y=" + (String)MAX_HEIGHT + "&z=0";
    //String Data = "x=Finally&y=Did&z=it;)";
    http.begin("http://testingblahblah.000webhostapp.com/IOTCON.php");
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    int sent = http.POST(Data);
    Serial.println(sent);
    String httpPayload = http.getString();
    Serial.println(httpPayload);
    if (sent > 0)
    {
      Serial.println("Message has been sent");
    } else {
      Serial.println("unable to send data");
    }
    delay(20000);

  }
}`

Your loop():

void loop() {
  Serial.println(String(WiFi.status()));
  if (WiFi.status() != 3)
  {
    WiFi.begin("VENTURE", "12345678");   //WiFi connection
    while (WiFi.status() != 3)
    {
      Serial.println("Waiting for connection");
    }
  }
  else
  {
    // Other code...
  }
}

While waiting for the connection, you are creating String objects at a very high rate, since your delay(20000) is in the else clause.

This means you are possibly running out of memory, as you are creating the String objects with every iteration, which is in the Megahertz range.

You likely don't need the String(...) wrappers, as the Serial.println() function can work with C-style strings returned by the WiFi library. Then, your program won't be allocating memory to hold the result of WiFi.status() millions of times per second, which you don't use later on in your program.


Sketch with multiple classes (.h and .cpp) - how to interconnect classes I wanted to move most functionality of my sketch into different classes, to keep things better organized. One class worked just fine, but when I had to use multiple classes and pass information between then things stopped working.

I have two classes, my main Remote class, and my RemoteDisplay class. The main class takes care of fx, measuring battery voltage and I want to display this through the RemoteDisplay class. To do so I initiate the Display class with a pointer to the Remote class, so I can access the voltage function. This, however, doesn't work, even though I forward declare the Remote class in the Display class.

Remote.ino

#include "Remote.h"

Remote Remote;

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

void loop() {
  Remote.display.showBattery();
}

Remote.h

#include "RemoteDisplay.h"
class Remote
{

public:

  RemoteDisplay display;

  Remote( void );

  float voltage;

};

Remote.cpp

#include "Remote.h"

Remote::Remote(void)
{
  display.initiate(this);
}

RemoteDisplay.h

class Remote;

class RemoteDisplay
{

public:

  RemoteDisplay(void);

  void initiate( Remote * _pointer );

  void showBattery( void );

private:

  /* Reference to the remote class */
  Remote * pointer;
};

RemoteDisplay.cpp

#include "RemoteDisplay.h"

void RemoteDisplay::initiate( Remote * _pointer )
{
  pointer = _pointer;
}

void RemoteDisplay::showBattery( void )
{
  Serial.println( pointer->voltage );
}

I get the errors:

error: invalid use of incomplete type 'class Remote'
showBattery( pointer->voltage() );

note: forward declaration of 'class Remote'
class Remote;

Why is it so? Any help is much appreciated.

In RemoteDisplay.cc you are using Remote in the Initiate method.

Also, since you use the voltage property, you need to include "Remote.h" within (as first line normally) in RemoteDisplay.cpp.

Also it is advised to use within every header file the following pattern (example for RemoteDisplay.h):

#ifndef REMOTE_DISPLAY_H
#define REMOTE_DISPLAY_H
...
...
#endif // REMOTE_DISPLAY_H

This prevents problems that two include header files forever include each other.


Arduino - Calculating the time for which a Pushbutton is pressed and held without being released I'm working on a project that requires calculating the time for which a pushbutton is kept pressed without being released. Is there a code snippet that i can use for this particular need ?

There is a library called "Debounce", which you can find here: playground.arduino.cc. Based on that library, here is a simple sketch that displays the amount of time a button is pressed.

// Connect one end of a N.O. push button switch to GND and the other
// end to pin 4 of the Arduino.
// NOTE: If the button is held down for less than the debounce delay
//       time, the elapsed time will display the debounce delay time.
#include <Debounce.h>
const byte SWITCH = 4;
unsigned long startTime = 0;
unsigned long endTime = 0;
unsigned long elapsedTime = 0;
const byte debounceDelayTime = 50;

Debounce debouncer = Debounce(debounceDelayTime, SWITCH);

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

void loop(){
  if(debouncer.update()){
    if(debouncer.read() == 0){
      startTime = millis();
      Serial.println("Button Pressed");
    }
    else if(debouncer.read() == 1){
      endTime = millis();
      Serial.println("Button Released");
      elapsedTime = endTime - startTime;
      Serial.print("Button Held Down For ");
      Serial.print(elapsedTime);
      Serial.println(" ms.");
    }
  }
}


Can i connect in pin of relay module to Analog pins of arduino instead of digital pin? Im a complete beginner
Im making a project using relay modules and arduino. but all the digital pins of my arduino are filled.
I wanted to ask if i can use the analog pins to connect my relay module to my arduino? If yes can anyone give me the statements to write high and low using analog.

Yes, you can  use the analog pins as digital pins.
Quoting this Arduino tutorial:
pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH);

EDIT:
Here is the code snippet for digital input:
pinMode(A0, INPUT);
digitalRead(A0);


Basic usage of Nick Gammon's Regexp library I am using the following code modified from the examples. I get the count of matches but the actual value is not displayed

#include <Regexp.h>

void setup() {
    Serial.begin(115200);
    MatchState ms;
    char buf [100];
    char buf2 [100] = "The quick brown fox jumps over the lazy wolf";
    ms.Target (buf2);
    unsigned int count = ms.MatchCount ("[aeiou]");

    Serial.print ("Found ");
    Serial.print (count);
    Serial.println (" matches.");
    for (int j = 0; j < count; j++)
    {
          Serial.print ("Capture number: ");
          Serial.println (j, DEC);
          Serial.print ("Text: '");
          Serial.print (ms.GetCapture (buf, j));
          Serial.println ("'");
    }
}
void loop(){}

You haven't defined any capture groups in your regexp.

The regexp [aeiou] will match any of those characters, but it won't capture them.  To capture you need to define a capture group which is a sequence of tokens surrounded by parenthesis.  For instance:

([aeiou])

In your test phrase "The quick brown fox jumps over the lazy wolf" that should match 11 times and capture each match, resulting in captures of e u i o o u o e e a o.

The reason why matching and capturing are two completely different things is so you can do things like [aeiou]([aeiou]) which would capture the second vowel in a two vowel sequence. In your example it would match the ui of quick and capture just the i.


How to wait outside the loop without delay()? Is it possible to delay a task inside a function that is called only once (meaning, it's not inside the loop) without using delay()?

This library I'm using, for reading sensor measurements via serial has a delay() in it. I want to get rid of it, but I don't how to do it, because the library's function is not looped.

I guess the simple solution would be to move the library functions inside the loop, so I can do a simple check with millis() and run the delayed part as soon as 250 ms have passed. I would like to improve this library though and do a simple, single call for sensor data that doesn't not hold up the entire program.

This is the function with the delay:

uint16_t COZIR::Request(char* s)
{
  Command(s);
  // empty buffer
  buffer[0] = '\0';
  // read answer; there may be a 100ms delay!
  // TODO: PROPER TIMEOUT CODE.
  delay(250);
  int idx = 0;
  while(CZR_Serial.available())
  {
    buffer[idx++] = CZR_Serial.read();
  }
  buffer[idx] = '\0';
  uint16_t rv = 0;

  switch(buffer[1])
  {
    case 'T' :
            rv = atoi(&buffer[5]);
            if (buffer[4] == 1) rv += 1000;
            break;
    default :
            rv = atoi(&buffer[2]);
            break;
  }
  return rv;
}

I've had a look at the SoftTimer library, but it requires sketches to be written very differently (without a loop). I'm also not sure if I can even pass arguments to delayed tasks with that library.

You could split Request() into two separate functions: You call sendRequest(), then go do other stuff, then, some time later, you call getResponse(). If you get RESPONSE_NOT_READY, then you know you have to call it later:

#define REQ_WAIT_DELAY     250  // Wait for 250 ms
#define RESPONSE_NOT_READY ((uint16_t) -1)

uint32_t time_request_sent;

void COZIR::sendRequest(char* s)
{
  Command(s);
  time_request_sent = millis();
}

uint16_t COZIR::getResponse()
{
  if (millis() - time_request_sent < REQ_WAIT_DELAY)
      return RESPONSE_NOT_READY;
  buffer[0] = '\0';  // empty buffer
  int idx = 0;
  // From here, same as original COZIR::Request()
}

This assumes that RESPONSE_NOT_READY (0xffff) is not an otherwise valid response. If all 2^16 values of an uint16_t may be valid, then you need another way for the library to signal that the response is not ready. Also, make sure you never compare timestamps, because of the millis() rollover problem. Taking the difference between two timestamps and comparing this with a specified delay (as in the example above) is rollover-safe.

Update: Here is an example of how this could be used:

COZIR cozir(some_serial_connection);

void loop()
{
    static bool waiting_for_a_cozir_response = false;

    if (time_to_get_another_cozir_reading()) {
        if (waiting_for_a_cozir_response) {
            report_something_is_wrong("This COZIR is too slow!");
        }
        else {
            cozir.sendRequest("Hi Cozir! Pliz send me another reading.");
            waiting_for_a_cozir_response = true;
            /* We won't get the response on this iteration. *
             * We will ask next time.                       */
        }
    }
    else if (waiting_for_a_cozir_response) {
        uint16_t response = cozir.getResponse();
        if (response == RESPONSE_NOT_READY) {
            /* Nothing to do now, really. We will just try again *
             * at the next loop() iteration.                     */
        }
        else {
            waiting_for_a_cozir_response = false;
            do_something_with_the_cozir_response(response);
        }
    }
    do_whatever_else_has_to_be_done_in_the_loop();
}


Nodemcu powering with 5.2v and 2A? I bought a this voltage regulator . DC-DC 5v 8A voltage regulator. ıts supported 8-35V input voltage . And i want to use this with 12v power supply.
But i searched on the internet . Nodemcu max amp is 800mA. This device can provide 2A per usb output if i will plug the nodemcu with usb cable this what happen ? Does it burn ? How can i drop the amps ?  i want to use other 3 usb output with other devices sensors and screen .

Generally, we specify DC power supplies as constant voltage sources.  In order to do this, power supplies deliver more or less current as demanded by the load in an attempt to keep the voltage constant regardless of the load.

When a constant voltage DC power supply specifies a maximum current, it is saying the power supply can only maintain the specified voltage while the current demand is less than the specified maximum current.

To be clear, unless you need a constant current power supply, a power supply should be picked based on the required constant voltage.  And the capacity of that power supply, usually measured in Amps, should exceed the maximum combined current demand of all connected devices (loads).


Can a motherboard be a simple circuit between arduino uno and a set of devices (ie: motors) Reason for question:
My son is working on a project to build a robot controlled by an arduino uno. This question is more about terminology than process, but since terms are very important at this level, I rather ask some expert advice - I have not found any input on the internet about this!

Question:
What is the correct technical name (if any) of the circuit board that acts as the interface between the arduino-uno (a micro-controller) and the motors (the external devices)? According to the definition of a motherboard*, this "interface" circuit board would act as a very basic motherboard, as it would "allow communication" between the components, but it would not contain expansion slots, so should it be called something else?

Background on project:
The robot will be very basic. A body will be made of plastic legs and motors for joints; an Arduino-uno will provide the logic for motor movement; and a custom circuit board (hence my question) will act as the interface between the uno and the motors, providing electricity from a dedicated source to the motors.

We are just missing the proper terminology to use for this "interface" board and I cannot find any concrete info online or on books. If I get good terms in this post, then we can do further research on those terms. Thanks.

https://en.wikipedia.org/wiki/Motherboard

I would call it an "interface" or "driver" board. You don't need to get too hung up on the exact name.
The word "shield" is one of the Arduino-peculiar words (like "sketch" for "code") which now has a generally-understood meaning. That meaning is, something that plugs directly onto the Arduino board, with the pins on the shield matching the sockets on the Arduino board.
Whilst a shield is a quick and easy way of getting started (because you don't need to wire anything) they can have their disadvantages. One being, what if you want two different functions, like a motor driver and an Ethernet interface? Two shields, one on top of the other? What if they both use a certain pin for different purposes?
I made up a radio-controlled car, see photo:

The only shield I used was a generic "put whatever you want onto it" shield, which let me mount some MOSFETs, a radio receiver board, and other components, as required by the design. There is a Uno underneath it, not particularly easy to see. Adjacent on the right is a motor driver board. A LiPo battery is slung underneath.
This kept things reasonably compact, without requiring a specific purpose-made shield which only does one thing.

and a custom circuit board (hence my question) will act as the interface between the uno and the motors, providing electricity from a dedicated source to the motors.

It sounds like your project is similar to my car. Just assemble things in a way that makes sense to you.


maximum interrupt-based PWM frequency at 500 Hz I need to control a 24 kHz ultrasonic transducer and decided to use an arduino uno I have lying around.

Using tone() or the atmega's hardware pwm is not very suitable because I need two 50/50 square waves with a phase difference of pi (which is equal to two XOR'ed pins) to switch the output polarity of the h-bridge synchronously. As the uC dosen't have anything else to do I wrote the following sketch where I just wait for an interrupt and toggle pins 2&3:

bool do_task=false;
void timer_init () {
  TCCR0A |= (1 << WGM01);
  OCR0A = 83;
  TIMSK0 |= (1 << OCIE0A);
  TCCR0B |= (1 << CS01);
}
ISR (TIMER0_COMPA_vect) {
  do_task=true;
}

bool state=false;
void toggle() {
  state=!state;
  digitalWrite(2,state);
  digitalWrite(3,!state);

}

void setup() {
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  timer_init();
}

void loop() {
  if(do_task) {
    do_task=false;
    toggle();
  }
}

I expected the output to have a frequency of ~24 kHz, but it is 500 Hz instead.

From my understanding:

16 MHz CPU frequency
timer0 prescaler is 8 (TCCR0B |= (1 << CS01))
output compare value (OCR0A) is 83

would result in a frequency of 16 MHz / 8 / 83 = 24096,4 kHz -but as I mentioned- it's 500 Hz and doesn't seem to depend on the prescaler.

You wrote:

  Using [...] the atmega's hardware pwm is not very suitable because I
  need two 50/50 square waves with a phase difference of pi

I believe hardware PWM is the best solution to your problem. The PWM
outputs can be set to either “inverting” or “non-inverting” mode.
Set the two channels of a single timer to the same duty cycle, with one
in non-inverting mode and the other one in inverting mode, and you have
your complementary outputs.

Example using Timer 1:

const float SIGNAL_FREQUENCY = 24e3;
const uint16_t HALF_PERIOD = round(F_CPU / SIGNAL_FREQUENCY / 2);
const uint16_t PERIOD = 2 * HALF_PERIOD;

int main()
{
    /* Set the PWM pins as outputs. */
    DDRB |= _BV(PB1);  // digital  9 = PB1 = OC1A
    DDRB |= _BV(PB2);  // digital 10 = PB2 = OC1B

    /* Configure Timer 1. */
    ICR1   = PERIOD   - 1;
    OCR1A  = PERIOD/2 - 1;
    OCR1B  = PERIOD/2 - 1;
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(COM1B0)  // inverting PWM on OC1B
           | _BV(COM1B1)  // ditto
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)  // ditto
           | _BV(WGM13)  // ditto
           | _BV(CS10);  // clock at F_CPU, start timer
}


OLED DISPLAY USING SPI My display is not responding to this code. Help please

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_MOSI 10
#define OLED_CLK 9
#define OLED_DC 12
#define OLED_CS 13
#define OLED_RESET 11
Adafruit_SSD1306 display(OLED_MOSI,OLED_CLK,OLED_DC,OLED_CS,OLED_RESET);

void setup(){
  Serial.begin(9600);
  display.begin(SSD1306_SWITCHCAPVCC);
  display.clearDisplay();

  display.setTextSize(1);
  display.setCursor(30,30);
  display.print("Hello WOrld");
  display.display();
  }

  void loop(){

    }

Pin definitions in your code seem to be mixed up. If Adafruit example works fine with your setup, you should keep the pin definitions Adarfruit uses:

#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13

Also, you are using a deprecated constructor. It is recommended to use a constructor which explicitly specifies display size.


Is it possible to use AWS and Arduino Uno to upload data from Arduino to a website running on my localhost? I was wondering if it's possible to send data from my Arduino Uno (e.g. from the temperature sensor) to the Amazon Web Service RDS or anything there, which will then upload the data to a website on my localhost?

If yes, could someone give me guidance please?

I've been messing with this for a few weeks now, but I am just getting lost with linking it all up together.

Thanks.

No, it is not (easily) possible.

AWS has no access to your localhost - you are (most likely) behind a NAT router.

You could possibly open up port forwarding on your router and then ensure that AWS knows always what the IP address of your router is so it can connect (using some dynamic DNS service maybe).

However, that is not secure, and dynamic IP address assignments makes it a real pain. It opens up your computer to hacking from the internet.  A more secure method is to use AWS as the "central point" and have your computer go and fetch data from there rather than having it send data to your computer.


Power converting - up or down? Sorry if there is an obvious answer to this - I'm pretty new at Arduino and electronics. I've searched a bunch, but I think I'm too vague - and don't know what terms to look for.

I have a pretty simple project using a 3.3v Arduino Pro Mini (https://www.adafruit.com/products/2377) and a 12v button/LED (https://www.adafruit.com/products/1185).

I'd like to give the LED the full 12v so the light is a bright as possible. The system will be battery operated.

The question is: Do I need a 12v power supply or can I use a 3.7v power supply and upgrade it somehow? I know I can power the LED with 3.7v but then it's really dim. Is there a way to "upgrade" the 3.7v to 12v? I would assume this would draw more power and drain the battery faster, but I think that would be ok.

I'm hoping to get away with a 3.7v power supply because I want to use a lithium ion polymer battery (https://www.adafruit.com/products/328) - since it's small and rechargeable.

Seems like if I go with 12v source then I need a much bigger battery pack, and I'm hoping to keep the project small. Not sure if it would help to know, but I only need the device to run for 4+ hours between charges.

I'm guessing people will say to go with 12v since the Pro Mini can downgrade the 12v supply so there'd be less parts I have to deal with (I can already make this work). But, again, I was hoping to get away with a small rechargeable power supply. Or, are there good, small 12v batteries - I can't seem to find any on Adafruit or SparkFun.

Any recommendations? Thanks!

Since your project is to be battery powered, you want to make your system as efficient as is reasonable.

So I am going to take an approach that ends up improving the efficiency of your project.

The button you describe in your link states :

  This button has a domed red plastic cover with a black retaining ring around it. There's an optional LED included

Further, the LED included has a "built in resistor", so that the LED can operate from 12 volts.

Since you would have to install the "optional LED",  why not purchase a Red LED that operates from lower voltage. You will still need a resistor but you won't need to have a voltage converter.

Example  :  Their LED probably has a 2 volt LED (approximate) that operates at perhaps 20 mA).  This would require a 500 ohm resistor (which they incorporate into the LED).  The power loss (wasted) in the resistor is 0.2 watts (200 mW).

Improved Example :  With LED of about 2 volts operating from 3.3 volt power source.  This would require a 68 ohm resistor.  The power loss in the resistor would be 0.027 watts (27 mW).  A substantial improvement in efficiency.

The manufacturer of the button does not give specifications for the LED (the one with the resistor included).  You should connect their LED to a 12 volt power supply and measure the current drawn.  It is possible their LED draws more current than I have shown in the examples.  This would require a re-calculation of the resistor values.

But in any case, the improvement in efficiency will still exist.


Increase PWM bit resolution I would like to increase the PWM bit resolution of the Arduino Uno.
At this moment it is 8-bit which I consider too low.
Is this possible without losing the ability of interrupts and delays?

Koen

EDIT
This setup delivers a 16-bit resultion

void setupPWM16() {
    DDRB |= _BV(PB1) | _BV(PB2);        /* set pins as outputs */
    TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
        | _BV(WGM11);                   /* mode 14: fast PWM, TOP=ICR1 */
    TCCR1B = _BV(WGM13) | _BV(WGM12)
        | _BV(CS11);                    /* prescaler: clock / 8 */
    ICR1 = 0xffff;                      /* TOP counter value (freeing OCR1A*/
}
/* Comments about the setup
Changing ICR1 will effect the amount of bits of resolution.
ICR1 = 0xffff; (65535) 16-bit resolution
ICR1 = 0x7FFF; (32767) 15-bit resolution
ICR1 = 0x3FFF; (16383) 14-bit resolution etc....

Changing the prescaler will effect the frequency of the PWM signal.
Frequency[Hz}=CPU/(ICR1+1) where in this case CPU=16 MHz
16-bit PWM will be>>> (16000000/8)/(65535+1)=30.5175Hz
*/

/* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
void analogWrite16(uint8_t pin, uint16_t val)
{
    switch (pin) {
        case  9: OCR1A = val; break;
        case 10: OCR1B = val; break;
    }
}

The Arduino Uno is based on an ATmega382P microcontroller. This chip has
two 8-bit timers, driving two PWM channels each, and one 16-bit timer,
driving the last two channels.

You cannot increase the resolution of the 8-bit timers. You can,
however, put the 16-bit timer in 16-bit mode, instead of the 8-bit mode
used by the Arduino core library. This will give you two 16-bit PWM
channels, with a reduced frequency of 244 Hz (maximum). You will
probably have to configure the timer yourself, and will not benefit from
the easy to use analogWrite() function. For details, see the section
on Timer 1 in in the ATmega328P
datasheet.

Update: Here is an implementation of a 16-bit analogWrite(). It
only works on pins 9 and 10, as these are the only pins connected to the
16-bit timer.

/* Configure digital pins 9 and 10 as 16-bit PWM outputs. */
void setupPWM16() {
    DDRB |= _BV(PB1) | _BV(PB2);        /* set pins as outputs */
    TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
        | _BV(WGM11);                   /* mode 14: fast PWM, TOP=ICR1 */
    TCCR1B = _BV(WGM13) | _BV(WGM12)
        | _BV(CS10);                    /* no prescaling */
    ICR1 = 0xffff;                      /* TOP counter value */
}

/* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
void analogWrite16(uint8_t pin, uint16_t val)
{
    switch (pin) {
        case  9: OCR1A = val; break;
        case 10: OCR1B = val; break;
    }
}

You may notice that the top of the counter sequence is configured
explicitly. You can change this to a smaller value to make the PWM
faster, at the cost of decreased resolution.

And here is an example sketch illustrating its use:

void setup() {
    setupPWM16();
}

/* Test: send very slow sawtooth waves. */
void loop() {
    static uint16_t i;
    analogWrite16(9, i);
    analogWrite16(10, 0xffff - i);
    i++;
    delay(1);
}


How to have multiple digital outputs for the same pin on Arduino Uno and Simulink? I'm trying to develop a PID controller with Simulink as shown in the image PID. I'm using a PID controller to control a motor via an Arduino Uno and motor driver.

I have the PID output connected to an if statement.

If u1 is larger than 0 then output 1 for digital output pin 2 and output 0 for digital output pin 4.
If u1 is smaller than 0 then output 0 for digital output pin 2 and output 1 for digital output pin 4.

This changes the direction of the motor so that if the PID overshoots it will change direction. And so on for u1 is smaller than 0.

I also have the PWM signal for the speed of the actuator from 0 being the slowest and 255 as the fastest[]. I forgot to fix the label for it.

I keep getting an error when I try to run it. The error says that I can't run it because of having multiple digital output blocks with the same pin as shown in this image Error in Simulink.

Is there a solution for this?

You cannot try and have two things controlling one output in two different ways. It just makes no sense.  Like trying to have two people steer a car and have one go left and the other right.

I don't quite know what you're trying to do, but under normal usage using a motor driver requires 3 pins (for example the common L239D). Two define the direction and a third (the EN pin on the L239D) controls the speed with PWM.


Where is the documentation for the Emoro GLAM pro module? My 11-year-old son recently brought out an Emoro robot he got for his birthday. We had some temporary confusion with the robot, but got it to work.
He is now trying to connect to his computer via Bluetooth from the Emoro, but cannot find any documentation on Emoro Bluetooth.

Where is the documentation for Emoro Bluetooth?

What you are searching can be found via googling, if you know, what to google for. I write a formal answer to this, because there is neither a link on the product page of the manufacturer, nor is it very easy to find for a beginner.

Have you seen this repository emoro-2560-library on github? It seems to incorporate libraries for nearly ever function of the Emoro, including the bluetooth functionality of the GLAM board. You can find examples in the GLAM examples folder.

How did I found it? I googled for "emoro github". A better search phrase would be "emoro 2560 github" (Since Emoro 2560 is somewhat the extended name of the robot). I used the term "github", since most libraries for Arduinos and their derivates/variants are hosted on github. If you are search for a library, you can first search for them on github. Most times you will find something. Often these libraries also serve as a kind of documentation (as real and good documentation can be rare to find).

Now somewhat unneeded, but from the library code and the pictures on the product page of the GLAM module, I think, that a serial bluetooth module with AT firmware like HC-05 is used. If you ever want to look past the bluetooth library for the robot, you would need to go that way. (How a Hc-05 is controlled can also be googled)


Update code over Ethernet? I've got an Arduino faithfully monitoring our sewer lift pump. It talks to the world over Ethernet (with PoE). I'm wondering if there is any way to load new code over the Ethernet as well. Any ideas if this could be done?

I imagine that using the boot loader might be out of the question, but perhaps it would be possible to upload a new system image – perhaps onto an SD card – and then use a modified boot loader to discover the new image and copy it into place.

A bootloader to network-boot might be too large to leave enough code space for your application. Your second suggestion sounds more workable - to collect & verify the entire new image in secondary storage first, then call a storage-to-flash boot loader. You really don't want to start loading an image that then suffers damage in transit, or to have the link go down mid-download. The likely only way out of that is a site-visit. Saving first lets you confirm the integrity of the new image before you start over-writing any of the old one.


Arduino HC05 - AT commands won't respond A little while ago i tried using AT commands on my HC05 bluetooth module using my arduino mega 2560 and it worked fine , skipping a few weeks ahead i tried doing the same , only now i suddenly doesn't work , i tried replacing the arduino and HC05 module , even used the same script for the commands. So i unplugged the module's VCC , pressed the button on the module , reconnected the VCC and the module was blinking every 2 seconds (it's in AT mode !) , now i go ahead to the serial monitor and using that script i typed the command i wanted to execute and it just didn't do nothing , i saw the serial LED on the arduino blink , but nothing was written in the serial monitor and nothing was changed in the arduino.

Does anyone know how to solve this ? it worked perfect before , but now it wont D:

Maybe you should try a couple of different baud rates for your script? Also check that your RX/TX wires are connected in the right order. I've had some HC-05 modules where RX/TX markings on the module were reversed.


SPI Digital Potentiometer not working on ESP32 I have an MCP4151 digital potentiometer chip. I have managed to get it to work using and Arduino Uno using the code below:

#include <SPI.h>

byte address = 0x00;
int CS= 5;

void setup()
{
  pinMode (CS, OUTPUT);
  SPI.begin();
}

void loop()
{
  for (int i = 0; i <= 128; i++)
  {
    digitalPotWrite(i);
    delay(10);
  }
  delay(500);
  for (int i = 128; i >= 0; i--)
  {
    digitalPotWrite(i);
    delay(10);
  }
}

int digitalPotWrite(int value)
{
  digitalWrite(CS, LOW);
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(CS, HIGH);
}

But when I try to get it to work using an ESP32 programmed using Arduino language it doesn't. I have connected like that

SCK -> 18
MOSI -> 23
SS -> 5

I also used the potentiometer inside like a voltage divider for test purposes. GND on one leg, 3.3v on the other and an LED on the wiper. Are there other settings that I have to implement in order the ESP32 SPI to work like an Arduino SPI? Did I miss something?

I managed to get it to work in a strange way. I opened the example included in the ESP32 SPI Library and copied some points from there.

I first initialise a pointer to the SPI class, then I call begin() at that pointer and inside the digitalPotWrite function I call beginTransaction(10000,MSBFIRST,SPI_MODE0) and end the transaction before digitalPotWrite finishes. Full code here:

#include <SPI.h>

static const int spiClk = 1000000;
byte address = 0x00;
SPIClass * hspi = NULL;

void setup()
{
  pinMode(15, OUTPUT);
  hspi = new SPIClass(HSPI);
  hspi->begin();
}

void loop()
{
  for (int i = 0; i <= 128; i++)
  {
    digitalPotWrite(i);
    delay(10);
  }
  delay(500);
  for (int i = 128; i >= 0; i--)
  {
    digitalPotWrite(i);
    delay(10);
  }
}

int digitalPotWrite(int value)
{
  hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  digitalWrite(15, LOW);
  hspi->transfer(address);
  hspi->transfer(value);
  digitalWrite(15, HIGH);
  hspi->endTransaction();
}


Coding for RTC and stepper motor How easy is it to create a code using an RTC to rotate the stepper motor one way at a specific time and back the other way at a specific time? and that time being charged different months of the year. how would I go about this?
I want to make an automatic chicken door, to open in the morning and close at night.
Thanks

I am assuming that you want to make a clock. To do that you need to find a gear ratio where 1 revolution of the motor equals 60 seconds, and then make the gear ratios for the minutes and horse from that. Then you can use the RTC to spin the motor by 6 degrees every second. If you are not making a clock, please be more descriptive.


Is there a library for non-SAMD Arduinos to use the DMP on MPU9250 I would like to use the DMP of the MPU9250 with my BTLE Feather board but the docu of the official library says that only SAMP-Processors are supported.

Is the a different library I can use?

I did have a look at the MPU9250 DMP library provided by Sparkfun and it seems that it is specifically built for their own board which has an M0 chip on the board. However looking at the library, there seems to be no reasons why it would not work with any other board. The main reason why it might not work with something like the 32u4 board would be because the end firmware is too large or the program need too much RAM that what the 32u4 has.

There is a fix provided on the github issues page for using it with a Nano, which might help you get it work with the 32u4 here and there is another library here that you might be able to use or build up on.

However the best way might be to use a M0 chip itself if you really want to use the same IMU since getting the library to work can turn out tricky. Adafruit does sell a M0 with a Bluetooth board here that you might be able to use.


Problem with interrupts Alright. This is what I wanted to do:

Make a circuit and code the arduino such that there are 2 tactile switches, each with a predefined pwm value.
 Whenever any one button is pressed the led should run at that pwm value, until the button is released. There is
 also an ultrasonic sensor on the same arduino that triggers an interrupt at a threshold distance that
 stops the led. When no button is pressed or the ultrasonic isnt active, the led should run at another pwm value.

Here is the code:(updated)

const int trig = 9;
const int echo = 10;
const int redswitch = 2;
const int yellowswitch = 3;
int redled = 6;
int greenled = 5;
volatile int pwm = 50;

volatile bool rs = LOW;      //RS - RED SWITCH
volatile bool ys = LOW;      //YS - YELLOWSWITCH
bool last_rs = LOW;
bool last_ys =  LOW;
volatile long distance=0;
long duration=0;
long temp=0;

void setup(){
  pinMode(trig,OUTPUT);
  pinMode(echo,INPUT);
  pinMode(redled,OUTPUT);
  pinMode(greenled,OUTPUT);
  pinMode(redswitch,INPUT);
  pinMode(yellowswitch,INPUT);
  Serial.begin(9600);

  attachInterrupt(digitalPinToInterrupt(redswitch), red,CHANGE);
  attachInterrupt(digitalPinToInterrupt(yellowswitch), green,CHANGE);

  digitalWrite(greenled,LOW);
  digitalWrite(redled,LOW);
}

boolean debounce(boolean temp,int switchPin)
{
  boolean current = digitalRead(switchPin);
  if (temp != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

void loop(){

  //Ultrasonic sensor's distance calculation
  digitalWrite(trig,LOW);
  delayMicroseconds(5);

  digitalWrite(trig,HIGH);
  delayMicroseconds(10);
  digitalWrite(trig,LOW);

  duration = pulseIn(echo, HIGH);
  temp = duration * 0.0343 / 2;
  noInterrupts();
  distance = temp;
  rs = debounce(last_rs,redswitch);
  ys = debounce(last_ys,yellowswitch);
  last_rs = rs;
  last_ys = ys;
  if(distance>8)interrupts();

  Serial.println(distance);
  analogWrite(redled,pwm);
  analogWrite(greenled,pwm);
}

void red(){

  if(rs == HIGH) pwm = 150;
  else pwm = 0;

}

void green(){

  if(ys == HIGH) pwm = 250;
  else pwm = 0;

}

Now, when the arduino is connected to my laptop, led runs at the a particular value. But whenever I press a button they go off. Can you help me find out what's wrong here?

Look at these lines:

distance = temp;
duration = pulseIn(echo,HIGH);
distance = duration * 0.0343 /2;

Here is what they do:

The first line sets the variable distance to zero (that's the value
of temp).
The second line waits for the ultrasonic pulse to reach the target,
bounce against it and come back, while at the same time timing the
whole trip. This can take a long time (several milliseconds). Chances
are your program spends most of its time executing this line.
The third line sets the variable distance to something sensible.

This means distance is zero most of the time (while the second line
executes). When the interrupt fires, there is a very high probability
for the interrupt handler to find a zero distance, and thus to set pwm
to zero.

Simple fix: never set distance to an unreasonable value. Leave it's
value alone until you have a new distance measurement ready, and only
then update that variable. In other words, just remove the first of
those three lines.

But there is a catch now. The variable is four bytes long, and updating
it takes four instructions. There is a small probability that the
interrupt fire in between these instructions. When that happens, the
interrupt handler finds the distance variable half-updated, with a mix
of bytes from the previous and the current distance measurements. This
is called a “race condition”, and is one of the worst kind of bugs you
can meet, because it is very hard to systematically reproduce.

The fix to the race condition is to update the variable with interrupts
disabled. The wrong way to do it is:

duration = pulseIn(echo, HIGH);
noInterrupts();
distance = duration * 0.0343 / 2;
interrupts();

This is bad because interrupts are blocked during the distance
calculation, which is too much. The right way is this:

duration = pulseIn(echo, HIGH);
temp = duration * 0.0343 / 2;
noInterrupts();
distance = temp;
interrupts();

Now interrupts are blocked only while writing the distance variable.

Personally I don't think it is such a great idea to read the buttons
with interrupts. Buttons are extremely slow peripherals. If you make
your code non-blocking, your loop() will always be fast enough to deal
with them. Handling the buttons in loop() means you don't have to
worry about all the bugs that can easily sneak into interrupt-driven
code, like the above mentioned race condition.

Edit: In the original version of your code, interrupts were used to
read the switches. In the edited version, you added a debouncer, and you
don't need interrupts anymore. In fact, the way this version uses
interrupts makes no sense at all. The most problematic bit is the fact
that this code can disable interrupts for arbitrarily long times. This
is not good, and you should be aware that the Arduino's timekeeping
functions rely on interrupts to perform their job.

I suggest you just remove from this code every single line where you see
the word “interrupt” (singular or plural), and you replace

if(distance>8)interrupts();

by

if (distance > 8) {
    red();
    green();
}

or, to streamline things a little bit, by

if (distance > 8) {
    if (ys == HIGH) pwm = 250;
    else if (rs == HIGH) pwm = 150;
    else pwm = 0;
}


How to access a website running on my localhost(host/server) to Serial Monitor using ESP8266(Client)? The following source code is from the official ESP8266 website(Explanation provided): https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/client-examples.html
This .ino code returns the html code of the server name mentioned in "const char* server" declaration, on to the Serial Monitor.

And Yes, this code perfectly returned the html codes of wwww.google.com, www.arduino.cc etc. But when I try it with my 'led blinking.html' I am unable to find any luck. I guess it is because the website should be hosted on a live server.

Other Details:
1. uC Board: Wemos D1 mini (An ESP8266 Variant)
2. I am using Xampp to run Apache server and MySQL
3. Wemos board is set up as a WiFiClient

#include <ESP8266WiFi.h>

const char* ssid = "xxxxx";
const char* password = "xxxxxxxx";

I have put the html,php code of the website in the directory : C:/xampp/htdocs/LED BLINKING/led blinking.html

IP Address of my Windows PC: 192.168.100.9

const char* server = "192.168.100.9/LED BLINKING/led blinking.html";

I tried with just "192.168.100.9"; too.
I also unblocked the windows firewall for my ApacheHTTP Server. Now I can view the webpage on my mobile with the URL: 192.168.100.9/LED BLINKING/led blinking.html.

void setup()
{
  Serial.begin(115200);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
}

void loop()
{
  WiFiClient client;

  Serial.printf("\n[Connecting ...");
  if (client.connect(server, 80))
  {
    Serial.println("connected]");

    Serial.println("[Sending a request]");
    client.print(String("GET /") + " HTTP/1.1\r\n" +
                 "server: " + server + "\r\n" +
                 "Connection: close\r\n" +
                 "\r\n"
                );

   Serial.println("[Response:]");
    while (client.connected())
    {
      if (client.available())
      {
        String line = client.readStringUntil('\n');
        Serial.println(line);
      }
    }
    client.stop();
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}

The output on Serial Monitor is:
Connecting to ssid connected
[Connecting connection failed!]

Variable server is a hostname or IP address for TCP connection.
The /LED BLINKING/led blinking.html goes after HTTP GET. Now there is / and it worked for main page of servers.

You need

client.print(String("GET /LED%20BLINKING/led%20blinking.htm") + " HTTP/1.1\r\n" +
             "server: " + server + "\r\n" +
             "Connection: close\r\n" +
             "\r\n"
            );

and you must escape the space


What are the tools that I need to program the Arduino in C? The Arduino IDE by default is oriented towards C++. The linker for example requires .cpp files and not .c files, otherwise it leads to errors during the linking process. See name mangling if you want to know more.

So, what are the tools that I need to setup a C environment? Can this be done from the Arduino IDE itself?

I work on a Linux system (Ubuntu 12.04).

Well, if you want to do more advanced stuff with your AVRs, you should definitely leave the Arduino environment, and integrate your AVR development in your "usual" favorite development environment, whatever it is.

Then you've got two choices, either do 100% pure C with AVR libraries, for which you only need a simple makefile that calls avr-gcc with avr-libc libraries as include path. You can also use Atmel Studio that helps you a lot on that stuff. But if you do so, you're loosing the advantages of the libraries built for/by the arduino community – which, sadly, is not a huge loss for a strong majority of those.

Or you can work your code out as a 100% C external library, used from within the sketch, and included at linking time. Then you'll have all the advantages of working with any C++ library you'd like to have, but still doing the important code in pure C. Having only the .ino used to generate the main .cpp and any .cpp library you'd need. Though, for many basic features like writing on the serial port, you'll have to do it [the good old way][2] or by doing some weird encapsulation of Serial.println() call sent as a functor to the pure C parts.

In the makefile I've written (debian offers another one with the non-gui install of arduino), every .c file from declared libraries are detected and compiled with avr-gcc, every .cpp file is compiled with avr-g++ and both gets linked when doing the .elf/.hex file.


Webserver on Arduino: How to 307 temporary redirect I originally asked this question. Regarding a webserver Refresh issue on arduino.

I am totally new to web development and ethernet. The answer from @Majenko is correct, but I do not understand how to implement it. Should I change the homepage() function's first line to HTTP/1.1 307 temporary redirect and use META REFRESH?

Or do the homepage() first using HTTP/1.1 200 OK and then for all the following requests, use HTTP/1.1 307 temporary redirect?

You need to make a decision on what to respond with depending on what the request is you have received.

If you receive a "command" URL (which you already check for by looking for certain sub-strings) then you need to respond with the 307 response. If you don't receive a "command" URL (so anything except the things you are specifically looking for) then you respond with the homepage.

A slight re-formatting of your decision code to use else if instead of just if would make it easier:

if (c == '\n') {
  Serial.println(readString); //print to serial monitor for debuging
  // homepage(); << This is now moved elsewhere.
  //controls the Arduino if you press the buttons
  if (readString.indexOf("?resetcount1") > 0) {
    count1 = 0;
    redirect();
  } else if (readString.indexOf("?resetcount2") > 0) {
    count2 = 0;
    redirect();
  } else if (readString.indexOf("?resetcount3") > 0) {
    count3 = 0;
    redirect();
  } else if (readString.indexOf("?resetcount4") > 0) {
    count4 = 0;
    redirect();
  } else if (readString.indexOf("?togglerelay1") > 0) {
    toggleRelay1();
    redirect();
  } else if (readString.indexOf("?togglerelay2") > 0) {
    toggleRelay2();
    redirect();
  } else if (readString.indexOf("?togglerelay3") > 0) {
    toggleRelay3();
    redirect();
  } else if (readString.indexOf("?togglerelay4") > 0) {
    toggleRelay4();
    redirect();
  } else { // If none of them match then send the homepage.
    homepage();
  }
}

redirect() is as simple as:

void redirect() {
  client.println("HTTP/1.1 307 Temporary Redirect");
  client.println("Location: /");
  client.println("Connection: Close");
  client.println();
  client.stop();
}


Find vehicle movement by IMU and GPS I'm using MPU9250 which has both accelerometer and gyroscope in a vehicle. What I want is to just know that if the vehicle is currently moving or not. I searched and find out that I can't get velocity easily so I skipped that but I was wondering how can I found movement with an IMU.

Edit:
As @Duncan said, it seems that it cannot be examined with only IMU. I also have a GPS sensor in my device and having the speed value from GPS but it is not very accurate. For example, if the vehicle is stopped for 5 minutes I get variable speeds between 0 to 10.0 kmph and on the other hand getting the location as lat/long has about 20 meters error. So I can't really rely on it. I was wondering can I combine both GPS and IMU to find out if it is really moving or not?
One solution that I came was relying on GPS speed but for spikes just check the accelerometer variations and if it is beyond a threshold, it means that it actually moved.

You noted that your goal is to determine whether or not a vehicle is in motion. Because you are trying an IMU, I assume the device that needs to know this is on-board the vehicle.

There are many complicated ways to know this, such as using the acceleration data from the IMU to perform Inertial Dead Reckoning, this has the problem of temporal drift. A GPS has the issue of needing it's speed data to be filtered a bit to get rid of high-speed spikes.

But -- if you just need to know if the vehicle is moving or not, and if the vehicle has wheels, you can use an light detector, such as an IR emitter and IR receiver pair, along with a slitted disc attached to the wheel, and simply count when the last time the receiver was activated -- if beyond some threshold of time, then you assume the wheel is not turning, and thus that the vehicle is not moving. Or perhaps just use a light sensor and paint white and dark patterns on the wheel.

Or put a magnet on the wheel and place a hall effect sensor (magnet sensor) near where the magnet will pass. Count the pulses from the hall effect sensor.

If the vehicle is not a wheel-based vehicle, then you may have to rely on GPS or some other method, however.


USB 1.1 Low Speed project for Arduino UNO/ATmega328P to learn USB protocol Arduino UNO is 5V, 16 MHz.

USB 1.1 Low Speed spec operate:

at 5V level - so we avoid to maintain voltage level
at 1.5 Mb/s - so we have 16/1.5 ~= 10 instructions per elementary protocol signal

Is it possible to make Arduino as slave USB device from UART lines connected to USB D+/D- interface with careful timing and assembler programming?

I doesn't familiar with ATmega328P pin I/O capabilities, may be them can't operate at 1.5 MHz so project isn't possible?

UPDATE I found V-USB library that:

implementation of a low-speed USB device for Atmel’s AVR® microcontrollers,
making it possible to build USB hardware with almost any AVR® microcontroller,
not requiring any additional chip.

Still dig into docs to realize possibilities.

Not exactly the answer to your question, but have you tried the typical way to emulate slave devices with Arduino UNO?

It uses the 2nd ATMega present onboard (this applies only to UNO, afaik) and lets you use the main ATMega for other tasks, delegating the USB protocol to the smaller ATMega16.

Do you have any specific reason why you would use the serial lines?


Problem with SIM800L GSM module and servo I have a SIM800L GSM module like in this link, .

.

The problem is when I connect the GSM to my Arduino Uno the GSM turns on for a while and then turns off. I tried to connect it with a 9-volt battery and an LM7805 voltage regulator, but I have the same problem. Attached to the Arduino are an LM35 temperature sensor, two LEDs, a buzzer, an LCD, a GSM module, a gas sensor and a servo.

The other problem is with the servo. I tested the servo and it works fine but when the servo stops moving, it starts to shake. I do not know what the problem is.

You SIM800 module will pull 2Amps when its transmitting.  If your servo is also trying to overcome the inertia at the start of a movement it will pull 4+ times its normal running current.

A 9 volt battery will let you pull a couple of hundred milliamps.  So when the GSM transmits you system will shutdown.

You need a proper power supply or a battery pack that can put out these levels of peak current (3+Amps)


How to solve this "xpected primary-expression before ',' token" I'm new in this arduino world, and I'm having some trouble. I am programming something for a school assignment. The program gives an error, and my teacher also doesn't know how to solve it. Maybe someone can help me?

#include <CapacitiveSensor.h>
#define speaker

CapacitiveSensor   cs_2_3 = CapacitiveSensor(2,3);
CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4);
CapacitiveSensor   cs_2_5 = CapacitiveSensor(2,5);
CapacitiveSensor   cs_2_6 = CapacitiveSensor(2,6);
CapacitiveSensor   cs_2_7 = CapacitiveSensor(2,7);
CapacitiveSensor   cs_2_8 = CapacitiveSensor(2,8);
CapacitiveSensor   cs_2_9 = CapacitiveSensor(2,9);
CapacitiveSensor   cs_2_10 = CapacitiveSensor(2,10);

int s1;
int s2;
int s3;
int s4;
int s5;
int s6;
int s7;
int s8;

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

void loop()
{

  s1 =  cs_2_3.capacitiveSensor(3000);
  s2 =  cs_2_4.capacitiveSensor(3000);
  s3 =  cs_2_5.capacitiveSensor(3000);
  s4 =  cs_2_6.capacitiveSensor(3000);
  s5 =  cs_2_7.capacitiveSensor(3000);
  s6 =  cs_2_8.capacitiveSensor(3000);
  s7 =  cs_2_9.capacitiveSensor(3000);
  s8 =  cs_2_10.capacitiveSensor(3000);

  Serial.print("s1: ");
  Serial.println(s1);
  Serial.print("s2: ");
  Serial.println(s2);
  Serial.print("s3: ");
  Serial.println(s3);
  Serial.print("s4: ");
  Serial.println(s4);
  Serial.print("s5: ");
  Serial.println(s5);
  Serial.print("s6: ");
  Serial.println(s6);
  Serial.print("s7: ");
  Serial.println(s7);
  Serial.print("s8: ");
  Serial.println(s8);

  if (s1 > 500){
    tone(speaker,131);
   }
  else if (s2 > 500){
    tone(speaker,147);
   }
  else if (s3 > 500){
    tone(speaker,165);
   }
  else if (s4 > 500){
    tone(speaker,175);
   }
  else if (s5 > 500){
    tone(speaker,196);
   }
  else if (s6 > 500){
    tone(speaker,220);
   }
  else if (s7 > 500){
    tone(speaker,247);
   }
  else if (s8 > 500){
    tone(speaker,262);
   }

  if (s1<=500  &&  s2<=500  &&  s3<=500 && s4<=500  &&  s5<=500  &&  s6<=500 &&  s7<=500 &&  s8<=500){
    noTone(speaker);
  }
}

This:

#define speaker

defines "speaker" as nothing, an empty string. Then:

tone(speaker,131);

is translated into

tone(,131);

which makes no sense. The compiler expected to find an expression before the comma.


How to flash hex files from a micro SD card to an Arduino Nano using an SD card module? I want to flash a hex file stored in a micro SD card into an Arduino [Uno/Nano]. So far I can read and write to the SD card using Arduino.

Without modifying the bootloader, is it possible to flash the Arduino using micro SD card module?

No. Only the bootloader is allowed to write to the program flash.


Soldering Arduino Pro Mini's disaligned pins I have a couples of Arduino Pro Minis (original from sparkfun) that have those 4 disaligned pin. Unfortunetely, I need to use 2 of them, A4 and A5, because they are the I2C pins and I want to solder them onto a perf board.

Now, I really want to use headers and I do not want to solder any wire directly to it. I also do not want to add headers facing up on the board because I am trying to minimize space. Last, I am not willing to change Arduinos so please do not suggest me to use an Arduino Nano or Pro Micro.

So I would like to know if there is a way to connect those 2 pin to the perf board via headers or is there any alternative pins that I can use to connect and use the I2C interface.

That's indeed quite an problem.

If you don't mind losing 2 analog pin, you could solder some jumper-wires between A4 and A2; and between A5 and A3. Then you could connect your I2C lines to pins A2 and A3.

But you have to be careful to never set pins A2 and A3 to OUTPUT in your software. If you want to be super-duper safe, you could cut the trace from the header pins going to the TQFP-chip. See the image below.


Arduino stops loop randomly whenever a button is pressed I'm having a problem with this Arduino code.

So whenever I press the "button" in port 11, which is supposed to either reset the burglar alarm or stop it, the whole program stops (the void loop() function stops). The wiring is most likely not the problem, because I've tested it on multiple occasions with different codes. The button, too, works perfectly well as a button with different codes.

In the Serial port, it keeps printing "78005", which it should before the button is pressed, until when I press the button, at which it randomly breaks off printing (resulting in 78, 780, 7, 7800, or 78005 as the last line printed).

Can anyone explain why the arduino will behave in this way?

Thank you so much.

int button = 11;
int receiver = 12;
int buzzer = 13;
int frequency = 1000; // frequency of buzzer

bool keepAlerting = false; // toggles Alarm regardless of detected charge
int receiverVal = LOW; // value from port 12
int buttonVal = LOW; // value from button
int oldButtonVal = LOW;

int setupTime = 5000; // time the user has to close the box after toggling alarm

bool alarmOn;
int buttonMode = 0;
const int resetButton = 1;
const int stopButton = 2;
int buttonModeDecider = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(buzzer, OUTPUT);
  pinMode(receiver, INPUT);
  pinMode(button, INPUT);
  Serial.begin(9600);

  noTone(buzzer);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print("7");
  receiverVal = digitalRead(receiver);
  buttonVal = digitalRead(button);
  Serial.print("8");

  if(alarmOn == true){
    Serial.print("6");
    setAlarm();
  }

  Serial.print(buttonVal);
  Serial.print(oldButtonVal);

  if(buttonVal == HIGH && oldButtonVal == LOW){
    buttonModeDecider = 1 - buttonModeDecider;
    Serial.print("Toggled");

    if(buttonModeDecider == 1){
      buttonMode = resetButton;
      Serial.print("1");
    } else {
      buttonMode = stopButton;
      Serial.print("2");
    }

    switch(buttonMode) {
      case resetButton:
      {
        delay(setupTime);
        alarmOn = true;
        break;
        Serial.print("3");
      }
      case stopButton:
      {
        alarmOn = false;
        Serial.print("4");
      }
    }
  }
  Serial.println("5");
  oldButtonVal = buttonVal;
}

void setAlarm() {
  if(receiverVal == LOW || keepAlerting == true) {
    tone(buzzer, frequency);
    keepAlerting = true;
  }
}

A 10 Ohm resistor when switched to ground can cause the power supply to drop below the operating voltage of the Arduino. If you mean to have a pulldown resistor to ground use a 10K value instead.

Note that a 10 Ohm resistor across a 5V supply draws 0.5 Amps of current.


Serial not displaying sketch for MPU6050 I followed this tutorial on youtube: https://www.youtube.com/watch?v=M9lZ5Qy5S2s

Where he provided the code below. The problem I'm having is the serial monitor shows nothing. I tried changing the baud to 115200 and still nothing showed up. I'm using an Arduino nano.

Update: I wrote a Serial.print in each function (printing the name of the function), and I found it just printed up to "recordAccelRegisters" then stopped. Then I put a Serial.print after each line in the function, and it prints until the line
while(Wire.available() < 6);
Is this a problem with the while function or I2C?

Ok, so I reinstalled Arduino and got this message on the serial print with the I2C test:

"Scanning... I2C device found at address 0x69  ! done."

#include <Wire.h>

long accelX, accelY, accelZ;
float gForceX, gForceY, gForceZ;

long gyroX, gyroY, gyroZ;
float rotX, rotY, rotZ;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  setupMPU();
}

void loop() {
  recordAccelRegisters();
  recordGyroRegisters();
  printData();
  delay(100);
}

void setupMPU(){
  Wire.beginTransmission(0b1101000); //This is the I2C address of the MPU (b1101000/b1101001 for AC0 low/high datasheet sec. 9.2)
  Wire.write(0x6B); //Accessing the register 6B - Power Management (Sec. 4.28)
  Wire.write(0b00000000); //Setting SLEEP register to 0. (Required; see Note on p. 9)
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x1B); //Accessing the register 1B - Gyroscope Configuration (Sec. 4.4)
  Wire.write(0x00000000); //Setting the gyro to full scale +/- 250deg./s
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x1C); //Accessing the register 1C - Acccelerometer Configuration (Sec. 4.5)
  Wire.write(0b00000000); //Setting the accel to +/- 2g
  Wire.endTransmission();
}

void recordAccelRegisters() {
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x3B); //Starting register for Accel Readings
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6); //Request Accel Registers (3B - 40)
  while(Wire.available() < 6);
  accelX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
  accelY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
  accelZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
  processAccelData();
}

void processAccelData(){
  gForceX = accelX / 16384.0;
  gForceY = accelY / 16384.0;
  gForceZ = accelZ / 16384.0;
}

void recordGyroRegisters() {
  Wire.beginTransmission(0b1101000); //I2C address of the MPU
  Wire.write(0x43); //Starting register for Gyro Readings
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6); //Request Gyro Registers (43 - 48)
  while(Wire.available() < 6);
  gyroX = Wire.read()<<8|Wire.read(); //Store first two bytes into accelX
  gyroY = Wire.read()<<8|Wire.read(); //Store middle two bytes into accelY
  gyroZ = Wire.read()<<8|Wire.read(); //Store last two bytes into accelZ
  processGyroData();
}

void processGyroData() {
  rotX = gyroX / 131.0;
  rotY = gyroY / 131.0;
  rotZ = gyroZ / 131.0;
}

void printData() {
  Serial.print("Gyro (deg)");
  Serial.print(" X=");
  Serial.print(rotX);
  Serial.print(" Y=");
  Serial.print(rotY);
  Serial.print(" Z=");
  Serial.print(rotZ);
  Serial.print(" Accel (g)");
  Serial.print(" X=");
  Serial.print(gForceX);
  Serial.print(" Y=");
  Serial.print(gForceY);
  Serial.print(" Z=");
  Serial.println(gForceZ);
}

https://github.com/VRomanov89/EEEnthusiast/blob/master/MPU-6050%20Implementation/MPU6050_Implementation/MPU6050_Implementation.ino

Ground the AD0 pin. I thought the address should be set to 0x68 without this, but from what I've seen it fluctuates between 0x68 and 0x69. If you want the address to be 0x69 short the AD0 pin to 5V. I guess this would be useful if you need to use 2 MPU6050s with different I2C addresses without doing something in software. Haven't looked into that yet

Still, the I2C scanner for arduino may be useful for detecting the address/debugging: http://playground.arduino.cc/Main/I2cScanner


How does the build process in Arduino IDE work for ESP8266 How does the build process for esp8266 work in arduino IDE. Arduino ide uses avr-gcc to compile programs For atmel micro controllers. Does it uses same for compiling programs for esp8266?

Does it uses same for compiling programs for esp8266 ?.

No. It uses xtensa-lx106-elf-gcc. The compiler has to match the architecture.

Most of the build "process" (as in the actions that are taken) is the same, but executables specific to the EXP8266's XTensa core are used. There's also a few extra things in there, like building the (optional) SPIFFS image, etc.


How can I use attached interrupt on my project? Hi I have a coinslot project and connected with a fingerprint sensor it was stated in the ardiuno forum that it will work on pin 2 and 3 , but it is already used pins of the finger print sensor .
Coinslot signal is in pin 9 and the in2,3 is for the rx and tx of the fingerprint sensor.

If you can't rearrange the pins like Majenko suggests in the their comment, something you can do is is use pin change interrupts rather than the regular "external" interrupts.  On the UNO, these are available on all of the "digital" capable pins, which also includes most of the "analog" pins if you have an SMT UNO, or all of them if you have a DIP model.
NiceHood's PinChangeInterrupt library is modeled after the regular attachInterrupt function, so it should be familiar looking to you.  It's in the library manager; you don't need to get it from github.
NOTE: The O.P. opened a another question which seems to be this same thing, only with different context and specific code.  There I've given more details on what's outlined above but in relation to that that specific code in an answer there.


Write char array containing new line to SD card How do I a buffer (char array) containing new line character to SD card using SdFat?

I tried:

File myFile = SD.open("test.txt", FILE_WRITE)
myFile.write(buffer, BUFLEN)

but I get this instead:

0000 0000 0000 0000 0000 0000 0000 3337
3837 3838 3937 3035 2c20 2020 2031 2c20
2020 3531 0a33 3738 3738 3839 3730 352c
2020 2020 322c 2020 2035 310a 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000

If I use the normal method, then it seems that SdFat stop printing at the newline character:

myFile.print(buffer);

Note: the buffer containing data samples in fixed width csv format

3787889751,    1,   49
3787889752,   10,   49
3787889753,    1,   49

File.print() stops printing at a NULL character (ASCII 0) not a new line.  You can stick as many new lines as you like in a string and it will print.  Try this example

void loop ()
{
  Serial.print ("Hello\nMultiline\nPrint\n");
  Serial.print ("Hello\0Multiline\0Print\n");
}

File.write() writes binary data to a file, it will write BUFLEN bytes, even if you don't give it that many bytes.

Looking at the output from you hex editor your string ends with ... 2020 2035 310a which would be 3 spaces (20), 51 (35 and 31) and a new line (0A).  There is also a null (00) after that, but I can't tell how many because you have 0s to pad the output (or fill the file).

If you look further back in the output (3rd col, 3rd row) you can see another newline (0a33) so that proves its not new lines that is stopping your output.

Without your code we can't say whats wrong, but I agree with Mark that its not what you think it is.

To write data to a CSV file I would write each row of data into a struct and then hold those structs within a list.  Then have a function that iterated through the list and printed each record to the file.  That way you wouldn't need a buffer.  If it didn't have to be a CSV then you could just call

myFile.write (currentRecord. sizeof(StructRecord));


How to interface MPU9250 and NodeMcu? I am trying to send MPU sensor data to Pubnub IOT platform but not able to do it since there is some unknown problem. There is no error in code but following issue pops up in com port:-

It looks like sensor reading needs to be in JSON Format but no sure how to do it. I Just need it in raw imu sensor reading for now so how do i get it.

Here is the code:

#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP
#include "MPU9250.h"

const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
const char *pass =  "786110786";

const char * pubkey = "my key";
const char * subkey = "my key";

const char * pubchannel = "demo_keyset";
const char * subchannel = "demo_keyset";

MPU9250 IMU(Wire,0x68);
int status;

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(115200);

       Serial.println("Connecting to ");
       Serial.println(ssid);

       WiFi.begin(ssid, pass);
       while (WiFi.status() != WL_CONNECTED)
          {
            delay(500);
            Serial.print(".");
          }
      Serial.println("");
      Serial.println("WiFi connected");

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);

    while(!Serial) {}

  // start communication with IMU
  status = IMU.begin();
  if (status < 0) {
    Serial.println("IMU initialization unsuccessful");
    Serial.println("Check IMU wiring or try cycling power");
    Serial.print("Status: ");
    Serial.println(status);
    while(1) {}
  }
}

void loop() {
    // read the sensor
  IMU.readSensor();
  // display the data
  Serial.print(IMU.getAccelX_mss(),6);
  Serial.print("\t");

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "String(IMU.getAccelX_mss())");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

What do you guys think?

The error you're reporting is coming from your call to PubNub.publish(). You could have diagnosed the problem by taking outputting and inspecting what you were passing to it.

Your line:

PubNonSubClient *pclient = PubNub.publish(pubchannel, "String(IMU.getAccelX_mss())");

is not going to work. You're sending the string "String(IMU.getAccelX_mss())" to PubNub rather than the value of IMU.getAccelX_mss() as a String. Take the quotes off it:

PubNonSubClient *pclient = PubNub.publish(pubchannel, String(IMU.getAccelX_mss()));

If for some reason the number has to be returned as a string, the code would look like:

PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"" + String(IMU.getAccelX_mss()) + "\"");


Check if any of loop's insides returns 1 and hold it until the whole loop is 0 again I'm new to this, so, please, don't crucify me.
I have a function that checks if an entry in multilevel array is in a certain range. Using FOR loop I check the whole array with this function, which gives me true/false value for each record.
And now the problem:
I need to check if ANY entry in that loop returns true and hold it until every result of that loop is false again.
Any tips?
Thanks a lot.
There is my for loop:
  for(int i = 0; i < arrayTop; i++){
for(int j = 0; j < arrayDay; j++){
  for(int k = 0; k < arrayTime; k++){
    timeCompare(timeArray[i][j][k][0], timeArray[i][j][k][1], timeArray[i][j][k][2], timeArray[i][j][k][3], timeArray[i][j][k][4], timeArray[i][j][k][5], timeArray[i][j][k][6]);

    //Serial.print(i);Serial.print(j);Serial.print(k);Serial.print(" ");
    Serial.println(compareVar);

    if(i == 0){

      //set water switch
      if(compareVar == 1){
        waterOn = 1;
        Serial.println("Water ON");

        goto bailout;
      }
      else {
        waterOn = 0;
        Serial.println("water OFF");
      }
    }
    else if(i == 1){

      //set light switch
      if(compareVar == 1){
        lightOn = 1;
        Serial.println("Light ON");
        goto bailout;
      }
      else {
        lightOn = 0;
        Serial.println("light OFF");
      }
    }
  }
}

}
bailout:
and this is the called function:
//time compare with ON/OFF switch
int timeCompare(int hrOn, int minOn, int secOn, int hrOff, int minOff, int secOff, int timerSwitch){
  unsigned long int onTime = (hrOn*10000UL) + (minOn*100UL) + secOn;
  unsigned long int offTime = (hrOff*10000UL) + (minOff*100UL) + secOff;
  unsigned long int currentTime = (dt.hour*10000UL) + (dt.minute*100UL) + dt.second;

  if(timerSwitch == 1){
    if(onTime < currentTime && offTime > currentTime){
      compareVar = 1;
    }
    else {
      compareVar = 0;
    }
  }
 else if(timerSwitch == 0) {
    compareVar = 0;
  }

  //Serial.print("compare: "); Serial.println(compareVar);

}

First, you should really not use a global variable to get the result of your comparison function. That is only confusion and unnecessary complicated code. For that we have return values. So instead of setting the compareVar variable inside the timeCompare() function, you should just return the corresponding value. In the timeCompare() function replace
compareVar = 1;

with
return 1;

and
compareVar = 0;

with
return 0;

Then in your main code: As I understood, you only need compareVar in the for loops, so you could delete the globally defined compareVar and declare it directly before the for loops:
int compareVar = 0;

Now we can do the magic trick. We want to go through our for loops and get a result of 1, if for any of the elements timeCompare() returns 1. For that we just doing an OR operation:
compareVar = compareVar || timeCompare(timeArray[i][j][k][0], timeArray[i][j][k][1], timeArray[i][j][k][2], timeArray[i][j][k][3], timeArray[i][j][k][4], timeArray[i][j][k][5], timeArray[i][j][k][6]);

This is a boolean OR ||. In C++ zero is treated as false, while any other number is treated as true. We are starting with compareVar begin zero. When timeCompare() for the element returns also zero, it stays zero. If it returns 1, compareVar will become 1. If it returns 1 again, it will stay one. If it returns zero, it will stay zero.
So now you can check for compareVar after the for loops. It will be 1, if any of the elements gave you 1.
Similarly you could check for all elements returning 1, if you replace the OR || by an AND && operation.

Lastly I want to strongly discourage you from using goto. It ignores some important principles and you can easily create really bad code with it. Refer to questions like this one to read more about it. I would say, that in every case you have better ways than goto. Here it seems, that you simply want to go out of both loops. I would pack these loops into a function, so that you could simply use a return statement to get out of them.


Please explain this adafruit image for connecting a DS1307 RTC https://learn.adafruit.com/assets/3813

I understand that analog 4 and 5 are SDA/SLC, isn't the picture also showing 5v and GND being plugged into two analog pins? Does that work?

I have it wired up to the actual 5v and GND, but it would be convieniet to be able to stack the RTC like they show in the picture

It's written in the tutorial

  If you set analog pin 3 (digital 17) to an OUTPUT and HIGH and analog pin 2 (digital 16) to an OUTPUT and LOW you can power the RTC directly from the pins!


Acrylic enclosure for Arduino I've been browsing Aliexpress and eBay for decent Arduino enclusures, but I've found out they are even pricier then boards themselves.

Then I've realized that there are multiple firms that offer cheap laser cutting - I can buy 1 sq.m acrylic sheet and order cutting multiple parts of boxes at once.

Obviously I am not the first one who came up with this idea. Has anyone seen downloadable vector layouts I can use as something to start from? Thanks.

Making your own is quite possible, especially if you own a router (or even better a router table). You need a V shaped 90 degree router bit, a tube of proper perspex glue and some acrylic sheet. The glue is hard to find, but plastic sign manufacturers generally will sell it. Unless you are a DIY expert, I suggest the gap filling type of glue rather than the watery product that only fills perfectly matched surfaces. Try searching Youtube on "acrylic box making". There are several videos. My first two efforts were pretty bad, but the last couple are fine, and are of course exactly the right size.


Is `millis()` affected by long ISRs? I have a project that uses timers and interrupts frequently. A lot of CPU time is spent handling ISRs over an extended period of time.

Would this affect code inside the main loop that relies on the millis() function since a significant amount of time is spent processing the ISRs?

After some digging around in the core, it seems like Arduino updates millis() with a 8 bit timer: it uses overflow with a prescaler value of 64. In simpler terms, it has it set up so a certain piece of code (the ISR) is run approximately once per millisecond on a 16MHz system (and proportionately less frequently on slower clocked systems).

When that ISR is ran, it increments a variable that is used by the millis() function.

So, even if some non-interruptable code is being ran for a fraction of a millisecond, it won't matter since the bit for that interrupt vector will still remain set.

However, there is a problem when the ISR is ran less often than it should be triggered. This may be a result of using noInterrupts() for an extended period of time or when too many other interrupts are being ran and there is not enough CPU for all of the tasks. If a lot of the other ISRs have a higher interrupt priorities, it is possible that the code for the millis() may never be ran. In this case, you would have more serious issues than this, but it is something to keep in mind when you're writing code.

The general rule of thumb of ISRs still apply: keep it short!!!

Note: if you require extreme accuracy, the built in function isn't the best choice. A RTC is a good idea for long term time keeping.


Adafruit IO example won't compile, library required is correct version I have Arduino IDE 1.8.5 installed, and also Adafruit IO Arduino 2.6.0 and Adafruit MQTT Library 0.20.0.

With the Adafruit IO lib comes a set of examples, and I wanted to use example adafruitio_07_digital_out as a starting point for a project on an Adafruit HUZZAH ESP8266.

It won't compile. I get

#error "This sketch requires Adafruit MQTT Library v0.17.0 or higher. Please install or upgrade using the Library Manager."

which I find strange. I've tried installing 0.17.0 instead of 0.20.0, but that doesn't help.

Is there anything I can do to get this to work? The suggested solution of using the Library Manager to install the required package is obviously not working.

It turns out that the problem was that I had installed the Arduino IDE through the windows app store. Uninstalling it, downloading it through a browser, and using the same code works just fine.


The Arduino IDE can’t find my Arduino Uno My Arduino has all of its LEDs on. The Rx, Tx and L LEDs are all on and my computer can’t see it (it's an SMD edition).

It can have many reasons, but you can try the following:

First time use?

Check if you need to install a special driver for CH340

Environment/Software problems

Try another USB port
Change USB cable
Restart Arduino IDE
Restart computer
Reinstall Arduino IDE

Hardware problems

Test using another Arduino
Test using another computer/laptop
Replace USB cable
The Arduino is (partly) broken, nothing much to do here


Voltage issue on an esp32 wvroom 32D development board I have an esp32 wroom 32 dev board. I'm running into power issues and I'm not sure what's going on.

When I try to upload sketches the uploads fail if I have any jumpers running to the 5v or 3.3v pins which is weird.

Also, when I have nothing plugged into the board other than the usb cable and try to measure voltage across the ground and power pins I get 1.5v from the 5v pin and 0 from the 3.3 pin

This is a brand new out-of-the-static-bag board and I'm having the same issue with another board of the same type.

I feel like there's something I'm missing. Any ideas?

Try measuring the voltage against a different ground pin? I had a similar problem and discovered the pin next to the 5v input pin wasn't actually ground. Not sure why this would affect sketch uploading though..


Using an array as a queue I recently created a state machine for my latest Arduino project. It is a simple LED control, but it has many different modes and functions. I created a template for my state machine so I can use it in the future, but I am looking to take it to the next level. Here is a copy of the current template for reference:

/*Setup Variables here*/
int nextState;
int currState;

/*Fill enum with all case names*/
enum cases{

  init;
  idle;
  case1;
  case2;
  leave;

};

/*Begin Program*/
void setup(){
  Serial.begin(9600);
  currState = init;
}

void loop(){
  switch(currState){

    case init:
      /*Prepare program here*/
      nextState = idle;
      break;

    case idle:
      if (input1){
        nextState = case1;
      }else if (input2){
        nextState = case2;
      }else{
        nextState = idle;
      }

    case case1:
      //Code for case1 here
      break;

    case case2:
      //Code for case2 here
      break;

  }

  currState = nextState;
}

I am trying to make a Queued State Machine (QSM). This means that instead of a single variable nextState, I can add several states to be executed. Is the best way to do this an array? I have not found much in my research about how to add and remove elements easily, so if this is the best way, could you point me towards a good tutorial on these types of array functions?

Thanks in advanced for all the help!

Have an array with fixed size, and have two indexes. One pointing to the first/current item in the queue, the other to the last item in the queue.

(It actually better/easier to have the second index point to where the next item has to be written)

To add an item to the queue:

Check that that the queue isn't full (second index is the same as the first)
If not write to second index.
Increment second index, and modulo array/queue size, so it wraps around.

To read from the queue

Read value at the first index
Increment first index, modulo array/queue size


How to package a 16 bit integer to send it with serial.write? I am trying to display the values i get from reading a potentiometer (0-1023) in the program called 'processing'.

when I just use Serial.write(integer) and display the value on a line graph in 'processing' the line will max out at 256 and loop back around to 0 as i vary the potentiometer.

I understand that this is because the serial.write can only write in bytes(8 bits) so I would need to package the 16 bit integer into 2 bytes.

i was considering using a union but as you can probably guess i am very new to arduino so i haven't been able to make that work.

here is the code i have tried:

union Data{  uint16_t now; } data;

void setup() {   // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(A1, INPUT);

}

void loop() {   // put your main code here, to run repeatedly:
    uint16_t sensorVal = analogRead(A1);
     union Data data;

    data.now = sensorVal;

    Serial.println(data.now);

    //Serial.write(sensorVal);
    delay(10); }

You need to send the uint16_t as the two the individual bytes it is composed of, one at a time, in whatever order your Arduino code and the code on the PC agree on: (MSB first, aka, big-endian; or LSB first, aka little-endian).

Since it would be possible for the two devices to get out of sync, you may also want to package up the two bytes with a third, or "start-byte". Pick some fixed value (such as 0xCC) that has a couple of its MSbits set, then the MSB, then the LSB. Your receiver can know to look for that fixed value, then the MSB (which it knows can't have those high bits set because the analog data is only 10-bits), then the LSB (which could have any value).

The PC should only accept a three-byte packet when it has received one that fits that scheme. Otherwise it waits for another 0xCC (or whatever value you choose), collects two more bytes, and tries again.


String does not name a type I'm using Arduino IDE for ESP32 WROOM board. I am testing the OTA feature with the ESP32httpUpdate library. I am using the example sketch of the library with the name httpUpdate.ino
However, as soon as I change the update url with a string pointer that I declare globally, it is throwing a compile error that String does not name a type. Any ideas?

/**
 * httpUpdate.ino
 *
 *  Created on: 27.11.2015
 *
 */
String* FIRMWARE_UPDATE_VERSION = "1000";

String* updateURL = "XYZ.php";

#include <Arduino.h>

#include <WiFi.h>

#include <HTTPClient.h>
#include <ESP32httpUpdate.h>

#define USE_SERIAL Serial

void setup() {

    USE_SERIAL.begin(115200);
    // USE_SERIAL.setDebugOutput(true);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    WiFi.begin("SSID", "PASSWORD");

}

void loop() {
    // wait for WiFi connection
    Serial.println("Yolo");
    if((WiFi.status() == WL_CONNECTED)) {

        t_httpUpdate_return ret = ESPhttpUpdate.update(updateURL, FIRMWARE_UPDATE_VERSION);

        switch(ret) {
            case HTTP_UPDATE_FAILED:
                USE_SERIAL.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
                break;

            case HTTP_UPDATE_NO_UPDATES:
                USE_SERIAL.println("HTTP_UPDATE_NO_UPDATES");
                break;

            case HTTP_UPDATE_OK:
                USE_SERIAL.println("HTTP_UPDATE_OK");
                break;
        }
    }
}

String is included by Arduino.h. Before #include <Arduino.h> String is not defined. Move #include <Arduino.h> to the top of the file or remove it. If you remove it, the Arduino builder adds it.


storing 600 unsigned int values in an array and find minimum and maximum values I am reading an ASCII serial data values from a sensor and storing it in an unsigned integer variable. The values are ~45000 to 50000 range. I need to store 600 values and then find the minimum and maximum. after 600 values reached the oldest value is being replaced with the new value. The array size required is 600 which is approx.1200Bytes of the size of storage. I'm using Atmega 2560. I would like to know is it possible to store all 600 values in SRAM or do I need to use EEPROM memory?

The Atmega 2560 has 8K of static ram, more than enough for your 1200-byte array.
Reading-, and especially, writing EEPROM are very slow, and EEPROM has a rather limited lifetime-number-of-write-cycles, so it is not a good candidate for active use but rather for storing data that change infrequently and need to survive a power-down. These would typically per-system preferences, or data that needs to be stored to let the system resume at the next power-up, where it had left off when the power went down. This latter function requires that the system store enough power (capacitor or tiny battery) to keep it running long enough to sense the main power failing and still have run-time enough to write to EEPROM.