Troubleshooting WS2812b LED strip with toggle on/off button I have a very rudimentary setup with an arduino nano, an LED strip, a pushbutton and a resistor.
I was trying to use the pushbutton as a toggle, using this code
#include <stdio.h>
#include <stdlib.h>
#include<FastLED.h> // header file

#define NUM_LEDS 14 // number of led present in your strip
#define DATA_PIN 12 // digital pin of your arduino

CRGB leds[NUM_LEDS];

const int button = 2;            // GPIO 8 for the button
int status = false;

void setup() {
  //Serial.begin(9600);
  pinMode(button, INPUT);         // define button as an input
  pinMode(DATA_PIN, OUTPUT);           // define LED as an output
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}

void loop() {
  if (digitalRead(button)==true) { // if button is pressed
    // flip status
    //Serial.println("Changing status");
    status = !status;
    //Serial.println(status);
    toggle(status);
  }

  while (digitalRead(button) == true) {
    //Serial.println("while loop");
    delay(50);
    //Serial.println(status);
  }//

  delay(50);
} // begin again

void toggle(bool status) {
  if (status == true) {
    for (int i = 0; i < NUM_LEDS; i++) {
      leds[i] = CRGB::White;  //set the all leds to white
    }
    FastLED.show();
  } else {
    for (int i = 0; i < NUM_LEDS; i++) {
      leds[i] = CRGB::Black;  //set the all leds off
    }
    FastLED.show();
  }
}

This is my circuit

I am powering this from a battery (PNY model 12200, 2200 mAh, Output 5 V=1A) via USB into the arduino board. I am having some issues. Mainly, the lights would go on by themselvs after a while, maybe not full power but still would be on. Not sure where the problem is, any hints appreciated.
I also sometimes get the lights turned off, maybe I'm feeding current into the wrong place and a safety mechanism either on the arduino or the battery stick turns everything off to protect itself?

The manual for the T2200, which I think is what you're referring to, says:

Note: If the PowerPack does not automatically power on when a device
is connected press the power button. The PowerPack will turn off after
90 seconds when there are no devices connected.

This is a common feature for USB battery banks meant for charging phones and similar devices.  It probably shuts off when the current drops below some set limit, say 50mA for more than 90s.  But it could also be looking every 90s for the average current over the course of 10ms.  They just don't say.  Given their description it sounds likely that it regularly turns on for some short time to probe for a load.  All in all, not knowing the specifics of this may drive you nuts.  Part of the thing to keep in mind is that someone using this thing to charge a cellphone wouldn't necessarily notice or care if it cut in and out every few seconds.  If you want to use this to power an Arduino it's worth getting a good handle on how it behaves through some experimentation.  Some of these power banks do have a way to disable their load detection and auto-shutoff feature; I did not see anything about that for this model.
The Nano, the official one anyway, has a 500mA PTC polyfuse on the USB VBUS ("5V").  Your code says #define NUM_LEDS 14.  The WS2812b LEDs use something on the order of 50mA each at max output.  You should probably measure what you're actually drawing, with the intensity you are commanding them to be, to be sure you're a good margin below 500mA.  If you are in fact using 14 of them, and if it's possible that all can go full brightness, then you are perhaps trying to use something like 735mA, quite a bit above 500mA.  You way find that it's necessary to route 5V around your Arduino to your LED strip, ideally through its own over-current protection.
Each time you power on or reset your project there's going to be some time before the sketch sets the pin connected to WS2812 data signal to output and some defined level.  It may be a good idea to add an external pull resistor on the LED data signal, probably to GND, so that during power-up and reset the LED strip data signal is not picking up noise and trying to interpret it as color data and changing your load on your power source in the process.  Having the powerbank potentially turning your project on and off gives extra opportunities for this to happen.  If you trip the polyfuse, either by commanding the LEDs to draw too much or having the floating data pin do likewise, the voltage on the Nano side of it will drop.  When the voltage drops it may trip the AVR microcontroller's brownout detector, which in turn will reset it the AVR, again bringing about a floating data pin on your LED strip.


MPU6050 hanging/freezing I am really short of interrupt pins on my Arduino because I have a project that already uses a lot of Arduino pins and to read DMP data from MPU6050 you always have to use an interrupt pin. I searched A LOT in the internet and many people says it's impossible to retrieve DMP data without interrupt pin. Some people also said the only way to do that would be if I could reverse engineer the MPU6050 code (which I don't know how to do).

But today, playing with MPU6050 I could finally get all of its DMP data without the interrupt pin, you just have to connect 4 pins (VCC, GND, SCL and SDA). Upload the code below to your Arduino and see that it works!

#include "MPU6050_6Axis_MotionApps20.h"
MPU6050 mpu;
uint16_t packetSize;
uint16_t fifoCount;
uint8_t fifoBuffer[64];
Quaternion q;
VectorFloat gravity;
float ypr[3];

void setup() {
  Wire.begin();
  TWBR = 24;
  mpu.initialize();
  mpu.dmpInitialize();
  mpu.setXAccelOffset(-1343);
  mpu.setYAccelOffset(-1155);
  mpu.setZAccelOffset(1033);
  mpu.setXGyroOffset(19);
  mpu.setYGyroOffset(-27);
  mpu.setZGyroOffset(16);
  mpu.setDMPEnabled(true);
  packetSize = mpu.dmpGetFIFOPacketSize();
  fifoCount = mpu.getFIFOCount();

  Serial.begin(115200);
}

void loop() {
  while (fifoCount < packetSize) {
    fifoCount = mpu.getFIFOCount();
  }

  if (fifoCount == 1024) {
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
  }
  else {
    if (fifoCount % packetSize != 0) {
      mpu.resetFIFO();
    }
    else {
      while (fifoCount >= packetSize) {
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        fifoCount -= packetSize;
      }

      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetGravity(&gravity, &q);
      mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

      Serial.print("ypr\t");
      Serial.print(ypr[0] * 180 / PI);
      Serial.print("\t");
      Serial.print(ypr[1] * 180 / PI);
      Serial.print("\t");
      Serial.print(ypr[2] * 180 / PI);
      Serial.println();
    }
  }
}

There is only one problem: Intermittently the Arduino hangs in the getFIFOBytes function for no reason. I am pretty sure it's a bug because when you call too many times getFIFOBytes for some reason the Arduino freezes.

I added a mpu.resetfifo after de mpu.dmpGet.... lines.
Since then 2 different systems work for at least 5 hours and with the original interupt pin attached


LCD 16*02 I2C shield only shows first character printed I have an I2C LCD screen provided with a Sunfounder kit and certainly built by DFRobot or such a constructor (there is nothing written on the LCD), and an Arduino Uno R3 copy.

My issue is when I use lcd.print() to write a string on the LCD, only the first character of the string is printed. I can only print on other positions by using setCursor but only one character at a time.

I tried to change libraries (https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library, the one supplied with the LCD...), It always behaves the same!

For example, here's a very simplistic program which exhibits this behavior:

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);
// set the LCD address to 0x27 for a 16 chars and 2 line display
void setup() {
  lcd.init();
  lcd.backlight();
}

void loop() {
  lcd.print("write");
  delay(1000);
  lcd.setCursor(10, 0);
  lcd.print("p10");
  lcd.setCursor(0, 1);
  lcd.print("0, 1 write");
  if((millis() / 1000) % 5 == 0) {
    lcd.clear();
    delay(1000);
  }
}

I end up with something like:

w      p
0w

On the screen (before the clear() occurs of course).

Instead of something like:

write  p10
0, 1 writewrite

The lcd itself was ok some time ago. The only thing I could think is I recently updated to Arduino 1.6.6. Can it be a bug in the compiler?

The hello world from DFRobot also doesn't work properly (first char only, again) (please note to make it display something with my LCD I have to change the address from 0x20 to 27).

That's definitely a bug appeared in 1.6.6.
For reference, see
https://blog.arduino.cc/2015/11/03/arduino-ide-1-6-6-released-and-available-for-download/#comment-278766
https://forum.arduino.cc/index.php?topic=359652.0
http://forum.arduino.cc/index.php?topic=357312.msg2476987#msg2476987

Last link seems to provide a solution, by a updated version of LCD I2C lib : https://github.com/marcoschwartz/LiquidCrystal_I2C (not yet tried).

The 1.6.6 is a bit messy according some people, but the I2C lib too ;). So the question is : where should it be fixed ?


Checking for multiple values in IF separated by commata My code is:

if ((minute == 31) && (hour == 4, 6, 9, 11))
{
  digitalWrite(8, HIGH);
}

I want to turn on the LEDs when it is exactly

04:31,
06:31,
09:31,
11:31

However, the code above doesn't work.
Might be the multiple values the reason for this?

Yes, the list of values 4, 6, 9, 11 does not mean what you think it does.

if ((minute == 31) &&  ((hour == 4) || (hour == 6) || (hour == 9) || (hour == 11))) {
    digitalWrite(8, HIGH);
}


Blink Adafruit_NeoPixel I wish to blink all the strip. In the code below it just blink the first LED, how can I fix it?

Code:

#include <Adafruit_NeoPixel.h>

#define PIN 6
#define NUM_LEDS 24

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show();
}

void loop() {
  strip.setPixelColor(0, 255, 255, 255);
  strip.show();
  delay(1000);
  strip.setPixelColor(0, 0, 0, 0);
  strip.show();
  delay(1000);
}

The first argument of setPixelColor is is the number of the led. In your case 0, so the first led.

Instead use a for loop to set all the leds from 0 until (excluding) 24 (which is stored in NUM_LEDS).

void loop()
{
  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, 255, 255, 255);
  }
  strip.show();
  delay(1000);

  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, 255, 255, 255);
  }
  strip.show();
  delay(1000);

To make the code better (shorter, but more important more maintainable, and reducing code duplication), create a separate function:

void loop()
{
  setLeds(255);
  setLeds(0);
}

void setLeds(int intensity)
{
  for (int led = 0; led < NUM_LEDS ; led++)
  {
    strip.setPixelColor(led, intensity, intensity, intensity);
  }

  strip.show();
  delay(1000);
}


Using C# Program to Interpret Keystrokes I am in the process of developing an Arduino application that can read keystrokes from a PS/2 keyboard. I was wondering if it would be possible to upload a C# program onto the Arduino to interpret the keystrokes from the keyboard and write an Arduino program to perform operations based on the keystrokes.

The answer is actually, surprisingly, yes! C# requires .NET CLR for execution, I had assumed that .NET exists only in microsoft desktop land, but it has in fact been ported to microcontrollers and released open source as .NET micro, it can even run baremetal with no OS.

However this is not possible on an 8 bit regular arduino, it requires one of the larger 32 bit models. There is a prebuilt clone that has the .NET micro CLR framework ported to it on an STM32F4 cpu called the netduino

Unfortunately the footprint for .Net Micro is too large to run on a regular 8bit arduino and probably hasn't been built for 8bit systems. It is possible with the arduino Due (in theory) and on other micrcontroller platforms that support .NET micro to run C# code outside of the windows platform.


Passing non-static member function using bind I'm using the GxEPD2 library to communicate with an E-Paper display. I now wanted to use the drawPaged method of this library with an object display.

I also have written my own class from which I want to print stuff on the display.

Here's the relevant code for the MyClass.h:

class MyClass{
    //some variables and methods
    void drawClass(); //this is public
    void drawClassCallback(const void* v1); //this is private
    //    this is actually a uint8_t --^
}

And here's the MyClass.cpp:

void MyClass::drawClass(){
    //some display preparation
    uint8_t var; //A variable to pass information from the callback to this method since it is needed later
    display.drawPaged(std::bind(&MyClass::drawClassCallback, this, &var));
    //some code where I need var with info from the callback
}

I'm getting the following error:

  no matching function for call to 'GxEPD2_BW::drawPaged(std::_Bind_helper::type)'

  note: candidate: void GxEPD2_BW::drawPaged(void ()(const void), const void*) [with GxEPD2_Type = GxEPD2_290; short unsigned int page_height = 296u]
       void drawPaged(void (drawCallback)(const void), const void* pv)

I've also tried display.drawPaged(std::bind(&MyClass::drawClassCallback, this, std::placeholders::_1), &var) without success.

I've stumbled upon this post already, however the solution presented there (and the one used above) does not work in this case.

Why is that?

In your MyClass example, the drawPaged() call is given only a single argument, while according to the library, it needs two:
void drawPaged(void (*drawCallback)(const void*), const void* pv)

The first argument is the function pointer (or the one wrapped by std::bind!). The second argument seems to be some data that will be passed on to that function. (according to the [linked API)
The error actually explains it, it suspects that you are trying to call void GxEPD2_BW::drawPaged(void ()(const void), const void*). Hence it mentions this as a candidate.
What you need to do is something like this:
display.drawPaged(std::bind(&MyClass::drawClassCallback, this, std::placeholders::_1), &var);

std::placeholders::_1 is the placeholder that represents the var argument that will be passed on when it is called.


What are (or how do I use) the power saving options of the Arduino to extend battery life? For solar & battery powered projects, decreasing power consumption is a necessity.

I know a little bit about using a timer and interrupt to put the microcontroller into sleep when it isn't doing anything.

I have also read that you can disable some peripherals to further save power.

Here is a page explaining these: Power Saving Techniques

My question:

What other techniques are there to save power?
Are there any libraries that make using these AVR features easier?

Note: I wanted to point out that, even though my answer was accepted, the reader (you) should really read Anindo's answer first if you really want to save energy with any Arduino board. Once you address those items in your design, then you should read my answer and worry about how to set the MCU into low power mode.

Having said that, there are several techniques to make an Arduino save power. I'll list a few and then point you to a page that explains them all in more detail.

While the controller isn't doing anything important (between one read of a sensor and the next, for example), you can put the controller into one of the sleep modes below, with the command set_sleep_mode (SLEEP_MODE_PWR_DOWN). Next to each mode is the approximate power consumption of each mode.

SLEEP_MODE_IDLE: 15 mA
SLEEP_MODE_ADC: 6.5 mA
SLEEP_MODE_PWR_SAVE: 1.62 mA
SLEEP_MODE_EXT_STANDBY: 1.62 mA
SLEEP_MODE_STANDBY : 0.84 mA
SLEEP_MODE_PWR_DOWN : 0.36 mA

Disable brown-out detection (the circuitry that turns off the controller when low voltage is detected).
Turn off ADC (analog to digita conversion)
Use the internal clock

Then, when you put the controller to sleep, you need to use one or more mechanisms below to wake up the controller and do something with it:

Wake up with a signal
Wake up with a timer

This is a summary I made from -

Nick Gammon's article: Power saving techniques for microprocessors.

That article applies mostly to ATmega328P, but the technique applies to other Arduino compatible controllers as well. As TheDoctor said well, you will need to check the datashet to make sure your controller suports any of those techniques and how to do it more precisely.


How can I compare two serial port readings on Arduino Mega? I'm writing some code that compares information from two Arduino Unos by an Arduino Mega 2560. The problem that I'm having is that when I read the information coming in through Serial1 and Serial2 on my if statements, I get both inputs out on my serial monitor for the Mega, but if I try to compare them after I have read them it comes out not working the way it is intended. I don't know if I might be missing some syntax on my code or if I'm doing this wrong but I would appreciate any help I can get.

byte inData;

byte inDataTwo;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);

  while (!Serial)
  {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}

void loop()
{
  if (Serial1.available()>0 )
  {
      inData = Serial1.read();
      Serial.print(char(inData));
  }
  if (Serial2.available()>0)
  {
    inDataTwo = Serial2.read();
    Serial.print(char(inDataTwo));
  }
  if(inData == inDataTwo)
  {
    Serial.print("true");
  }
  else
  {
    Serial.print("False");
  }
}`

I think your code is implemented wrong in general. Even if it worked "like intended" it would not behave like you might want it to.

The first problem is, that you are polling for bytes that are received asynchronuously. That means that  two byte sequences must not only be equal, they must also be sent "at the same time" if they should pass your comparison test. As the atmega will loop() very fast, there is only very little tolerance in timing.

Secondly, the variables you write received values to are not reset, meaning that once they have the same value they will pass the if statement until another byte has been received. Actually they aren't initialized and therefore will be 0 at the very beginning. So I wonder why you don't get your Serial interface flushed with true. Is this actually the entire code?

As a solution I suggest accumulating received bytes into a buffer and waiting for a soecific termination byte (often /n). If a termination character has been received, perform the comparison on that buffer.


Battery level indicator In this arduino project we have 3 Leds that lights up according to the voltage of a battery but when we the voltage read is very close, it results into an uncontrolled switching between  Leds  can any one help me ?

int Batpin = A0;
int Led1  = 12;
int Led2  = 11;
int Led3 = 10;

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  pinMode(Led1,OUTPUT);
  pinMode(Led2,OUTPUT);
  pinMode(Led3,OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  volt ();
}

void volt(){
int sensorVal = analogRead(Batpin);
float voltage = sensorVal * (5.0/1023.0);

 Serial.print(" volt: ");
 Serial.println(voltage);
 if (voltage < 3.80){
     digitalWrite(Led1,HIGH);
  }

   if (voltage > 3.80 && voltage <= 4)
   {
      digitalWrite(Led1,LOW);
      digitalWrite(Led2,HIGH);
   }

   if (voltage > 4)
   {
      digitalWrite(Led1,LOW);
      digitalWrite(Led2,LOW);
      digitalWrite(Led3,HIGH);
   }
   delay (1000);
}

What you could do with for this is hysteresis.

Instead of simple threshold ranges (0 < A < B < C < 5) you instead need to watch the voltage over time and decide what it is doing compared with what it has done in the past.

You need to keep a record of what state the voltage is in at any one time - That is, is it in band A, B or C in the thresholds above. You then need a second set of thresholds, A1, B1 and C1.

The two thresholds overlap:

If, for example, the voltage rises from between A and B to between B1 and C1 then you switch states to the BC state.

If it falls from between B1 and C1 to between A and B then you switch to the AB state.

Basically, if the voltage rises, it needs to transition between the lower set of thresholds to the upper set of thresholds to register as a change. If it drops it has to transition between the upper set of thresholds and the lower set of thresholds to register as a change.

So, in pseudocode,

if (State == 0A && Voltage > A1 && Voltage < B1)
    State = AB
    Turn on LED 1

if (State == AB && Voltage > B1 && Voltage < C1)
    State = BC
    Turn on LED 2

if (State == BC && Voltage > C1)
    State = C5
    Turn on LED 3

if (State == BC && Voltage < B && Voltage > A)
    State = AB
    Turn on LED 2

if (State == AB && Voltage < A)
    State = 0A
    Turn on LED 1

if (State == C5 && Voltage < C && Voltage > B)
    State = BC
    Turn off all LEDs

It's up to you to decide what a good level of separation is suitable for your system.


Can ZigBee API and ZigBee AT work together in the same network? I'm currently trying to make 3 arduinos talking to each other with ZigBee, and it's kinda working.
But I currently use AT mode on the Bees and it's a little bit harsh when I have to switch the destination address in the Coordinator of the network (1 Coordinator and 2 Routers)

Can I put the Coordinator in API mode (to make it easier to switch addresses with xbee-api for Arduino) but still be able to communicate with the AT routers and be able to send/receive data from them?

Thanks for your answer :)

My question has been answered on Stack Overflow, if you ask

https://stackoverflow.com/questions/28765288/can-zigbee-api-and-zigbee-at-modules-work-together-in-the-same-network


MIDI connectors / Diodes Does anybody know if the following MIDI DIN connectors will fit in a breadboard?

(or in general with 'generic' electrical components?)

MIDI DIN

And the same for:

Diodes to be used for MIDI in.

Breadboards use a 2.54 mm (0.1") grid. The PCB footprint on that link uses a nominal 2.5 mm grid, which is essentially the same:

However, those pins are rather large; it's possible that you need to rotate some pins by 90° (with pliers and brute force) to make them fit into your breaboard's holes, or that they do not fit at all. And even if they fit, they can ruin your breadboard.
You might need to file them off.

Consider using a panel-mount MIDI jack instead (which would require soldering, or leads with test clips):

(search for "5 pin DIN female jack")

The MIDI specification recommends a 1N914 diode, but that is only because it was written over thirty years ago. The 1N4148 is much more common now, and has the same characteristics. But this diode is used only as reverse voltage protection for the optocoupler's LED, so you can use any random fast switching diode.

As for the optocopler (which you didn't mention, but I'll throw in my two cents worth anyway): the PC900 was discontinued, and the 6N138 is slow. Use either the H11L1 (of which the PC900 was a clone) or the 6N137; both work best with a 1 kΩ pull-up resistor.


HC-SR04 pulse at multiple angles I have a HC-SR04 sensor mounted on a stepper motor, mounted on a car.
The idea is this:

The car moves forward with the ultrasonic sensor facing the front
If the sensor reads a small distance the car do the following:

Stop
Turn the sensor to the left and get a new distance
Turn the sensor to the Right and get a new distance
Drive slightly backward
The car turns the to direction the distance was the highest
Drive forward again

I think I must have wrongly understood how the echo/ultrasonic sensor works. Because when I read values to the left and right, it will always return zero, but reading values when driving forward works very well.

Below is the relevant code

//Trigger
void triggerEcho(){
  digitalWrite(echoTrigPin,LOW);
  delayMicroseconds(5);
  digitalWrite(echoTrigPin,HIGH);
  delayMicroseconds(10);
  digitalWrite(echoTrigPin,LOW);
}

//Trigger, receive and calculate distance (cm)
long getEchoDistance(){
  triggerEcho();
  pinMode(echoRecPin, INPUT);
  long echoDuration = pulseIn(echoRecPin, HIGH);

  return echoDuration / 58;
}

void loop(){

  long distance = getEchoDistance();

  //If front obstacle is encountered
  if((distance < 5) && (distance != 0)){
      carStop();
      servo.write(180);                     //turn echo sensor left
      delay(250);
      long distanceL = getEchoDistance();   //trigger and read sensor value
      servo.write(0);                       //turn echo sensor right
      delay(250);
      long distanceR = getEchoDistance();   //trigger and read sensor value

      //this will always show distance as 0
      Serial.print("  LEFT :"); Serial.print(distanceL); Serial.print("\n");
      Serial.print("  RIGHT:"); Serial.print(distanceR); Serial.print("\n");

      carDriveBackward(135, 1.185, 1.0);     //drive backwards
      delay(250);
      if(distanceR>distanceL)                //turn in the direction that was furthest
        carTurnRight(100,1250);
      else
        carTurnLeft(100,1250);
      carStop();
      servo.write(90);                        //face sensor forward
      delay(250);
    }
    else
      carDriveForward(135, 1.185, 1.0); //R - L
}

I bet something is wrong with how I'm implementing the triggerEcho() and getEchoDistance(). I excluded anything on the wiring and pins, as the reading of the distance is very correct when reading the facing the front.

I doubt you have misunderstood the way ultra sound works.  You send a pulse and then go quiet waiting for a reply.  The time it takes to send the pulse is the minimum distance you can detect things at.

If you are not getting returns left and right then it could be there is nothing there or turning the head is breaking a connection.

Firstly jack the vehicle up off the floor so it doesn't go anywhere.
Place a solid object (book) in front of the vehicle and make sure it detects it.
Now place the same object to the right of the vehicle, do it detect it?
Stop the US sensor when it is looking right (by killing the power) and check that it is looking horizontally.  Check the connections, are they being pulled loose?

Your code looks fine, you US works forwards so I think it is a mechanical issue with your car.


Getting different results from function. How to retrieve values correctly? Trying to implement PI controller in function.
Already worked for one controller.
However, for more than one controller, the results are shifting.
Suppose to get same values in the following code.
Any help I appreciate it.

float r_in_1 = 10.00;
float y_out_1 = 5.00;

float r_in_2 = 10.00;
float y_out_2 = 5.00;

float r_o_1;
float y_o_1;

float r_o_2;
float y_o_2;

float vi_1 = 0;
float vi_2 = 0;

void setup() {

 Serial.begin(9600);

  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

r_o_1 = pow_2(r_in_1);

r_o_2 = pow_2(r_in_2);

y_o_1 = pow_2(y_out_1);

y_o_2 = pow_2(y_out_2);

vi_1 = PI_1(r_o_1, y_o_1);
vi_2 = PI_1(r_o_2, y_o_2);

Serial.print(vi_1);
Serial.print(',');
Serial.println(vi_2);
delay(1000);

}

float pow_2(float x){

float z;

z = x*x;

return z;

}

float PI_1(float r, float y){

float e;
static float sum_e=0;
float vi;
float kp=2.00;
float ki=10.00;

e = r - y;
sum_e =  sum_e + e;
vi = kp * e + ki * sum_e;

return vi;
}

A PI controller has “state”: it has to remember the sum of all the
previous errors. If you want several controllers you have to
independently store the state of each one.

The traditional solution used by C programmers is to write a controller
function that takes an extra parameter which is a pointer to the state.
In C++ you can use a reference instead:

// PI controller.
float PIController(float &sum, float r, float y)
{
    const float kp = 2.00;
    const float ki = 10.00;

    float e = r - y;  // error
    sum += e;         // integral of error
    return kp * e + ki * sum;
}

You would use it like this:

void loop()
{
    static float sum_1, sum_2;  // State of the controllers.
    // ...
    vi_1 = PIController(sum_1, r_o_1, y_o_1);
    vi_2 = PIController(sum_2, r_o_1, y_o_1);
}

The C++ language provides a nicer way of writing the same thing: you can
use a class to wrap the state and the controlling method together under
the same name:

// PI controller.
class PIController {
public:
    PIController() : sum(0) {}
    float operator()(float r, float y);
private:
    float sum;
};

float PIController::operator()(float r, float y)
{
    const float kp = 2.00;
    const float ki = 10.00;

    float e = r - y;  // error
    sum += e;         // integral of error
    return kp * e + ki * sum;
}

Which you would use like this:

void loop()
{
    static PIController pi_1, pi_2;  // Controller instances.
    // ...
    vi_1 = pi_1(r_o_1, y_o_1);
    vi_2 = pi_2(r_o_1, y_o_1);
}

The generated assembly should not be much different. Note that in both
cases the static variables of loop() could be globals if you prefer.


Follow black and white line simultaneously I have a line following bot which uses IR sensors (LSA08, more specifically) to detect the white line on black surface and stay on track. For the project however, there is a trick in the track. At a certain point, the line changes from white to black and the bot is expected to follow the black line on the white surface.

My question is, how would I design the algorithm which will make the bot recognise that the track and conditions have changed.

It depends a bit on your precise requirements. Currently you are following the black line (meaning sensing black in the middle and white on the sides). Instead you could follow the border of that line. To do this you would have to control the motors in a way, so that in at the middle of the sensors there is a high contrast (black at the right, white at the left, or vice versa). It will not follow the exact same path as before, but a bit to the side.


ESP8266 to ESP8266 communication using Arduino IDE I am trying to achieve communication between two ESP8266, ie one acts as a server and the other acts as a client, where i am passing the string from the server's serial monitor to the client. But the client is not receiving the string.

I have uploaded the server's and client's code below:

#include <ESP8266WiFi.h>
const char* ssid = "xxx";
const char* password = "xx";

WiFiServer server(80);
char inData[64];
char inChar=-1;

void setup() {
  Serial.begin(115200);
  delay(10);
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  // Start the server
  server.begin();
  Serial.println("Server started");
  // Print the IP address
  Serial.println("ip address..");
  IPAddress ip(192,168,1,2);
  IPAddress gateway(192,168,1,1);
  Serial.print(F("selecting static ip to:"));
  IPAddress subnet(255,255,255,0);
  WiFi.config(ip,gateway,subnet);
  Serial.print(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  byte numBytesAvailable= Serial.available();
  if(numBytesAvailable > 0) {
    client.print("hi");
    int i;
    for (i=0;i<numBytesAvailable;i++) {
      inChar= Serial.read();
      inData[i] = inChar;
    }
    inData[i] = '\0';
    client.print(inData);
    delay(500);
    client.flush();
    Serial.println(inData);
  }
  String line = client.readStringUntil('\r');
  Serial.println(line);
  delay(100);
}

Client code:

/*
 *  This sketch sends data via HTTP GET requests to data.sparkfun.com service.
 *
 *  You need to get streamId and privateKey at data.sparkfun.com and paste them
 *  below. Or just customize this script to talk to other HTTP servers.
 *
 */

#include <ESP8266WiFi.h>
void Readled(String line);
const char* ssid     = "xx";
int ledPin1 = 14;
int ledPin2 =  12;
int ledPin3 = 13;
int ledPin4 = 15;
String ON=String("ON");
String OFF=String("OFF");
char inData[64];
char inChar=-1;

void setup() {
  Serial.begin(115200);
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
}

void loop() {
  delay(200);
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect("192.168.1.2", httpPort)) {
    Serial.println("connection failed");
    return;
  }
  // This will send the request to the server
  client.print("hi");
  while(client.available()) {
    String Data = client.readStringUntil('\r');
    Serial.println(Data);
    client.flush();
    Readled(Data);
  }
}

This is the logic. Please suggest me where I am going wrong.

I don't like the order between two statements:

server.begin();
...
WiFi.config(ip,gateway,subnet);

Since you start the server and then modify the IP address, server may be "connected" to the wrong address. Try swapping these two statement groups - start the server after setting the IP address.

I don't know your WiFi router, but it might not like you arbitrarily changing your IP address like that.


Arduino as USB HID is slowed down when PC doesn't read events I have an Arduino Micro that is acting as a HID device for a Linux PC.

I use this call to send the HID values:

HID().SendReport(1, _values, sizeof(_values));

This works in principle, but I noticed this issue:

If my Linux PC is not actively reading the events from the Arduino, then the Arduino is slowed down. My rotary encoders are missing signals, is one symptom.

But as soon as I read the events with my Linux PC, the Arduino loop() runs at full speed again.

I suspect that this is due to recv/send time out delays in the USB core code? Because I noticed this in USBCore.cpp:

u8 timeout = 250;               // 250ms timeout on send? TODO

Anyway, I tried to solve this issue in the following manners:

Check for configuration and suspension with:

     if (USBDevice.configured())
      if (!USBDevice.isSuspended())
         ...

Which did not work.

I also tried monitoring the increments of the frame number:

  // See if USB shows activity.
  static uint8_t prev_fr_num = UDFNUML;
  static uint8_t num_times_idle = 0;
  uint8_t fr_num = UDFNUML;
  if (fr_num == prev_fr_num )
  {
    if (num_times_idle < 255)
      num_times_idle++;
  }
  else
  {
    num_times_idle = 0;
    prev_fr_num = fr_num;
  }

And then only send if num_times_idle is smaller than a threshold. Again, this did not help.

The only way to make it fast, is by reading the events with linux, like so:

$ jstest /dev/input/js0

or alternatively:

$ evtest /dev/input/event5

How can I have the USB HID stuff not slow down my loop code when the PC is not paying attention?

Thanks!

Bram

For those that hit the same issue, here is how I solved it:

Expose the USB_SendSpace() information in the HID interface by editing

/usr/local/arduino-1.8.12/hardware/arduino/avr/libraries/HID/src/HID.cpp

u8 HID_::SendSpace(void)
{
        return USB_SendSpace(pluggedEndpoint);
}

And adding the interface to class HID_ in:

/usr/local/arduino-1.8.12/hardware/arduino/avr/libraries/HID/src/HID.h

That way, before calling HID().SendReport() you can check for send buffer space available by calling the HID().SendSpace() method.

If there is no space, just skip the SendReport() calls, and the Arduino loop() will no longer be slowed down by time outs.


How do I connect components to the Arduino with a motorshield? How would I connect components to the Arduino with this motor shield?

Thanks :)

If you are up for a little soldering, look into stackable Arduino headers. (Feel free to shop around for those, adafruit was just the first result.) You could then use male jumpers and a breadboard to connect anything that fits in a breadboard.

Just be careful to avoid pins that the shield is already using.


Arduino yun as ssh client Is it possible to set the Arduino Yun up as an ssh client? If so, how?

You need to install package openssh-client: it's available in the package list. See this tutorial about how to install optional packages.

You can call ssh on the Linux side using Process from the Bridge Arduino library.
Best is when you execute single or grouped commands using a syntax as:

ssh user@your_other_host 'echo 1; echo 2'

Managing an open ssh session is possible but I think may be troublesome, so avoid it if you can.


Attiny85 route vcc though output pin I'm still learning the basics so please bare with me if something seems unclear ;-)

I want to hook up an Attiny85 to a WiFi module (esp8266) and 2 sensors. The VCC will be provided by a battery pack and a step-up/step-down converter to ensure steady voltage without too much efficiency loss. Right now the modules are all hooked up to the VCC rail, together with the Attiny85 in one circuit.

I would like to take a sample, and then make as much of the circuit power down until the next reading with a 2 minute interval or so.

While looking for power saving modes for the esp8266 and struggling a bit with it, it got me thinking. What if I let Attiny85 handle the WiFi and sensors circuit via an OUTPUT pin and just turn that high or low. I read somewhere that an OUTPUT pin would not be able to supply as much current as if it was directly connected. That would probably be the case for me here since the WiFi module draws significant current.

Maybe using a transistor to "flip the switch" be a good solution instead if that is the case?

So my question is, is my way of thinking here even viable? How do I know what kind of max current can go through an OUTPUT pin?

What you want is a P-channel MOSFET to control the power. Something with a nice low "logic level" gate threshold.

simulate this circuit – Schematic created using CircuitLab

R1 keeps it switched off.  Set the output to LOW to pull the gate down and enable the MOSFET.

Be sure to "stop" your Serial connection and set both TX and RX pins to INPUT to prevent damage to the ESP8266 (or ATTiny) while powered off.


Mosquitto TLS over WifiMulti on ESP8266 With these few lines I am able to attach my certificate, tell it to WifiClientSecure the certificate, start the wifi as well as the mosquito pubsubclient:

WiFiClientSecure espClient;
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}

PubSubClient mqtt_client(espClient);
mqtt_client.setServer(mqtt_server, 8883);
mqtt_client.setCallback(mqtt_callback);
espClient.setCertificate(ca_crt, ca_crt_len);

if (!mqtt_client.connected()) {
  mqtt_reconnect();
}

mqtt_client.loop();

With these lines I am able to connect to wifi, depending on which the closest station is:

ESP8266WiFiMulti wifiMulti;

wifiMulti.addAP("primary-network-name", "pass-to-primary-network");
wifiMulti.addAP("secondary-network-name", "pass-to-secondary-network");
wifiMulti.addAP("tertiary-network-name", "pass-to-tertiary-network");

wifiMulti.run();

How can I combine both? I.e, I am interested in sending data to secure MQTT over a set of possible wifi networks?

The WiFiMulti has nothing to to with the MQTT and TLS side of things at all.  It only has anything to do with the WiFi.  As such it just replaces the code that directly interfaces with the WiFi.

That is, this code:

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}

is replaced by this in the global scope:

ESP8266WiFiMulti wifiMulti;

This in setup():

wifiMulti.addAP("primary-network-name", "pass-to-primary-network");
wifiMulti.addAP("secondary-network-name", "pass-to-secondary-network");
wifiMulti.addAP("tertiary-network-name", "pass-to-tertiary-network");

and this in loop():

wifiMulti.run();

All the MQTT side of things remains exactly the same.


How to use breakpoints for debugging Breakpoints are a great way to see how the compiler runs to your code. Now my question is, is there a possibility to use breakpoints when you debug your code?

As noted in Majenko's answer, the Arduino IDE doesn't provide a breakpoint  mechanism but Atmel Studio does support breakpoints.[*]

However, if you have a switch and an LED, you can track the progress of your program in a way that provides some of the benefits of breakpoints.  You would add a subroutine, say BPReport(), that via serial output or an LCD reports values of critical variables, then lights the LED and waits until the switch has been pressed and released, with debounce.  Call your BPReport() routine whereever you want an unconditional breakpoint.  For conditional breakpoints, you can have a routine BPReportIf(cond) which calls  BPReport() if cond is true.  If you don't want to output via serial, you might use several LEDs or an LCD, and you might use several switches if you want external break controls (for example, cond could be a test of one of the extra switches).

[*] Some hardware debuggers modify downloaded code each time breakpoints are added, changed, or removed.  That usage will wear out flash memory more rapidly than just occasionally downloading to it.  If a chip has been heavily used for such debugging, don't use that chip in a production system.


Not able to upload code to NodeMCU Im now working on a Node MCU based project but the problem is that i cannot upload the code to the board. Further more whenever i connect the usb to the NodeMCU my keyboard stops working and only works again after i turn off and on my pc this happens whenever i disconnect and connect the Node MCU. The error is COM port is not found or board is not connected and sometimes after i disconnect the Node MCU my system gives a message The Last USB device malfunctioned
Can anyone help I'm using a basic NodeMCU 12E CP2021??

I'd check 3 things:

If it's a specific USB port/cable problem, not related to the NodeMCU itself (your said it interacted with your USB keyboard, what makes sense if it's a computer-usb issue). Try to connect the NodeMCU to a different USB port/hub in your computer using another USB cable.

Of course it could be a USB-Serial driver issue. Please make sure what chip is used on your NodeMCU (CH340 or CP1202) and make sure the correct driver is installed.

Most important - you must make sure your Serial pins on the NodeMCU (TX, RX) are not connected to anything during program upload. They are bridged to the Serial connection that is coming from the computer (through the USB-to-Serial chip) and interact and interfere with them.

Good luck!


Powering a Nano with a 5v mini USB adaptor I have made a simple temp sensing circuit that lights an LED when it reaches a certain point. It works perfectly when powered by a USB plugged in to the laptop but when I connect it to a 5V supply with a mini-USB connection nothing happens.

Is this correct and do I need to send power directly to the board on the 5V pin?

Many thanks,
Jack

Thanks all. I found a different power source with a mini-usb connector and it works fine. I think when plugging it in to the PC the Nano makes some faint clicking noises but when direct to  5v plug it does not? I'm not sure so I'll re-test. It was the lack of clicking that lead me to believe it wasn't working as I can't see the on board LEDs using my enclosure.

I don't know about the accuracy but it seems to work for my situation - it is to be placed in a fridge that recently turned itself in to a freezer but has since fixed itself. This project is an early warning system in case it decides to do it again.

Thanks again.
Jack


Arduino MEGA with RTOS I've been coding for FreeRTOS on the MEGA 2560, and was using some LEDs to determine activity per task by toggling each individual LED each time through the task, and monitoring the time using a scope on the LED pin(s). All worked fine until I added the code for the last task.

Only the LED for the last task showed activity, and I assumed I screwed up in the new code, and spent a full day re-doing the code and troubleshooting. Well, it turns out that the code was working just fine. The problem appears to be RTOS is not manipulating the appropriate LED for each task, but using some other pin. The same configuration but with simple test code works fine.

I've tried just about everything I know, with negative results. The 3 tasks are running OK (I still need to do much more testing) so it's not like there is an issue with stack overflow, plus I decided to make ALL the variables as global variables to minimze stack use, and possible conflicts with the variables, which were the same on two of the original programs. I'm using about 600 bytes of RAM for those variables, and have tons of spece in the MEGA in all aspects. The code only uses 14K of the 256K available.

So, I'm officially stumped, and I assume that there's a problem with the task switching somehow, but I'd expect the code to crash eventually if that were the case, but it runs for hours and hours.

Does anyone have any real experience with FreeRTOS that have experienced similar issues related to simple digitalRead and/or digitalWrite problems similar to what I'm seeing?

Well, DUMBO (that would be me) found the problem, and it was a real bonehead error.

When I applied the stand-alone code to the RTOS environment, I did not reallocate pin assignments, so there were multiple I/O events writing to the same port that was using the Test LEDs.

I knew that FreeRTOS couldn't be that bad, as if the I/O went to the incorrect pins, the code would be useless.

So, don't take shortcuts, even if you're not ready to complete all segments of the project. Check for duplicate definitions or they will bite you in the ass.......


Arduino FIFO queue for with potentiometer values and 7 segment display As of now I have code that takes a value from a potentiometer and maps it from 0-9. Based on this mapped value a number will be displayed on the seven segment display.

Currently, if I quickly turn the pot completely then back to zero it will show everything very quickly and then show 0 until I change the pot value again. What I am trying to do is make it so if it's quickly turned completely then back to 0, after a second it will display all the number from 0-9 then back down to 0, each for a second.

I was given a hint to use arrays to create a FIFO queue but I am not sure how to go about doing this and I have been stuck on this for a while. Here's my code:

// Pin 2-8 is connected to the 7 segments of the display.
// Pin 0 is for potentiometer
int potval;
int pinA = 2;
int pinB = 3;
int pinC = 4;
int pinD = 5;
int pinE = 6;
int pinF = 7;
int pinG = 8;
int i;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pins as outputs.
  pinMode(pinA, OUTPUT);
  pinMode(pinB, OUTPUT);
  pinMode(pinC, OUTPUT);
  pinMode(pinD, OUTPUT);
  pinMode(pinE, OUTPUT);
  pinMode(pinF, OUTPUT);
  pinMode(pinG, OUTPUT);
}

void loop() {
  potval=map(analogRead(A0),0,921,0,9);
  if (potval==0){
    //0
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, HIGH);
  }
  if (potval==1){
    //1
    digitalWrite(pinA, HIGH);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, HIGH);
  }
  if (potval==2){
    //2
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, HIGH);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, LOW);
  }
  if (potval==3){
    //3
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, LOW);
  }
  if (potval==4){
    //4
    digitalWrite(pinA, HIGH);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==5){
    //5
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, HIGH);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==6){
    //6
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, HIGH);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==7){
    //7
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, HIGH);
    digitalWrite(pinG, HIGH);
  }
  if (potval==8){
    //8
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, LOW);
    digitalWrite(pinE, LOW);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
  if (potval==9){
    //9
    digitalWrite(pinA, LOW);
    digitalWrite(pinB, LOW);
    digitalWrite(pinC, LOW);
    digitalWrite(pinD, HIGH);
    digitalWrite(pinE, HIGH);
    digitalWrite(pinF, LOW);
    digitalWrite(pinG, LOW);
  }
}

Without seeing the code it is bit difficult to help. Please edit your answer and include the relevant parts of the code, otherwise we will end up (re)writing your code for you.
Hint: why not, when you detect a change in the pot, take the new reading, and then count down/up slowly (at the rate that you desire) from the currently displayed reading to the new measured reading - using a for loop, which contains a delay()? With each iteration of the loop you can display the new value. Easy!
However, this sounds like a terrible idea
Note that your code won't do anything else whilst the display is incrementing and decrementing, using this method. So, if you were to spend a lot of time twiddling with the knob, then the code wouldn't get much time to actually do any real work, apart from displaying the updated value.
In order for your code to do real work, whilst displaying the new updated value, you would either need interrupts, or integrate the display updating procedure into the loop(), such that each iteration of the loop() updates the display (or upon each n iterations of loop(), as loop() will probably be looping to quickly. You will probably need to use millis()).
NOTE: From a UX aspect, although it all sounds very 1960's-James-Bond-evil-guy-equipment, the whole notion of the displayed value slowly following the actual location of the knob sounds, at best, extremely infuriating, if not down right dangerous (depending upon the context). Human feedback should be as fast as possible. Else the user will constantly be turning the knob to reach the value that they which to achieve, when in fact they have already passed that value, and may be over compensating, and it is just the fancy display graphics that is showing the wrong value.
Assuming that the knob is controlling something else (actuator, motor, heater, etc.), and not just a pretty display in itself, unless, you are actually outputting the delayed displayed digital value, and not the knob's actual current analogue value, I would seriously recommend against doing this.
I may be wrong, and it would probably require a separate question on SE.UX, although, I would imagine that it has been asked already.


Order of Evaluation for #define Macros EDIT: I think this fits better in the C++ Stack Overflow, so I'm going to re-post this there.

I am working on a menu system with #define macros (inspired by the Marlin firmware on my 3D printer) I am attempting to generalize each menu item with the macro #define MENU_ITEM_EDIT(). The full code is really long, so I am leaving out chunks of code of compactness. However, you can find the full code here: https://pastebin.com/h24itG9y

void draw_row(int row, char* value) { /* Stuff here*/ } // Draws row
char* uiToStr(int x) { /* Stuff here*/ } // Converts unsigned int to a string

#define disp_array(display, value)  display[value]
#define disp_func(display, value)   display(value)
#define disp_char(display, value)   display

#define MENU_ITEM_EDIT(min, max, rate, display, displayType, width, label, value) \
    // A bunch of stuff
    draw_row(rowNum, disp_ ## displayType(display, value)); \
    // More stuff

Using the code macro would look like:

// Values
const char item1[] = "Item 1", item2[] = "Item 2", item3[] = "Item 3";
const char* const itemList[] = {item1, item2, item3};
int currentItem = 0;
uint8_t item1Val = 10;

void menu1()
{
   START_MENU();
       MENU_ITEM_EDIT(0, 3, 1, itemList, array, 6, "Item:", currentItem);
       MENU_ITEM_EDIT(0, 255, 1, uiToStr, func, 3, "Item 1 Value:", item1Val);
   END_MENU();
}

Which displays as:

Item:     Item 1
Item 1 Value: 10

For convenience in the declarations of my menus, I am trying to use common menu types, such as an uint8_t that ranges from 0 to 255. Then, in the menu, I would use __u255_t instead of the first 6 arguments.

#define __u255_t 0, 255, 1, uiToStr, func, 3

void menu2()
{
    int item2Val = 10;

    START_MENU();
        MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
    END_MENU();
}

Previously, I had it set up such that every time I wanted a different type of menu, even if I would only use it once, I had to define a type for it and how it should evaluate in the macro. This way, I can use 1 argument instead of 6 for commonly recurring types in rows. However, I still want the ability to use the 6 argument option when I have a row that has a unique set of arguments, such as a different range or list of display strings.

However, in this example, the program won't compile because it places __u255_t into min in the MENU_ITEM_EDIT() macro, rather than expanding __u255_t into its 6 values and placing them into the first 6 arguments of MENU_ITEM_EDIT(). The macro evaluates as:

MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
// Evaluates as:
MENU_ITEM_EDIT( (0, 255, 1, uiToStr, func, 3), "Item 2 Value", item2val, , , , , );

Note: I put an extra set of parentheses to make it more clear to understand.

But I want:

MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
// Evaluates as:
MENU_ITEM_EDIT(0, 255, 1, uiToStr, func, 3, "Item 2 Value", item2Val);

I thought about using a struct, however I'm not sure that I can because depending on the row, the value string in draw_row() could be a function or an array. Does anyone have any advice on how to solve this problem?

Also, please let me know if I need to add any more code to make my problem more clear.

You need to turn your macro itself into a macro. Sounds odd, I know.  But take the following example:

#define foo bar, baz
#define foobar(X, Y, Z) something(X, Y, Z);
#define boofar(...) foobar(__VA_ARGS__)

boofar(foo, 4)

boofar is a macro that takes a variable argument list.  That expands out into a call for your actual macro call, expanding foo in the process.  Then your actual macro gets expanded out with the real arguments already in here. The point here is that foo is expanded before being passed to the macro that needs the multiple arguments that are inside foo.

So the expansion chain is actually:

boofar(foo, 4) ->
foobar(bar, baz, 4) ->
something(bar, baz, 4);

Running it through cpp and you get:

# 1 "t.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "t.c"

something(bar, baz, 4);


Where can I find a hardware manual (or documentation) for Arduino board? Where can I find a hardware manual (documentation or a book) for Arduino board?

As far as I know, all hardware details are dispersed (or scatter) in different tutorials.

The Arduino Uno is little more than an ATmega328P microcontroller. In
most cases you will be interested by the documentation of the
microcontroller itself. Anyway, here are both:

The Arduino Uno product page contains the most basic specs, as well as links to

the board schematic
the pin mapping, but see below for a nicer alternative

the ATmega328P product page links to

the ATmega328P datasheet, a 650 page authoritative document
the AVR instruction set manual, for those who want to play with assembly
many application notes discussing specific uses of some peripherals

Alberto (aka PighiXXX) has published nicer versions of the Arduino Uno
pinout.


Did I Brick my Controllino? I recently obtained a Controllino Mini to be used in a small industrial project. While checking it out I also wanted to test the built-in RTC capabilities. In doing so I toyed around with the available commands from the supplied library. After uploading another sketch it seems I have bricked the Controllino, since I cannot upload anything else :

  avrdude: stk500_recv(): programmer is not responding avrdude:
  stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

and the reset LED is permanently lid. When looking at the pinout diagram of the Controllino Mini I saw that there was a small remark  near the top stating

  Not proper handling of the RTC/INT output can cause permanent
  controllino reset , so I guess I somehow reached that state.

Since I am pretty new to the whole Arduino / Microcontroller scene I don't really know where to go from here.

Is it a viable idea to try and burn a new bootloader ?
Is there a simpler way to reset the state of the device?
What did I even do wrong ?

Any help is greatly appreciated !

Christian

Below is the sketch that got me into this mess:

#include <Controllino.h>

unsigned char day, weekday, month, year, hour, minute, sec;
#define analogInputPin A0
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(analogInputPin, INPUT);
Controllino_RTC_init(1);
Serial.print("Initalized RTC: ");
Controllino_SetTimeDate(1,6,4,2016,15,14,10);
}

void loop() {
 Controllino_ReadTimeDate(&day,&weekday,&month,&year,&hour,&minute,&sec);
  float voltage = 15*(analogRead(analogInputPin)/1023.0);
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.print(sec);
  Serial.print(" : ");

  Serial.println(voltage);

}

It certainly looks like the INT pin of the RTC can kill the whole unit. Bit of a FUBAR on their part I would say.

  Is it a viable idea to try and burn a new bootloader ?

If the problem is that INT pin then you won't be able to replace the bootloader, and even if you did it wouldn't fix the problem.

  Is there a simpler way to reset the state of the device?

It looks like you will have to make a hardware modification - cut the connection between /INT and /RESET on the board - if you can identify which track that might be - or use a soldering iron to heat and lift the /INT pin of the RTC chip, which might be easier, depending on what the chip is (they are amazingly short on information).

  What did I even do wrong ?

Probably nothing serious - it's the design that is at fault. Anything that has the potential to completely cripple a system like that without even trying is just idiotic.


Converting three axis magnetometer to Degrees I do not know if here is the best place to post this question.
I have a 9-DOF sensor (MPU 9150) and I want to use its magnetometer to retrieve the rotation angle, from 0 to 359. However, its library returns three values: x, y and z.

I do not know how to transform this into a single value. There's any way to do this?

The answer given by Dave X, namely

az=90-atan(y/x)*180/pi

is on the right track. However, it cannot work as is for two reasons:

The formula fails badly whenever x = 0,
It gives the same azimuth for x = y = 1 and for x = y = −1. In other
words, it cannot differentiate between north-east and south-west.

The formula could be fixed by replacing atan(y/x) by a function that
returns:

atan(y/x) if x > 0
π/2 if x = 0 and y > 0
−π/2 if x = 0 and y < 0
atan(y/x) + π if x < 0 and y ≥ 0
atan(y/x) − π if x < 0 and y < 0

That would be essentially a two-argument, “quadrant-aware” version of
the arctangent, yielding results in (-π, π] instead of
(−π/2, π/2).

Fortunately, such function already exists. It is a very standard
function of the C library and is called atan2(). Thus, the correct
formula is

az = 90 - atan2(y, x) * 180 / M_PI;

Now, since atan(y/x) = π/2 − atan(x/y), the formula above can be
simplified into

az = atan2(x, y) * 180 / M_PI;

This formula gives the direction of the (x, y) vector counted clockwise
from the y axis. It is likely that the OP wants instead to know the
heading of some kind of vehicle. The correct formula depends then on how
the magnetometer has been mounted relative to the vehicle. If we assume
that the x axis of the magnetometer points forward and the y axis points
to the left, then:

the vehicle is heading north (0° magnetic heading) when the horizontal
component of the magnetic field is along +x
the vehicle is heading east (90° magnetic heading) when the horizontal
component of the magnetic field is along +y

From here, it follows that the vehicle heading is

heading = atan2(y, x) * 180 / M_PI;

Obviously, the magnetic declination has to be added if one is
interested in the true (rather than magnetic) heading.


Analog input draws current when Arduino is turned off I am using a Arduino Pro Micro from SparkFun (similar to Arduino Leonardo, cpu: Atmega 32u4). It has a analog input: A0, which I use to keep track of the battery voltage in my battery powered project (via analogRead).

I found out that the red LED on the board lights up, even if there is no supply voltage on the usual inputs (micro-USB or Vcc). If I use a multimeter to measure the current between the battery and A0, I see that the analog input is drawing about 30mA if the Arduino is not powered.

Is this the normal behaviour? Can I fix this via hardware?

Yes, it is normal behaviour, and it's called back-powering.

The current is flowing into the input pin and then flowing up through the ESD protection diode inside the chip to VCC.  It's bad, because the ESD protection diode can't take much current and is easy to damage.

simulate this circuit – Schematic created using CircuitLab

You can prevent it from happening by adding some isolation into the input:

simulate this circuit

MOSFET M1 will be ON when VCC has power, but off when it doesn't. The 100kΩ resistor pulls the gate to ground when VCC is off so it doesn't float. The diode is the body diode of the MOSFET added for clarity. You don't need to add a diode there.


Message received with 1 character less I have the following situation:

One Arduino Uno with a 433mhz transmitter wired to the laptop to have serial communication. Another Arduino Uno with a 9V battery wired with a 433mhz receiver and an LCD screen (16x2, I2C).

I have the following code to transmit:

#include <VirtualWire.h>

void setup() {
  //Force low when enabled
  vw_set_ptt_inverted(true);
  //Set pin 12 for transmitter
  vw_set_tx_pin(12);
  //Setup with speed of the data transfer.
  vw_setup(4000);
  //Set serial communication at 9600 baud
  Serial.begin(9600);//set Serial
  //Set pin 13 to light up when transmitting
  pinMode(13,OUTPUT);
}

void loop() {
  //If message send via serial monitor
  if (Serial.available()) {
    //wait a bit for the entire message to arrive
    delay(100);

    while (Serial.available() > 0) {
      //Read serial into string
      String message = Serial.readString();
      //Initialize char array
      char msg[message.length()];
      //Write string to char array
      message.toCharArray(msg, message.length());
      //send char array as unsigned int (bits)
      vw_send((uint8_t *)msg, strlen(msg));
      //Wait until the complete message has been send
      vw_wait_tx();
      //Turn on light when finished
      digitalWrite(13,HIGH);
      delay(200);
    }
  }else{
    //Turn off light
    digitalWrite(13, LOW);
  }
}

And the following code to receive a message and print on a LCD screen:

#include <LiquidCrystal_I2C.h>
#include <VirtualWire.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

void setup() {
  //start up LCD with 16 chars with 2 lines
  lcd.begin(16,2);
  //Turn on backlight
  lcd.backlight();
  //Write initialising message
  lcd.setCursor(0,0);
  lcd.print("Initialisation..");
  //Force low when enabled
  vw_set_ptt_inverted(true);
  //Set pin 12 to receive
  vw_set_rx_pin(12);
  //Setup with speed of the data transfer.
  vw_setup(4000);
  //set pin 13 for light
  pinMode(13, OUTPUT);
  //Start receiver
  vw_rx_start();

  //Set message on LCD that setup has completed
  lcd.setCursor(0,1);
  lcd.print("Completed!");
}

void loop() {
  //initialize array for message
  uint8_t msg[VW_MAX_MESSAGE_LEN];
  uint8_t msgLength = VW_MAX_MESSAGE_LEN;

  //If message received
  if (vw_get_message(msg, &msgLength)){
    //Turn on light
    digitalWrite(13, HIGH);

    //Print on lcd
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.write(msg, msgLength);
  }else{
    //Else turn of light
    digitalWrite(13, LOW);
  }
}

My problem is that the message that is being transmitted and received by the other arduino always is short 1 character. For example if I send "test", it receives and displays "tes". What am I missing?

(My short solution was to just add a space to the message, then the space got cut off. But I want to understand what is going wrong.)

I haven't found the source of the problem by reading through the code, and will limit my comments to advice about debugging the problem.

With the code as it stands, there are half a dozen points where the missing character might have dropped out.  With just a final result, the problem location is difficult to narrow down.  Modify your code to display intermediate data.

For example, in the sending code, print the read-in string and its length to Serial.  Eg, if you #include <Streaming.h> you can say:

Serial << message << ' ' << message.length() << endl;
Serial << msg << ' ' << strlen(msg) << endl;

and so forth.

[Note, msg actually occupies strlen(msg)+1 bytes, the last byte being a null-byte terminator, which your code doesn't send or receive.]

In the receiving code, besides the lcd.write of msg, do an lcd.print with msgLength.

You can also do some code clean-up in the sender.  Remove the line

while (Serial.available() > 0) {,
and its corresponding }, because  Serial.readString() already contains a character-wait loop with timeout.


Converting code for ATTINY85 to ATMEGA2560. Pin change interupts I have code that compiles correctly for an ATTINY85 board using the ARDUINO IDE but I don't have an ATTINY85 board. I have an Arduino Mega ATMEGA2560 and when I select this board in the Arduino IDE the code does not compile and throws this error message

sketch_feb21a:216:3: error: 'GIMSK' was not declared in this scope

   GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts

   ^

sketch_feb21a:216:16: error: 'PCIE' was not declared in this scope

   GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts

                ^

sketch_feb21a:217:3: error: 'PCMSK' was not declared in this scope

   PCMSK |= _BV(PCINT2);                   // Use PB3 as interrupt pin

   ^

exit status 1
'GIMSK' was not declared in this scope

Here is the code snippet that throws the error

void sleep()
{
  GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT2);                   // Use PB3 as interrupt pin
  ADCSRA &= ~_BV(ADEN);                   // ADC off
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

  MCUCR &= ~_BV(ISC01);
  MCUCR &= ~_BV(ISC00);       // Interrupt on rising edge
  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep

  cli();                                  // Disable interrupts
  PCMSK &= ~_BV(PCINT2);                  // Turn off PB3 as interrupt pin
  sleep_disable();                        // Clear SE bit
  ADCSRA |= _BV(ADEN);                    // ADC on

  sei();                                  // Enable interrupts
}

ISR(PCINT0_vect) {
   /*noInterrupts();
   while (digitalRead(BUTTON_PIN) == LOW);

   delay(50);
   while (digitalRead(BUTTON_PIN) == LOW);
   playTrack(1 + (curTrack++ % 2));
   delay(400);

   interrupts();*/

}

Each processor has different registers, things that control stuff like interrupts, input and output. I would not expect code written for one processor, especially if it directly accesses the registers, to work on another processor.

You would need to look at the datasheet for the Atmega2560 and see how to control its pin change interrupts.


Arduino mega R17 led blink continuously I have bought 10 Arduino Mega 2560 clones and all of them have the same problem. When I connect the to my PC I get a message that windows cannot recognize that device and the LED at the board in R17 blinks non stop. normally this led stops when the arduino is ready. Also in the Arduino IDE I don't see the port option enable.

You need CH340G drivers. CH340G is a chip that basically replaces the usual ATMega 8U2/16U2 that is used for USB to serial interface. As CH340 cannot be reprogrammed it means that you can't emulate other USB devices with your arduino for example a keyboard.

You can download the drivers here.


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

So, how do I program ATmega4809 chip from Raspberry?

The ATMega4809 uses UPDI (Unified Programming and Debugging Interface) for programming, not ICSP like the older ATMega328P. You need a UPDI programmer.
There is a project jtag2updi which you can run on an Uno that turns it into a JTAG to UPDI adaptor which is then compatible with avrdude -c jtag2updi ....


How to control cold to hot (blue to red gradient) RBG LED strip/bulb with a rotary encoder? I'm doing a project for university and I am struggling to code and set up a rotary encoder that can control hot-cold variations. Much like the idea of communicating temperature selected by turning a dial. I would either like to control a single strip of RGB LEDs or a single bulb (changing and fading between colours at the same time).

I would like to have the dial turn from 0 - 180 degrees and relate to intense blue changing to intense red and all the colours in between as increments.

I have an Arduino Uno.

Thank you!

Well as I understand you want to use a rotary encoder ? Rotary encoder can turn freely. Which you can read via arduino easily with a library. You can count a number(let's say x) from 0 up to 255, and write that number to one of the color. For the other color write 255-x so when blue is fading down the red is increasing. But I suggest you to use a potentiometer which has a limited turn (about 270 degrees). Connect it to arduino's one of the analog read pins. It will give you a 10 bit value which is between 0-1023 . You can scale this down to 0-255 range with map function. [Example:  "x = map(x,0,1023,0,255);" ] after that just follow the same process as before.


what voltage level is a digital low for the interrupt mode LOW? I am learning about interrupts and one of the interrupt modes is LOW which triggers anytime the pin is a digital low.
Can someone tell me what voltage that is for an Arduino nano? I did a google search and it said a LOW can be anywhere from 0 to 2V.
I am making a project using a nano and I am powering it with batteries. It would be great if I could set up an interrupt to turn on an LED when the batteries were getting weak so I would know when to change them.

It would be great if I could set up an interrupt to turn on an LED
when the batteries were getting weak

That won't work. The thresholds for the pin registering LOW or HIGH
depend on the supply voltage. Very roughly:

a pin in guaranteed to register LOW if its voltage is below ⅓ Vcc
it is guaranteed to register HIGH if it's above ⅔ Vcc
nothing is guaranteed between ⅓ and ⅔ of Vcc.

For the exact voltage levels, you should check the datasheet.
Note also that those are guaranteed levels. The actual thresholds are
closer to ½ Vcc, with an hysteresis of roughly Vcc/10.
For detecting a low battery condition, you should use the ADC, combined
with either a voltage divider on Vcc or the internal bandgap reference.


Saving a .txt file to SD Card and Reading each content data to txt file then save it to a variable I am new to arduino I am trying to create an arduino project that Saving a .txt file to SD Card and Reading the txt file then save it to a variable data type "Long" named 'savednum'. I had successfully can save the txt file and read it, however the problem lies in storing the read txtfile, when I read the txtfile and stored it in savednum and then serial print the savednum it gives different/ random numbers which is not equal to the data in the .txtfile that I store and read. I am wondering what seem to be wrong? Any suggestion is really appreciated. I thank you in advance.

#include <TMRpcm.h>
 #include <SD.h>
 #include <SPI.h>
 #define SD_ChipSelectPin 4 //using digital pin 4 on arduino nano 328

 TMRpcm tmrpcm; // create an object for use in this sketch

File myFile;

char serialData;

int i = 0;
long n1 = 123456789;
long n2 = 245678918;

long savednum =0;

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

 }

Serial.print("Initializing SD card...");

 if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("initialization failed!");
 while (1);
}
Serial.println("initialization done.");

 myFile = SD.open("NEWDATA.txt", FILE_WRITE);

if (myFile) {
Serial.print("Writing to NEWDATA.txt...");
myFile.println(n1);
myFile.println(n2);

myFile.close();
Serial.println("done.");
} else {

Serial.println("error opening NEWDATA.txt");
}

myFile = SD.open("NEWDATA.txt");
if (myFile) {
Serial.println("NEWDATA.txt:");

while (myFile.available()) {
  Serial.write(myFile.read());
// here the code I tried to read .txt file and store it in long
savednum = myFile.read();
Serial.println(savednum);
}

myFile.close();

}

}

void loop()
 {

  }

myFile.read() reads just one byte from the file - not the whole file or even a whole line.

You're reading one byte, then printing it. Then reading a second byte, storing that in a variable, then printing the variable. Then you loop back to the beginning again.

So you're printing alternate "odd" bytes, and storing / overwriting the variable with "even" bytes. So you just get nonsense.

You're storing the data in your file as ASCII text, so it's necessary to read the entirety of each line and then convert that string of characters into a number. Or read each character in turn and manipulate your total value for the line.

For example:

long savedNum = 0;
long numberOne = 0;

while (myFile.available()) { // Something left to read
    char c = myFile.read(); // Get the next character
    if (isdigit(c)) { // It's a number 0-9
        savedNum *= 10; // Make room by decimal shifting to the left
        savedNum += (c - '0'); // Convert the character to a number and add it to the total
    } else if (c == '\n') { // End of line
        Serial.print(F("The number is: "));
        Serial.println(savedNum); // Show us the number
        numberOne = savedNum;  // Store it somewhere else - enhance this for multiple numbers.
        savedNum = 0;  // Reset to 0 ready to read the next line
    }
}

The Arduino API (Stream class) also includes some handy helper functions, such as:

int num = myFile.parseInt(); // get the next integer

There's no parseLong() though, but despite its name, parseInt() actually returns a long.  That reads characters up until it gets a non-numeric character and converts them to a long using the same method as in my example. It doesn't distinguish lines, though, so can be used to get separate numbers on the same line, such as 32847,2345534,12,-43.

With your file though you may need to filter out the extra \r that may be in there from the line endings or you'll get missing numbers.


Arduino Turn Signals Could I use an Arduino to power run the following lights? Here I have a project in mind, and although I am new to electronics, I am a computer programmer (C, C++, C#, Java) by profession so the coding side doesn't worry me, what I am confused about is what power supply I need etc.

If you mean you want to power it directly from a GPIO pin from an Arduino: no, for two reasons:

It doesn't show the current needed, but it's likely more than 20 or 40 mA which is maximum for a GPIO pin. So you need to use a transistor, which can be used to turn on something with higher current, with the current of a GPIO pin. Search for 'Transistor as a switch' for more info.
Also, it's 12 V and the Arduino delivers 5 V.

What you need is a separate 12V adapter, with a current capability MORE than what that light needs. I cannot find the current (mA) in the link, so you might need to measure it (e.g. with a digital multimeter). If you don't have a digital multimeter, buy one, you need one anyway if you will do electronics. You can even buy a 3 euro one from China if you want (for now).


What value of resistance to put between the output of a 74hc595 and the LEDs? I'm going to start a project to make an array of LEDs using the shift registers 74HC595, I've seen many tutorials and it's not really difficult using the Arduino plataform.

The situation is as follows: in the tutorials they put a resistance between the outputs of the 74HC595 (Qx) and the LEDs , but in each tutorial the resistance varies (between 200 and 575 Ohms).

Then the question would be: if feed with 5V to 74HC595 (the same power as the Arduino) and the resistance that I put between its outputs (Qx) and the LEDs is lower (let's say 200 Ohms), the LEDs will light brighter than if I do it with resistors with higher values (let's say 500 Ohms)?

You are correct that a lower resistance would offer higher brightness. The more current through the LED, the brighter it will be. The current is calculated by dividing the voltage across the resistor by resistance value. The voltage across the resistor would be your 5V - the voltage drop across the LED. this often varies by color. A RED LED might have a 1.2V drop, and GREEN or BLUE would be higher. So to get the same relative brightness in different color LEDS, you will often see a lower resistance used, to get the same current.

Lets say you have a 20mA Red LED, with a 1.2V drop. So (5 - 1.2)/.020 = 190 ohms. If the LED required 10mA, that would be 380 ohms.

Now you DO need to look at the data sheet for the chip driving the LED, and make sure it is up to the task. Can a pin source or sink 10mA? 20mA?


Include guards vs #pragma once Is there any particular reason why #pragma once doesn't seem to be used in Arduino code? Is this just because it's not a well-known feature, or is there some overriding reason to use #ifndef XXX_H/#define XXX_H/#endif?

#pragma once operates on the absolute filename of a file. Include guards work on the content of the file.

If you have multiple copies of the same library (maybe one library has some parts of another included in it - it happens...) #pragma once would have no hope of working right.

Add to that the fact that the Arduino IDE copies some files around the place when building and '#pragma once is pretty much screwed.

Include guards work regardless. So sensible people use include guards and shun #pragma once.


Is it OK to Serial.print(message), when the USB cable is not connected to a host PC? Often I put a bunch of Serial.print( F("debugging messages") ) in my Arduino sketch.

Normally those messages go up a USB cable to a host PC so those messages can be seen on the serial monitor.

I want to install this Arduino as part of a stand-alone system far from any PC and plug the "host" end of the USB cable into a wall-wart USB charger.

Without anything to accept those messages, the buffer on the Arduino eventually fills up, right?
Do I need to do anything to keep the Arduino from overflowing and crashing when it's not connected to a host PC?

Does it make any difference if I'm using a (1) "single-chip" Arduino-compatible where the processor includes on-chip USB, vs. (2) an Arduino-compatible with separate "USB interface chip" and "processor chip"?
(By "single-chip Arduino-compatible", I mean things like the Arduino Leonardo, Arduino Yún, LilyPad Arduino USB, Arduino Micro, the Teensy-LC, etc.)

It is OK to write out serial data with nothing connected.
In case (2) "Arduino + USB interface chip", the arduino has no idea if anything is connected or listening to the serial port. The code will transmit the bytes and act exactly the same whether plugged in to anything or not.
In case (1) "arduino with built in USB" it has some idea, but just drops bytes that are going to be transmitted when the USB port is not connected.
Hardware serial (case 2) has an output buffer, but that just makes the program a little faster. When the buffer is empty, a call to serial.{print, write} will place bytes in the buffer and move on. When it's full, Serial.{print,write} will wait until there is enough room to put the rest of the message in the buffer and move on. The hardware UART and interrupts it generates will keep taking bytes out of the buffer and transmitting them at a constant rate whether something is plugged in or not. In any case, the buffer is a fixed size and will never overflow.
As far as I can tell USB-Serial (case 1) only buffers incoming data. Since the calls to Serial.{print, write} do nothing when not connected, they may take less time than they would otherwise. If your code is really unsafe about timing, that could cause a problem, but I doubt it will.
Many examples that come with the Arduino IDE have the following bit of code that pauses native USB Arduino-compatibles until the USB connection is initialized:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

This code stops the Arduino from doing anything until the USB cable is connected.
Comment out or delete those 3 lines if you want the Arduino to run "stand-alone" without a USB cable connection (Arduino Cookbook p. 117) --
after you delete those lines, if you later plug in a USB cable, the USB will initialize correctly, and then you will see on your serial monitor everything printed by any later Serial.print() commands that run. (Tested on a Teensy LC).


Will plugging in a 12v power supply in the wrong polarity to a CNC SHIELD fry my circuit or damage my power supply? I'm currently in the process of making a DIY pen plotter using an Arduino CNC Shield and GRBL Code. Right now I'm connecting the power supply to the shield. I got a standard 12v supply and I cut off the barrel connector so I can connect the supply directly to the CNC Shield. I can't seem to figure out which wire is negative and which is positive. I don't have a multimeter on me so can't test it but I have attached a picture of the information on the power supply which I think should be able to give someone with more knowledge, insight onto the polarity. I think the left wire is negative but not one hundred percent sure. If I risk a test will this damage my circuits or power supply ? Sorry for such an easy question I just don't want to accidentally fry my circuits as have been working on this for a really long time !!
Thank you so much,
Arav

If you wire the power into that shield wrongly you risk killing things - and with those big electrolytics reverse polarity could get very messy indeed.
You need to identify the polarity before you wire it in, and to do that you need something that is sensitive to polarity.
If you don't have a DMM you can do it with a simple resistor and LED in series - an LED will only work if the polarity is right.
Take a normal LED of the 5mm type (they're easier to identify) and look for the flat edge on the flange around the base. That indicates which is the "negative" or cathode of the LED.  Alternatively look for which of the legs is the shorter of the two, which is also an indication of which is the cathode.
Connect a resistor to this identified negative leg. You want the resistor to be at least 1kΩ, but no more than 10kΩ. You don't need the LED to be bright...
Connect your wires, one to the LED and the other to the resistor.
If the LED lights up then the wire connected to the LED is positive and the wire connected to the resistor is negative.  If it doesn't light up then the wires are reversed.  In this case check it by swapping the wires over - the LED should now light up.


ESP32 stops looping after 2 loops My code: https://pastebin.com/UmdK33U2

I made a menu so I can send commands. First I connect to the wifi and then I send the command to send a request.

Then when it detects the key datos(); goes true, so the loop detects that and it starts sending requests.
After 2 requests it just doesnt continue.

What I can do?

Btw im using a ESP32.

Thank you!

boolean datos = false;

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "ssid";
const char* password = "pass";

//removed the password and ssid for security, it was there before.
void setup() {
  pinMode(2, OUTPUT);
  Serial.begin(115200);

  while (!Serial)
    ;
  Serial.println("===================================================");
  Serial.println("Welcome to the menu, choose what do you want to do:");
  Serial.println("1º Connect to the Wifi | W");
  Serial.println("2º Scan Wifi | S");
  Serial.println("3º Send data to Website | D");
  Serial.println("===================================================");
  Serial.println("Made by Francine and Javi.");
  Serial.println("===================================================");
}

void scanwifi() {
  int n = WiFi.scanNetworks();
  Serial.println("===================================================");
  Serial.println("Scan have been finished.");
  Serial.println("===================================================");
  if (n == 0) {
    Serial.println("===================================================");
    Serial.println("No networks have been found.");
    Serial.println("===================================================");
  } else {
    Serial.print(n); // imprimir en el puerto serial el # de redes encontradas
    Serial.println(" networks have been found.");
    for (int i = 0; i < n; ++i) {
      // SSID: Nombre de la red; RSSI: Potencia de la red en dBm
      Serial.print(i + 1); //iniciamos en la red # 1...
      Serial.print(": ");
      Serial.print(WiFi.SSID(i)); //Imprime el nombre de la red
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i)); //Imprime la potencia de la señal en dBm
      Serial.print(")");
      byte encryption = WiFi.encryptionType(i); // en la variable encryption, guardamos el tipo de encriptación de la red
      Serial.print(" Encryption Type: ");
      Serial.println(encryption, HEX); // imprimimos el tipo de encriptación: 2: WPA, 5: WEP, etc.
      delay(10);
    }
  }
}

void conectarsealwifi() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);

    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");
  delay(1000);
  setup();
}

void loop() {
  if (Serial.available()) {
    char ch = Serial.read();
    if (ch == 'w' || ch == 'W') {
      conectarsealwifi();
    }
    if (ch == 'S' || ch == 's') {
      scanwifi();
    }
    if (ch == 'd' || ch == 'D') {
      datos = true;
      Serial.println(datos);
    }
    if (datos == true) { // si esta habilitado el sending de datos haz
      //randomN = random(200);
      if (WiFi.status() == WL_CONNECTED) {
        digitalWrite(2, HIGH);
        HTTPClient http;

        http.begin("removedtheurl"); //Specify the URL
        int httpCode = http.GET();                            //Make the request

        if (httpCode > 0) { //Check for the returning code

          String payload = http.getString();
          Serial.println(httpCode);
          Serial.println(payload);
          Serial.println("===================================================");

        } else {
          Serial.println(
              "Error on HTTP request, reminder maybe its cloudflare shit.");
        }
        http.end(); //Free the resources
        digitalWrite(2, LOW);
      }
      delay(2000);

    } else {

    }
  }
}

You send from Serial Monitor a character followed by a new line character. This two characters are available. Nothing more to enter the if (Serial.available()) { block.


Use Arduino to transmit signal to a vibrating pager I am an engineer at a machine shop. When a machine stops running, I want to be notified via a vibrating pager (like at restaurants). My plan is to attach the arduino board in the machine and when the machine stops (quits vibrating) I want it to trigger the vibrating pager that I have in my pocket. By what means can the arduino communicate with the vibrating pager to cause it to go off? SMS? Wifi? Bluetooth would likely be out of range. Other options?

To do SMS through a GSM shield like https://www.arduino.cc/en/Main/ArduinoGSMShield with a dataplan, and the device should be accessible anywhere you can get reception.  With a wifi shield like https://www.arduino.cc/en/Main/ArduinoWiFiShield101 you could make it work within your wifi network.

Sparkfun's sales guide at https://www.sparkfun.com/pages/wireless_guide indicates there are a few bluetooth modules that reach 100m, so if your range is less than 100m, bluetooth is a possibility.


need help in code to send sms to multiple contacts using arduino, gsm800, push button When button 1 is pressed, the message should be sent to 4 members. But we are receiving the message for one member and after some delay for the other members. But receiving to all members of contacts given in the code (Here numbers are not mentioned)

#include <LiquidCrystal.h>

int ButtonValue1=0;
int ButtonValue2=0;
int ButtonValue3=0;
int ButtonValue4=0;

int Button1=8;
int Button2=9;
int Button3=10;
int Button4=11;
int buz=12;
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

void okcheck()
{
  unsigned char rcr;
  do{
    rcr = Serial.read();
  }while(rcr != 'K');
}

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

  pinMode(buz,OUTPUT);
  pinMode(Button1,INPUT);
  pinMode(Button2,INPUT);
  pinMode(Button3,INPUT);
  pinMode(Button4,INPUT);

  digitalWrite(12, HIGH);

  lcd.begin(16, 2);
  lcd.clear();
  lcd.print("INNOVATIVE CLG");
  lcd.setCursor(0, 1);
  lcd.print("BUS INFO SYSTEM");

  delay(1000);
}

void loop()
{
  ButtonValue1=digitalRead(Button1);
  ButtonValue2=digitalRead(Button2);
  ButtonValue3=digitalRead(Button3);
  ButtonValue4=digitalRead(Button4);

  if(ButtonValue1!=0)
  {
    lcd.clear();
    lcd.print("BUS STARTED...");
    Serial.write("AT\r\n");         okcheck();
    Serial.write("ATE0\r\n");         okcheck();
    Serial.write("AT+CMGF=1\r\n");         okcheck();
    Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
    Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED FROM STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
  }
  if(ButtonValue2!=0)
  {
    lcd.clear();
    lcd.print("BUS IS @ 1st stage");
    Serial.write("AT\r\n");         okcheck();
    Serial.write("ATE0\r\n");         okcheck();
    Serial.write("AT+CMGF=1\r\n");         okcheck();
    Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
    Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 1st stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 1st stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 1st stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
  }
  if(ButtonValue3!=0)
  {
    lcd.clear();
    lcd.print("BUS IS @ 2nd stage");
    Serial.write("AT\r\n");         okcheck();
    Serial.write("ATE0\r\n");         okcheck();
    Serial.write("AT+CMGF=1\r\n");         okcheck();
    Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
    Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 2nd stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 2nd stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
  }
  if(ButtonValue4!=0)
  {
    lcd.clear();
    lcd.print("BUS IS @ COLLEGE");
    digitalWrite(buz,LOW);
    delay(1000);
    digitalWrite(buz,HIGH);
  }
}

You need to refactor you code, It has become just too complicated for this kind of straight linear code! Your code must be organized better, Don't Repeat Yourself (DRY); just by doing this you may find your error(s).

First lets fix your variables:

#include <LiquidCrystal.h>
#define NUMBUTTS 4
int ButtonValues[NUMBUTTS]= {0,0,0,0};
int Buttons[NUMBUTTS]= {8,9,10,11};
int buz=12;
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

and add some new ones

String numbers[NUMBUTTS] =
{
    "+91234567890",
    "+91234567890",
    "+91234567890",
    "+91234567890",
}

String msgs[NUMBUTTS-1] =
{
   "GUD MNG.. BUS STARTED FROM STARTING POINT\r",
   "BUS IS @ 1st stage\r",
   "BUS IS @ 2nd stage\r",
}

next lets clean up your function:

void okcheck()
{
    unsigned char rcr = 0;
    while(rcr != 'K') // rcr can't be 'K' when it starts as 0
        rcr = Serial.read();
}

Setup needs to be changed now that we changed your vars:

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

    pinMode(buz,OUTPUT);
    digitalWrite(buz, HIGH);

    for(int i=0; i<NUMBUTTS; i++)
        pinMode(Buttons[i],INPUT);

    lcd.begin(16, 2);
    lcd.clear();
    lcd.print("INNOVATIVE CLG");
    lcd.setCursor(0, 1);
    lcd.print("BUS INFO SYSTEM");

    delay(1000);
}

now we need to extract duplicated code and put it in a function:

// common starting code.
void preamble()
{
    Serial.write("AT\r\n");
    okcheck();

    Serial.write("ATE0\r\n");
    okcheck();

    Serial.write("AT+CMGF=1\r\n");
    okcheck();

    Serial.write("AT+CNMI=1,2,0,0\r\n");
    okcheck();

    Serial.write("AT+CSMP=17,167,0,0\r\n");
    okcheck();
}

// common message code
void send_sms(String& msg)
{
    String prefix = "AT+CMGS=\"";
    preamble();

    for(int i=0;i<NUMBUTTS;i++)
    {
        Serial.write(prefix+numbers[i]+"\"\r");
        delay(100);

        Serial.write(msg);
        delay(100);

        Serial.write(0x1A);
        delay(2000)
    }
}

now we need to fix up loop():

void loop()
{
    for(int i=0; i<NUMBUTTS; i++)
    {
        ButtonValues[i]=digitalRead(Buttons[i]);
    }

    for(int i=0; i<NUMBUTTS-1; i++)
    {
        if(ButtonValues[i]!=0)
        {
            lcd.clear();
            lcd.print(msgs[i]);
            send_sms(msgs[i]);
        }
    }

    //special case for button4
    if(ButtonValue[3]!=0)
    {
         lcd.clear();
         lcd.print("BUS IS @ COLLEGE");
         digitalWrite(buz,LOW);
         delay(1000);
         digitalWrite(buz,HIGH);
    }
}

Now your program logic is separate from the code that sends the messages, and you can test each in isolation from each other. You can test that send_sms() actually sends SMSs. Then you can see if your logic does what you think it does; by either replacing send_sms() with a test stub, or just by inspection.

With clean code it should be easier to spot your problem. The code looks like it should work, so I would guess that the modem itself may be causing the delays, maybe it takes a while to send a message and you are queuing them up and it takes a few seconds to get through each one, its possible that not all get send because one or more gets dropped while it is busy sending another. Hard to know without looking at the documentation for your module.

Your diagram looks like it is hooked up wrong, you have TX-> RX, but MOSI -> TX; Serial.read() reads from RX not MOSI, so i don't know how checkok() doesn't just loop forever, since you left the arduino RX floating.