A whole basic game project Arduino Firstly, I know that I have already posted this. I do not think anyone here is stupid so:
The game is: a power source connected to 6 buttons connected to 6 LEDs. you press them all in the randomly generated order, and they blink in the order pressed after completion, then randomize and reset.

I have an array shuffler code  1)Does the array shuffler work 2)How do I configure ports and attach them to values in the array, 3) How do I use an if-then statement to say if all buttons pressed in order, then LEDs blink 3 times?  I have a picture but not the actual Arduino, so, upon request, I can post the picture. Thank you. code:

void setup() {
    // put your setup code here, to run once:
}

void loop() {
    // put your main code here, to run repeatedly:
    int questionNumberArray[] = {0,1,2,3,4,5,6};//the array itself
    const size_t n = sizeof(questionNumberArray) / //the array used
    sizeof(questionNumberArray[0]);//the base of the array

    for (size_t i = 0; i < n - 1; i++) //the loop itself
    {
        size_t j = random(1, n - i);
        int t = questionNumberArray[i]; //integer output for increase
        questionNumberArray[i] = questionNumberArray[j];//the value definition
        questionNumberArray[j] = t;
    }

}

The six buttons are connected to digital pins (1, 2, 9, 11, 12, 13)

So you leds are connected to "pins" not "ports." Since each of the buttons will turn on only 1 led we need to keep track of which button pairs with which led. To do this we can use a struct like this one:

struct ButtonLed{
        int buttonPin;
        int ledPin;
};

You declare a ButtonLed like this: ButtonLed button1 = {1, 0} where the first parameter is the button's pin and the second is the led's pin. (All of the led pins are set to 0 since I don't know which pins you have them connected to.)

And the array will hold the button/led pin pair like this:

ButtonLed questionNumberArray[] = {button1, button2, button3, button4, button5, button6};

Since there are 6 leds you know that your array is size 6 so use this declaration instead

const int n = 6;

I fixed you range for the random number generation. Look at the documentation for random() here https://www.arduino.cc/en/Reference/Random. We can use this function for shuffling the array.

void shuffleArray (ButtonLed arr [], const int size){
    for (int i = 0; i < size - 1; i++){ // iterates through array except last element
        int j = random(0, size); // generates a random index from (0 to n-1) inclusive

        // swap current index with random index
        ButtonLed t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }
}

We will use this function to wait until the user enters a sequence of button presses:

ButtonLed getButtonPress (ButtonLed arr [], const int size){
    bool pressed = false;
    ButtonLed  pressedButton;
    while (!pressed){ // loops until a button was pressed
        for (int i = 0; i < size && !pressed; i++){ // !pressed allows early out
            if (digitalRead(arr[i].buttonPin)){ // one of the six buttons was pressed
                pressed = true; // exit both loops
                pressedButton = arr[i]; // stores which button was pressed
            }
        }
    }
    return pressedButton; // return the pressed button
}

Essentially it gets stuck in a loop and reads each of the 6 buttons until one of them is pressed and then records which one was pressed.

Try using the code below and read the comments the only thing you need to do is change all the zeros in the ButtonLed declarations to whatever pin the leds are connected to. Also the struct above needs to go into it's only file called "ButtonLed.h" It must be called that.

#include "ButtonLed.h"

// These are ButtonLeds our newly created data type
// they hold both an led's pin and the pin for the button
// that turns it on
ButtonLed button1 = {1, 10};
ButtonLed button2 = {2,  8};
ButtonLed button3 = {9,  7};
ButtonLed button4 = {11, 6};
ButtonLed button5 = {12, 5};
ButtonLed button6 = {13, 4};

// This function will randomly shuffle an array of ButtonLeds
void shuffleArray (ButtonLed arr [], const int size){
    for (int i = 0; i < size - 1; i++){ // iterates through array except last element
        int j = random(0, size); // generates a random index from (0 to size-1) inclusive

        // swap current index with random index
        ButtonLed t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }
}

ButtonLed getButtonPress (ButtonLed arr [], const int size){
    bool pressed = false;
    ButtonLed  pressedButton;
    while (!pressed){ // loops until a button was pressed
        for (int i = 0; i < size && !pressed; i++){ // !pressed allows early out
            if (digitalRead(arr[i].buttonPin)){ // one of the six buttons was pressed
                digitalWrite(digitalRead(arr[i].ledPin, HIGH); // turns on the led the user chose
                delay(200);
                digitalWrite(digitalRead(arr[i].ledPin, LOW); // turns it back off
                pressed = true; // exit both loops
                pressedButton = arr[i]; // stores which button was pressed
            }
        }
    }
    return pressedButton; // return the pressed button
}

void setup() {
    randomSeed(analogRead(A0));
    // This is how you set up the leds for output
    pinMode(button1.ledPin, OUTPUT);
    pinMode(button2.ledPin, OUTPUT);
    pinMode(button3.ledPin, OUTPUT);
    pinMode(button4.ledPin, OUTPUT);
    pinMode(button5.ledPin, OUTPUT);
    pinMode(button6.ledPin, OUTPUT);

    // This is how you set up the buttons for input
    pinMode(button1.buttonPin, INPUT);
    pinMode(button2.buttonPin, INPUT);
    pinMode(button3.buttonPin, INPUT);
    pinMode(button4.buttonPin, INPUT);
    pinMode(button5.buttonPin, INPUT);
    pinMode(button6.buttonPin, INPUT);
}

void loop() {

    // This array is of type ButtonLed our newly created data type
    ButtonLed questionNumberArray[] = {button1, button2, button3,
                                       button4, button5, button6};
    const size_t n = 6; // array's size

    shuffleArray(questionNumberArray, n);

    numLeds = 1;
    bool guessCorrectly = false;

    // this while loop allows the user to keep trying until they get it right
    while (!guessCorrectly){

        // This loop displays the correct sequence to the user
        for (int i = 0; i < numLeds; i++){
            digitalWrite(questionNumberArray[i].ledPin, HIGH); // turn on the led

            delay(500); // decrease this number to flash faster; increase to flash slower

            digitalWrite(questionNumberArray[i].ledPin, LOW); // turn off the led
        }

        bool correctButton = true; // the user has pressed the correct button
        ButtonLed userSequence [6];      // stores the sequence the user entered
        // lets the user push 6 buttons
        for (int i = 0; i < numLeds; i++){
            userSequence[i] = getButtonPress(questionNumberArray, numLeds);
            delay(500); // delay between button presses
        }

        // check if the user entered the correct sequence
        for (int i = 0; i < numLeds && correctButton; i++){
            if (userSequence[i].buttonPin != questionNumberArray[i].buttonPin)
                correctButton = false;
        }

        if (correctButton){ // user entered the correct sequence
            guessCorrectly = true;
            // This will turn on the leds in the correct sequence
            for (int i = 0; i < numLeds; i++){
                digitalWrite(questionNumberArray[i].ledPin, HIGH); // turn on the led
                delay(500); // delay half a second
                digitalWrite(questionNumberArray[i].ledPin, LOW); // turn off the led
            }
            numLeds++;
            if (numLeds > 6)
                --numLeds;
        }
    }
}

After you are finished typing the code above it ctrl+shift+n and open a new tab called "ButtonLed.h" and add this to it:

#ifndef BUTTONLED_H
#define BUTTONLED_H
#include <Arduino.h>

// We create new data type called ButtonLed which stores the button's pin
    // and the led's pin; this allows us to keep both an led and it's
    // corresponding button together without have to manage 2 arrays
    struct ButtonLed{
        int buttonPin;
        int ledPin;
    };

#endif

Make sure you open a new tab and not a new project. Also as others have said you should really learn how to program. Be aware this code compiles however, I haven't tested it. I will update the code when you tell me what pins the leds are connected to.

Edit 1

I added a while loop that allows the user to keep trying until they guess correctly.

Edit 2

I also updated the code for which pins the leds are connected to. Remember they're connected to "pins" Not "ports.


Object can't get the right value of its property I'm doing a program for a robot and I got stuck at a weird problem:
I have classes defined for my robot's internals, for example for a StepMotor. I also defined a class for a Controller, which is going to control the speed of each StepMotor.

Here's a fragment of my code:

    #include <SPI.h>
    #include <Tone.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    /SILNIKI KROKOWE:
    class StepMotor: public Device
    {
        public:
            int motorPin;
            int dirPin;
            int sleepPin;
            int ForwardState;
            volatile double Speed;
            volatile int ControlValue;  //the value sent to the motor
            int MaxControlValue = 4000; //maximum ControlValue
            String Name;

            void Init ( void )
            {
                //init
            }

            void SetSpeed ( int speed )
            {
              toneObject.play(speed);
            }

            void SetMode(bool IsOn)
            {
              if (IsOn)
                digitalWrite(sleepPin, HIGH);
              else
                digitalWrite(sleepPin, LOW);
            }

            void SetDirection ( Dir direction )
            {
    //code for setting direction
            }

        private:
          Tone toneObject;
    };

    StepMotor motor_right;
    StepMotor motor_left;

    class Controller
    {
      public:
        ControllerType controllerType;
        double Kp;
        double Ki;
        double Kd;
        double Tp; //czas próbkowania
        volatile double e;
        volatile double e_old;
        volatile double P_result;
        volatile double I_result;
        volatile double D_result;
        StepMotor Motor;

        int Calculate ()
        {
          int Result;
     //Serial.print(Motor.Speed); HERE's THE PROBLEM
    /********************************
    /********************************
    /*******************************
          e = MoveOrder::speed - Motor.Speed;  //Motor.Speed is always 0.00, although it's not true

             //the rest is not important
        }

        void Reset()
        {
          //reset procedure
        }

    };

    Controller controller_right;
    Controller controller_left;

    setup()
    {
       controller_right.Motor = motor_right;
       controller_left.Motor = motor_left;
    }

    ISR(TIMER5_COMPA_vect)
    {
        motor_right.ControlValue = controller_right.Calculate();
        motor_left.ControlValue = controller_left.Calculate();
        motor_right.SetSpeed(motor_right.ControlValue);
        motor_left.SetSpeed(motor_left.ControlValue);

    }

I have cut the less important parts. The rest works properly, because my robot can drive when I use SetSpeed(somevalue); The only problem is that place where I need to read current speed of my motor.
In the Controller class, there's Calculate() method. In that method I want to calculate e = MoveOrder::speed - Motor.Speed; Unfortunately it can't be calculated properly, because Motor.Speed ALWAYS is 0.00 (when I display it with Serial.print(Motor.Speed) I see 0.00 all the time). It's very strange, because when I display speed of each motor (Serial.print(right_motor.Speed) or Serial.print(left_motor.Speed)) the value is correct (when the wheels are spinning, value is not 0.00).

The speed calculations are in a different function, which I didn't present here, because it would be too long - I'm sure it works, because, as I said, I can get speed values properly.

As you can see in setup(), I set each contorller's Motor porperty to the correct object.
I also used volatile keyword for the properties that are used in the interrupt.

What is wrong with my code?

If the code I provided isn't enough, here's the full version:
https://1drv.ms/t/s!Atl-jM_xUkz1hc1f-qYYotj-pJIgUw

I'm not sure if anyone would want to dive into it, because it's not so short.

My guess: controller_right.Motor = motor_right; makes a copy of motor_right. So you don't have the same class instance.

Basically Controller controller_right; calls default constructor which includes also default constructor for the StepMotor. And later all variables are copied into it by using default assigment operator, but still, it's not the same instance.


Using Arduino project migrated to breadboard with 12 MHz crystal instead of 16 MHz I am moving my Arduino Uno project from Uno to Bread and as we know, this requires two 22 pf capacitors and 16 MHz on the breadboard (and the other things too like the power-but my question is about the crystal frequency so I'll focus on that).

If I replace the 16 MHz crystal with a 12 MHz crystal then the project will work as expected on a breadboard-is that correct?

It seems that the fuse setting to use 16 MHz crystal is the same as for the 12 MHz crystal for Arduino Uno-so I guess a change to the fuse setting or bootloader is not required. Am I missing anything?

I guess it's as simple as replacing a 16 MHz crystal by a 12 MHz crystal.

Some of the code running on the microcontroller needs to know the clock speed it's running at for correct timing. For this reason the macro F_CPU is set with this value. In the Arduino IDE this value is commonly defined in the boards.txt build.f_cpu property. If you're using a bootloader(which is used for uploading sketches over serial) it also needs to know the clock speed so that it can get the baud rate of the upload correct. The bootloader is not compiled in the Arduino IDE so it is not affected by your setting in boards.txt. You can recompile the bootloader with the correct clock speed setting and then install the compiled file on your microcontroller using an ISP.

There is a much more simple solution. All the hard work has already been done for you in MiniCore:
https://github.com/MCUdude/MiniCore

You only need to:

Install MiniCore following the instructions at https://github.com/MCUdude/MiniCore
Tools > Board > ATmega328
Tools > Variant > 328P / 328PA
Tools > Clock > 12 MHz external
Tools > Burn Bootloader


47Effects MIDI Library and serial debugging I noticed that since I use the MIDI library from 47effects, I cannot use the print(ln) for the serial port for debugging purposes, neither I can find it in the documentation.

It states that the MIDI library uses the serial port, but I really miss the serial port now for debugging.

Update: so my question: The MIDI library uses the RX (pin 0) and TX (pin 1) on my Arduino One. However, I think the internal Serial.print/println also uses these same pins, so I was wondering how I can use Serial.print and Serial.println statements being visible on the Arduino IDE Terminal (emulator) while using the MIDI library.

I assume you have one or more Arduinos, are trying to do MIDI control, and want to know how to debug with the MIDI library having commandeered the hardware serial port.

One approach is to use I2C or SPI to communicate with a second Arduino, which uses its serial port to deliver debugging data to a host system.  See Nick Gammon's excellent page  Debugging using SPI/I2C and a second processor (gammon.com.au forum id=11329), which illustrates communication between two Arduinos, using one of them as a slave to forward information sent by I2C or SPI from a system being debugged.

Another approach might be to use a serial bridge.  I don't know the ins and outs of this or exactly what it does but have read that, for example, the Hairless bridge (which is an open-sourced software package) can display both sides of MIDI communication, possibly depending on use of Serial.write vs Serial.print.  You could designate certain note sequences as standing for various debugging cases.

A third approach is use of Arduino software serial to send debugging data to a serial port on your host system.  This would use some Arduino pins other than the hardware Rx, Tx pins.

Edit 1:  Pin Usage –

For approach 1, using I2C ties up two specific pins, SDA and SCK.  These are shared with other I2C devices, if any.  SPI typically shares three signals – SCLK, MOSI, and MISO – among all SPI devices, and generates one SS signal per device.  For pinout and protocol details, see Nick Gammon's well-organized and clearly-illustrated I2C and SPI pages.

Approach 2 would use no extra pins.

Approach 3 would use one or two extra pins:  one for half-duplex or output-only communication (which may be adequate for debugging), two for separate Rx, Tx lines.  Compared to hardware serial, software serial is CPU-intensive, does not support as-high data rates, and has a higher error rate.  It should work ok for light-weight debugging output, such as occasional text to show what tests succeeded or failed or what branch was taken, or values of a few variables.


HUGE deviation in Sharp IR sensor values if other pins are defined in void setup() I wrote this code for a project -

int sensorpin = A5;
int val = 0;
double avgval = 0;
int E1 = 11;
int brake = 12;
char data = ' ';

void setup()
{
  Serial.begin(115200);
  pinMode(E1, OUTPUT);
  pinMode(brake, OUTPUT);
  pinMode(sensorpin, INPUT);
}

void loop()
{

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

  val = analogRead(sensorpin);
  avgval = average(val);
  double volt = (avgval*5)/1023;
  Serial.println (avgval);
  Serial.println(volt);
  delay(1000);

  if (data == 'G'){
    analogWrite(E1, 255);
    digitalWrite(brake, LOW);
  }

  if( volt > 1.5 && volt < 1.75 ){
    digitalWrite(brake, HIGH);
  }
}

double average(double adc){
  int n = 1;
  double avg = 0.00, sum = 0.00;
  while(n<=23){
    sum = sum + adc;
    avg = sum/25;
    n++;
  }
  return avg;
}

The code works fine, except for the fact that the Sharp IR sensor (GP2Y0A710K0F) outputs values which are wrong (by a HUGE distance), ONLY if in the void setup() function, the commands -

pinMode(E1, OUTPUT);
pinMode(brake, OUTPUT);

are left uncommented. If I comment the above two statements, the sketch works fine.

What on earth is wrong here? I can't make out anything.

Not sure why commenting out those two lines makes a difference.  I think we need to see a schematic to resolve this.

However...

You do not use "pinMode" to setup an analog input!

Look at the examples on the "analogRead" page.  Notice there is no setup needed for the analog pin.  Just call "analogRead" like you are doing and everything should be fine.


Is there any chance of fixing it? I am new to arduino and robotic stuffs and I thought it would be a good idea to test circuits on my breadboard using arduino's R3 5V pin as power supply. The accident happened when I short circuited the things on the breadboard and after a while arduino gave off a nasty smell. The only part overheated on arduino was the left side of the micro-controller. After that I cant upload nor run code on arduino.

After I explained you my situation, can you imagine a potential problem?(e.g I mean is it a voltage regultor problem, a micro-controller faillure, both of them, or something else?)

Can I fix it?

(#1 - I know arduino boards are cheap. I just want to know if I can do anything        with that.

#2 - No comments about  the accident accepted.)

Thank's in advance.

Regarding the image, my vendor claims the arduino to be an exact copy of "open-source" arduino R3

Can I fix it?

If your power supply still works, there's a decent chance you can repair the board by replacing its microcontroller which is conveniently socketed.


Elapsedtime variable not resetting I am new to Arduino programming. Let me describe the application I am working on. I am pressing a button for a certain period of time (30 sec). I can not hold it in a pressed position for all the time. I want to avoid accidental transition from button state going from logic HIGH to LOW. I am trying to drive a solenoid valve only at the end of the event.

The algorithm I am using is if once the system detects a HIGH from the sensor it goes in a loop and looks for transition to LOW. It checks if there is continuous LOW for more than 5 sec. If NO then it resets to start checking LOW again. If YES that means end of event and drives the solenoid valve.

The problem I am facing with the code is although the transition to LOW and remaining in LOW is less than 5 sec, the system is sending pulse to drive the solenoid valve. I have incorporated Serial.print() function to observe the value of the sensor input state and elapsed-time. The elapsed-time variable does not reset and keep increasing even though the button state reverts from LOW to HIGH.

I am incorporating part of the code here which is related to the algorithm. I will greatly appreciate if you kindly take a look at the code and the output file and help me detect the bug.

Thanks again!
Niloy.

void loop() {

      buttonstate = digitalRead(button);   // read the state of the microswitch value: HIGH "on" or LOW "off"

      if (buttonstate == HIGH ){
          countstart = 1;

          while(countstart == 1) {
          buttonstate = digitalRead(button);   // read the state of the microswitch value: HIGH "on" or LOW "off"

          if ( ( buttonstate == LOW ) && ( startFlag == 0 ) ) { //start new time sequence
                  startFlag = 1;
                  startTime = millis();
            }
          if ( ( buttonstate == LOW ) && startFlag == 1 ){
                  endTime = millis();
                  elapsedTime = endTime - startTime;
          }

          if ( ( buttonstate == HIGH ) && startFlag == 1 ){
                  startFlag == 0;
                  endTime = startTime =0;
                  elapsedTime = endTime - startTime;
                  countstart = 0;
          }

          Serial.print(buttonstate);
          Serial.print("\n");       // Print tab space
          Serial.print(elapsedTime);
          Serial.print("\n");       // Print tab space

      if ( elapsedTime >= 5000)
      {
          delay(2000);  //2 sec delay
          solenoid->run(FORWARD);
          delay(40);
          solenoid->run(RELEASE);

          delay(500);

          solenoid->run(BACKWARD);
          delay(40);
          solenoid->run(RELEASE);

          countstart = 0;
          endTime = startTime =0;
          elapsedTime = endTime - startTime;
          buttonstate = LOW;
          delay(15000); //wait for 15 sec

      }
     }

    }
}

startFlag variable never goes to zero because there is a bug in this part of code:

 if ( ( buttonstate == HIGH ) && startFlag == 1 ){
          **startFlag = 0;**
          endTime = startTime =0;
          elapsedTime = endTime - startTime;
          countstart = 0;
  }


ADS1262 and 2.2 SPI TFT (Two SPI Slave) with Arduino I am interfacing two SPI slave module i.e. ADS1262 and 2.2 SPI TFT with the Arduino Ethernet board.

When I test each device on its own it works. Initially, I interfaced the TFT to the Arduino and it is working fine. Likewise, the example code of ADS1262 is working fine when I am running it alone.

So after successfully running the TFT alone, I then wire-up the ADS1262, add the corresponding code, however the ADS1262 doesn't seem to respond.

I think the issue may be related to the ADS1262_CS or ADS1262_START or ADS1262_DRDY pin sequence to access the ADS1262.

I have used the ProtoCentral_ads1262 library from GitHub and have used the example code.

From Comments:
We have already reserved D10 for Ethernet Controller and D4 for SD Chip select. The issue is, how to communicate both of them, one by one. I can access one of them only when code is prepare for both devices.

// Portion of the code is given here

// https://github.com/adafruit/Adafruit_ILI9341 library used for TFT

// Code start from here

for(j=initvalue;j<=finalvalue;j+=x)
{

      dacvalue=((j*5)/65535);

      writeValue(j);

      tft.fillRect(30,150,70,28,ILI9341_BLACK);

      tft.setCursor(30,150);

      tft.println(dacvalue,3); // dac value is showing on TFT

      Serial.println(dacvalue,3);

// ADS1262 is need to communicate here as per https://github.com/Protocentral/ProtoCentral_ads1262 library

// Which pins are need to control here to communicate with ADS1262???

      volatile int p,data;

      if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data ready(DRDY pin)
     {
       SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes conversion register
       Responsebyte = true ;
     }

      if(Responsebyte == true)
      {
       for(p = 0; p <5; p++)
      {
        SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + p);
      }
      Responsebyte = false;
      }

       if(SPI_RX_Buff_Count >= 5)
      {
        ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
        ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
        ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
        ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

        uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)|((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
        sads1262Count = (signed long) (uads1262Count);      // get signed value
        Serial.println("sads1262Count:");
        Serial.println(sads1262Count);
        resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
        Serial.println(resolution,15);
        volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
        volt_mV   =   volt_V*1000;                           // voltage in mV
     tft.setCursor(166,150);
     tft.println(volt_mV,3); } //not printed on TFT

In above code, ADS1262 is not activated so not giving value on serial window or TFT.

How to activate the ADS1262 module.

I would suggest that

1) you debug individual code and to make sure that they work separately before integrating them.

2) you put those code pieces in logical blocks. for example, you are likely going to read something from the adc and displaying it on the lcd. so your code flow should be something like this:

  vol_adc = ad1262_read(ADC1_CH); //read analog from ADC1_CH
  vol_mv = adc2mv(vol_adc); //convert the adc results to mv
  lcd_display(vol_mv);  //display vol_mv on the lcd

this approach allows for much easier programming and debugging for you and your readers.


strcmp() returns 0 when chars are different I am trying to build a sketch that reads a single number from the Serial Monitor and uses it to light a 7 segment display with this number.

I need to compare the input with the known values, stored in a char array, to know which character was typed in and associate the matching binary combination to light the 7 segment display.

I have made a sample code extracted from the sketch, just to test if I am able to pass a char and get the correct result back:

char nums[] = "0123456789."; // The characters we will check against

/* Tried also these, same results
      char nums[12] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '\0'};
      char nums[] = "456789.0123";
*/

void setup() {
  Serial.begin(9600);
  Serial.println("Write a single character"); Serial.println(" ");
}

void loop() {
  if (Serial.available() > 0) {
    char text = Serial.read(); // Read a single char from serial
    Serial.print("Character provided is: "); Serial.println(text);
    char c = parseChar(text); // Evaluate the char
    Serial.print("Character returned is: "); Serial.println (c);
    if (strcmp(c, text) == 0) { // Check if the returned char is the same
      Serial.print("      CORRECT character returned");
    } else {
      Serial.print("      WRONG character returned");
    }
    Serial.println(" ");
  }
}

char parseChar(char c) {
  int comp = 0;
  Serial.println("----- parseChar() START-----");
  Serial.print("  Parameter 'c' is: "); Serial.println(c);
  for (int i = 0; i < sizeof(nums) ; i++) { // Check the values of the array one by one
    comp = strcmp(c, nums[i]); // Compare the chars
    Serial.print("  Compare to nums["); Serial.print(i); Serial.print("] = "); Serial.print(nums[i]); Serial.print(" --> Result: "); Serial.println(comp);

    /* If the check matches, return the character at that index.
       For simplicity, it just returns the matching char of the array,
       that should be the same as the one sent in to the function.
    */
    if (comp == 0) {
      Serial.println("----- parseChar() END (found) -----");
      return nums[i];
    }
  }
  Serial.println("----- parseChar() END (not found)-----");
  return 0;
}

The function works well for all numbers from 0 to 6. However, for any number over 6, or any other character, the strcmp() function returns always 0, so the returned character is the index 0 of the array, regardless of the character typed.

This is the Serial Monitor output for different characters:

Write a single character

Character provided is: 3
----- parseChar() START-----
  Parameter 'c' is: 3
  Compare to nums[0] = 0 --> Result: 1
  Compare to nums[1] = 1 --> Result: 1
  Compare to nums[2] = 2 --> Result: 1
  Compare to nums[3] = 3 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 3
      CORRECT character returned

Character provided is: 6
----- parseChar() START-----
  Parameter 'c' is: 6
  Compare to nums[0] = 0 --> Result: -6
  Compare to nums[1] = 1 --> Result: 1
  Compare to nums[2] = 2 --> Result: 1
  Compare to nums[3] = 3 --> Result: 1
  Compare to nums[4] = 4 --> Result: 1
  Compare to nums[5] = 5 --> Result: 1
  Compare to nums[6] = 6 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 6
      CORRECT character returned

Character provided is: 7
----- parseChar() START-----
  Parameter 'c' is: 7
  Compare to nums[0] = 0 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 0
      WRONG character returned

Character provided is: g
----- parseChar() START-----
  Parameter 'c' is: g
  Compare to nums[0] = 0 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 0
      WRONG character returned

As you can see, the parseChar() function never returns a "not found" result, even for chars that are not in the array. In fact, it never loops through the array, as the first comparison returns 0 always.

I can't figure out why the strcmp() function returns 0 when the chars are different. Am I missing something?

strcmp is not for comparing a single character like your c parameter. It is for comparing a null-terminated string. I'm a little surprised you didn't get a compiler error, but there it is.

If you want to compare individual characters, just compare them with ==.


How do I start a function with serial input? I want to create a LED Sunrise/Sundown alarm clock. Therefore, I will use a Raspberry Pi that is sending commands over serial to a Teensy 3.1. Like:

"30 Minute Sunrise starting with Color(255,140,0)"
"20 Minute Sundown with Color(255,140,0)"
"start something else with these 3 parameter.

But I don't even get the basic serial part working. E.g. I tried this:

void setup() {
  Serial.begin(9600);
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  if (Serial.available() > 0) {
    if (Serial.read() == 'A'){
      int inte1 = Serial.parseInt();
      int inte2 = Serial.parseInt();
      int inte3 = Serial.parseInt();
      int inte4 = Serial.parseInt();
      int inte5 = Serial.parseInt();
      if (Serial.read() == '\n') {
        Serial.print(inte1);
        Serial.print(inte2);
        Serial.print(inte3);
        Serial.print(inte4);
        Serial.println(inte5);
      }
    }
  }
}

I planned to do a case switch afterwards. Inte1 should define sunrise/sundown, Inte2 the minutes, 'Inte3-5' the rgb color.

However, when I enter "A 1 100 100 100" it is not printing anything at all.

What is the best way do get this working?

Thanks in advance!

Okay, as Majenko and Nick Gammon have suggested. The \n had not arrived in the serial buffer. That way the if clause was not fulfilled and nothing was printed. This code has worked for me now:

if (Serial.available() > 0) {
 if (Serial.read() == 'A'){
  char inte1 = Serial.read();
  int inte2 = Serial.parseInt();
  int inte3 = Serial.parseInt();
  int inte4 = Serial.parseInt();
  int inte5 = Serial.parseInt();
  Serial.print(inte1);
  Serial.print(inte2);
  Serial.print(inte3);
  Serial.print(inte4);
  Serial.println(inte5);
 }
}

Although i read quite a bit now, serial input is still a mystery to me.


How to control continuous rotation servo via HC-12 rf module I am working on a project to wirelessly control a continuous rotation servo...something like a wireless vending machine.
The problem I am having is controlling how many revolutions the servo is making. During testing I used a button and had no issues getting the delay to work properly. Now that it's connected to the HC-12 RF module I can't get the delay to control how many rotations the servo makes. The servo I'm using is the FS90R.

#include <SoftwareSerial.h>
#include <Servo.h>
SoftwareSerial mySerial(2, 3); // RX, TX
Servo badservo;

int pos = 92;
unsigned long last = millis();

void setup() {
  mySerial.begin(9600);
  badservo.attach(9);
  badservo.write(pos);
}

void loop() {
  if(mySerial.available() > 1){
    int input = mySerial.parseInt();//read serial input and convert to integer (-32,768 to 32,767)
    int servpos = badservo.read();
    if(millis() - last > 250){
      if(servpos == 92 && input == 1234){
        badservo.write(0);
        delay(470);
        //mySerial.println(8894);
      }
      else{
        badservo.write(pos);
        //mySerial.println(8894);
      }
    }
  mySerial.flush();//clear the serial buffer for unwanted inputs
  last = millis();
  }
  delay(20);//delay little for better serial communication
}

With the servo that I'm using has a stop position of 92, meaning when I do
servo.write(92);
it will stop the servo. Also, the 470 delay was tested with a button and was a single full rotation.

Now, with the HC-12 module, I can't get the servo to rotate less than 2.5 times.
Anyone have any idea what I'm doing wrong? The goal is to get the servo to rotate only once when the RF module receives the proper signal.

You can't rely on a specific delay being one rotation - especially when you are using SoftwareSerial. SoftwareSerial breaks many things, and anything that uses interrupts (such as the Servo library) gets broken by it. It's a real interrupt hog.

The proper way of doing it is to use a rotary encoder on the servo to report the position (or change in position) so that you know where the servo is. That's really the only reliable method of getting the servo to perform precise operations.

By the way:

mySerial.flush();//clear the serial buffer for unwanted inputs

does absolutely nothing. The operation of flush() changed when the Arduino API turned one. It is now supposed to wait until both the TX circular buffer and the UART TX FIFO are empty. It has nothing to do with emptying any inputs.  Instead you want:

while (mySerial.read() != -1);


Are my stepper motors being burnt out? What is the issue here? I am building a mini-cnc laser engraver as shown in this intructable and this youtube video.

I have built the circuit (minus the jst connector and two male pins at the top left of the board) and have attached a stepper motor from a dvd drive. It worked like a charm, but made a loud ringing noise (like tinnitus.) I proceeded to test it with laser GRBL, and it moved great, but gradually started missing steps, at first only in one direction and eventually in both. After a couple hours of being connected, it wouldn't budge at all. I switched the motor for another motor, and tested it again. This time the motor was much shorter-lived. It made 5 steps perfectly and then just shut off. You could hear the motor try to turn, but it was like it didn't have any torque at all. What could be the issue? (I also tried it on the other axis with the other motor driver, no change.)

It's also worth noting that at one point both the positive and negative (ground) cables from my power supply made contact with metal at once, throwing a spark. However, the steps were already beginning to be lost before that happened.

As per your request, I have attached the circuit layout I am attempting (it's identical to the one in the tutorial) as well as a picture of my physical circuit board. (sorry, a link was my only option as the pics were to big for upload) I know the soldering is pretty bad- I have a giant soldering iron. I don't see any shorts though.

So the problem was that somehow the potentiometer had reset its own vref output. I couldn't adjust it after it did this. I replaced both drivers and it works like a charm now.


Arduino Analog pins go all to high problem I was taking measures from the  outputs of an OpAmp when all the sudden measure 5 volts from all pins of the Arduino Mega for no reason. I disconnected the Arduino and loaded the Firmata and test. All the pins are reading high to 1023.. 5 volts are been output for no reason even when I have the Analog Ping to input.

Sketches code are loading and the lights look normal. I did noticed the processor chip getting hot and the voltage in the breadboard line to the Arduino Analog pins reading 7 volts.

Is this a sign of a serious damaged to my device?

A high voltage at a pin can damage the microcontroller partially.

The ATtiny microcontrollers can sometimes survive a voltage of 7 V.
The ATmega microcontrollers are damaged by that voltage.
The ATmega2560 is older and even more critical with voltages, it can not work at 16 MHz below 4.5 V and gets easily damaged with voltages above 6 V.

When the microcontroller runs at 5.0 V, a input pin can have -0.5 V to +5.5 V.

When the microcontroller gets damaged, it can be damaged partially. It is impossible to determine which parts of the chip are still okay. Therefor a partially damaged microcontroller should not be used anymore.

Solution:

A simple solution is a protection resistor in the signal path to the analog input.

simulate this circuit – Schematic created using CircuitLab

According to application note AVR182, it is allowed to push 1 mA into a pin or pull 1 mA from a pin for the ATmega microcontrollers. That current flows via the internal ESD diodes to VCC or from GND.

With a protection resistor of 4k7 before an input, the microcontroller is protected up to: 1mA * 4k7 + 5.5V = 10.2 V.

The internal ESD diodes can have more than 1 mA, but the maximum is unspecified. It is also dangerous when for example the ATmega is put into sleep mode. Then the 1 mA can lift the VCC voltage and still damage the ATmega microcontroller.

When a voltage divider is used (two resistors, R1 and R2) and the internal reference is used, then the voltage divider can be designed to be protected against very high voltages. For example with a ATmega2560, internal reference of 2.56V, R1=47k, R2=10k. This can measure up to 14.6 V and be protected up to 78 V.


Does this code work as a PWM? I'm working on an Arduino project and I need to write some code that controls the frequency and duty cycle of a square wave signal (pulse width modulation). I'm not allowed to use the PWM function, I have to write my own code.

I've tried this code on Proteus (virtual Arduino) but there are two problems:

The frequency is always high (hundreds of Hz) even if the input voltage is zero. It never reaches 0.5 Hz or 1 Hz.
The duty cycle is very high or very low. I never see 50% or 75% duty cycle on an oscilloscope. When I change the position of the potentiometer it becomes 90% or 10% (I think) and there are no other values.

Would you tell me what's wrong with this code please? I can not find my mistake:

unsigned long Time = 2000000; unsigned int Volt; float dutyCycle = 0.5;
void setup() {
  pinMode(13, OUTPUT); //set Pin 13 or On-board LED to output
}

// the loop function runs over and over again forever
void loop() {

  Volt = analogRead (1);    // Frequency: input voltage is through potentiometer at analong pin 1
  dutyCycle = analogRead (0) / 1023;    // dutyCycle potentiometer is at analong pin 0
  Time = ( 2000954 / (1 + Volt) )- 954; //This equations is linear. When input voltage is zero, frequency = 0.5Hz. When input voltage is 5v, f=1000Hz.

  digitalWrite(13, HIGH);   // turn the LED on
  delayMicroseconds(Time * dutyCycle );              // wait
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delayMicroseconds(Time * (1-dutyCycle) );          // wait
}

dutyCycle = analogRead (0) / 1023;    // dutyCycle potentiometer is at analong pin 0

Dividing a small integer by a bigger integer leaves you with 0. If analogRead() returns 1023 you will get a result of 1. Everything else will give you 0. You need to divide by a floating point number - either 1023.0 or 1023f.

analogRead() is slow. Because it is happening between every single cycle of your square wave you can expect to never get to anywhere near 100% duty cycle. There will always be a LOW period where the analog input is being read.

You should:

Fix your integer division problem
Make the ADC "free running" or interrupt driven so it doesn't interfere with your PWM generation

... Or ...

Fix your integer division problem
Make your PWM generation timer driven, either using the OC peripheral or manually with interrupts, so it doesn't interfere with the analog reading.

... Or ...

You could even do both. Make everything as asynchronous as possible leaving your loop() free to just do the heavy work of calculating the values.


Quiescent Current Analog Input ESP8266 I'm planning an ESP8266 project, where I connect a soil moisture sensor to an ESP8266 chip (only the chip, not a board like the NodeMCU) (Analog Input). Since the whole setup will be battery-powered, I'm trying to minimize the quiescent current as much as possible. Now my question is: is there a quiescent current through the analog input pin of the ESP8266? and if yes, how large is this current approximately?

Thanks in advance

That depends on if you're using a NodeMCU or a "naked" ESP8266.

The NodeMCU has a fixed voltage divider with 220K/100K resistors to ground, contributing about 10 µA to quiescent current (plus the much smaller current caused by the ADC input impedance).

If you're using a NodeMCU you also have to worry about the USB-to-Serial chip and the on-board voltage stabilizer.

The input impedance of the ADC input of a "naked" ESP8266 is (probably) a lot higher, 1 or more MΩ, although it is almost impossible to find definitive numbers.


How to control low power devices when implementing Low Power Mode strategy? As part of implementing Low Power Mode, I wish to control power to attached devices, such as the HC12 transmitter/receiver.  I've read of the usage of MOSFETs to control motors and lighting systems, but don't understand the applicability of such implementations to control something like an HC12, which consumes approximately 200ma.
Should I be using MOSFET and, if so which one?  Else, what is a better solution?  The circuit I am now working on is essentially a PRO Micro, an HC12, and a small led, though I will later add a camera module, approx. 100ma.

Yes, MOSFETs are what you want.

The temptation is to just insert any old logic-level N-channel MOSFET in the ground connection to the device like you would when driving a relay, etc. However that method is fraught with danger. You get such issues as ground-level offsets (where ground isn't actually ground but some mV above ground) which can result in logic level mismatch problems. You get the possibility of power trying to make its way to ground through the device's IO pins and your MCU, etc.

So it is best to instead use a P-channel MOSFET to switch the positive power rail to the device. If the voltage you are switching is the same as the voltage you are doing the switching with (i.e., you are switching 5V using a 5V-level GPIO pin such as on an Arduino) then that is really all you need. However if the voltage you want to switch is higher then you will need to switch the P-channel MOSFET with an N-channel MOSFET, or an NPN BJT.

Here's two schemes:

simulate this circuit – Schematic created using CircuitLab

In the left schematic M1 is kept off by R2, and pulling the control GPIO low it turns M1 on allowing the current to flow.

In the right schematic M1 is kept off by R2 in the same way, but M2, when turned on by the GPIO being driven HIGH. R3 keeps M2 off while the MCU is not ready to drive the GPIO pin yet (in the bootloader, etc).

One thing to remember when switching the power off on either schematic is to first set all the GPIO pins that communicate directly with the device to INPUT mode. That will prevent them trying to power the target device through the IO pins (which will typically have ESD diodes that would feed current to Vcc).

All MOSFETs should be logic level (except M1 in the right schematic which can have a higher threshold depending on the voltage you are switching - best to keep it all logic level though as a rule).


expected class-name before '{' token I am getting the following error when attempting to compile my sketch:

  In file included from sketch.ino:24:0: SerialRenderer.h:7: error:
  expected class-name before '{' token

SerialRenderer.h

#ifndef SERIALRENDERER_H_
#define SERIALRENDERER_H_

#include <MenuSystem.h>

class SerialRenderer : public MenuComponentRenderer
{
public:
    SerialRenderer();
    virtual ~SerialRenderer();

public: // methods from MenuComponentRenderer
    virtual void render(Menu const& menu) const;
    virtual void render_menu_item(MenuItem const& menu_item) const;
    virtual void render_back_menu_item(BackMenuItem const& menu_item) const;
    virtual void render_numeric_menu_item(NumericMenuItem const& menu_item) const;
    virtual void render_menu(Menu const& menu) const;
};

#endif // SERIALRENDERER_H_

The contents of MenuSystem.h can be found at https://github.com/jonblack/arduino-menusystem/blob/master/MenuSystem.h.

It seems like the include of MenuSystem.h does not happen when SerialRenderer.h is included from my main sketch file. I get the same error if the include in SerialRenderer.h is removed.

Is there something simple I am missing for the compiler to be able to "see" MenuSystem.h?

EDIT:

Turns out I was looking at a newer version of the arduino-menusystem library than I had installed (version 2.1.1). That version did not have a class called MenuComponentRenderer.

I pulled the latest version from https://github.com/jonblack/arduino-menusystem/tree/master and it compiles fine.

It is most likely caused by the fact that a correct version of MenuSystem library is not properly installed.
Check whether you can add the library to your sketch.

EDIT: added that also the version should be correct


reading pwm signal doesn't work correctly my goal is to read a pwm signal from a rc receiver. For that i tried to use an arduino.

i ran this code on the arduino:

#define Pin 3

int pwm_value;

void setup() {
  pinMode(Pin, INPUT);
  Serial.begin(9700);
}

void loop() {
  pwm_value = pulseIn(Pin, HIGH);
  Serial.println(pwm_value);
}

Now i connected the 3rd pin with the output of the receiver. But instead of printing the correct pwm values they get printed completely crazy. Sometimes they are under 10 and sometimes they are over 10000. The receiver outputs the correct signal.

I also noticed that if i just touch the pin with my finger or if i only connect a single jumper cable without anything at the end, the arduino will read a pwm signal.

I have realy no idea to solve that. Can you please help me?

Thank you!

check if the problem is the fact you have set 9700 baud rate on your sketch while the commonly used 9600 is supported from arduino IDE.

I slightly modified your code and it works for me. Check if this works for you:

#define Pin 3
#define Source 5
unsigned long  pwm_value;

void setup() {
    pinMode(Source,OUTPUT);
    pinMode(Pin, INPUT);
    Serial.begin(9600);
    analogWrite(Source,500);
}

void loop() {
    pwm_value = pulseIn(Pin, HIGH);
    Serial.println(pwm_value);

}

when you connect pin3 with pin 5 you should get a consistent value on Serial(=967).

About getting signal on floating pins

Getting a signal on a floating pin is normal.
When you have a cable attached it acts like an antenna. When you touch it, you are the antenna!


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

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

2.Open port forwarding for port.

3.Almost done.

So how can I do it with AT commands?

As @Juraj mentioned, martyncurrey.com/arduino-esp8266-web-server , I need to start server with command: AT+CIPSERVER=1,5000, IP is IP of the esp8266 and reserve it on router or use the AT command to set static IP.


missing /dev/ttyACM* on Ubuntu I installed the Arduino IDE according to the arduino.cc instructions (invoking install.sh) rather than sudo apt install .... The ports /dev/ttyACM* were present when the following Linux command is issued.

ls -l /dev/ttyACM*

This shows that the devices have membership in the dialout group. It is necessary to add myself as a user to the group dialout.

sudo usermod -a -G dialout <username>

I selected the board and the port and did a download which eventually completed but it seemed to take a long time. The program probably wasn't working since the program was to flash an LED at a 2 second period but the flash rate was definitely much faster so it seems the download did not work.

I deleted the IDE and reinstalled and the ports disappeared.

I have applied this fix for using the Arduino IDE on Linux.

From the description of the fix the instruction is to issue the following commands:

wget https://github.com/adafruit/Trinket_Arduino_Linux/raw/master/99-adafruit-boards.rules

sudo cp 99-adafruit-boards.rules /etc/udev/rules.d/

Next reboot Linux.

According to this page on Arduino for Linux there ought to be some devices at /dev/ttyACM* but mine are missing. What is the solution to this problem? I have replaced the USB cable and it makes no difference.

The board is Adafruit Feather 32u4 which has an ATmega32u4. The OS is Ubuntu 16.04.

According to this page on Arduino for Linux there ought to be some devices at /dev/ttyACM*

That is not the case. On a "traditional" Arduino board, like the Uno, you have two chips: the main MCU which you program, and a USB interface chip, which is pre-programmed with code to present a CDC/ACM interface to the computer (which it then creates a /dev/ttyACMx device for).

With the feather you don't have that. You have one single chip. That chip is both the USB interface and the chip that you program - and most importantly, it is your program that provides the CDC/ACM device if you choose. If your program doesn't provide a CDC/ACM device then the computer will never see one, so it will never create /dev/ttyACMx.

In general the Arduino core always adds a CDC/ACM device whether or not you ask for it, since it is often used to initiate a reset into the bootloader. However if your sketch stops working for whatever reason then the CDC/ACM port is no longer there.

The M0 on the feather has a neat trick though - if you reset the board with the reset button twice the startup code recognises that fact and forces it to run the bootloader. That bootloader then presents the needed CDC/ACM device to the computer allowing you to upload new code.

Of course, if your program that you upload then doesn't initialise its own CDC/ACM device, or crashes, the CDC/ACM device will not be presented until you do the double-reset trick again.


See compiled assembly output (Visual Micro) I'm curious about what some of my code is being compiled into, is there a way to have the compiler save the intermediate assembly files, ideally somewhere in the project folder?  I read some forum posts about holding down shift when compiling from the Arduino IDE, but even that seems pretty hackish.

Turn on Verbose Compiling in the Arduino IDE and you will see all the intermediate file names (they are done in a temporary folder).

For example:

/home/nick/Development/arduino-1.6.7/arduino-builder -dump-prefs -logger=machine -hardware "/home/nick/Development/arduino-1.6.7/hardware" -hardware "/home/nick/.arduino15/packages" -hardware "/home/nick/Arduino/hardware" -tools "/home/nick/Development/arduino-1.6.7/tools-builder" -tools "/home/nick/Development/arduino-1.6.7/hardware/tools/avr" -tools "/home/nick/.arduino15/packages" -built-in-libraries "/home/nick/Development/arduino-1.6.7/libraries" -libraries "/home/nick/Arduino/libraries" -fqbn=arduino:avr:uno -ide-version=10607 -build-path "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -warnings=default -prefs=build.warn_data_percentage=75 -verbose "/tmp/arduino_1cdca0d02fcf3112936d1438c170697d/sketch_mar03b.ino"
/home/nick/Development/arduino-1.6.7/arduino-builder -compile -logger=machine -hardware "/home/nick/Development/arduino-1.6.7/hardware" -hardware "/home/nick/.arduino15/packages" -hardware "/home/nick/Arduino/hardware" -tools "/home/nick/Development/arduino-1.6.7/tools-builder" -tools "/home/nick/Development/arduino-1.6.7/hardware/tools/avr" -tools "/home/nick/.arduino15/packages" -built-in-libraries "/home/nick/Development/arduino-1.6.7/libraries" -libraries "/home/nick/Arduino/libraries" -fqbn=arduino:avr:uno -ide-version=10607 -build-path "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -warnings=default -prefs=build.warn_data_percentage=75 -verbose "/tmp/arduino_1cdca0d02fcf3112936d1438c170697d/sketch_mar03b.ino"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/home/nick/Arduino/libraries/PID_v1/PID_v1.cpp" -o "/dev/null"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
...
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-ar" rcs  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/main.cpp.o"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-ar" rcs  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/new.cpp.o"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-gcc"  -Os -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp.o" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/libraries/PID_v1/PID_v1.cpp.o" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "-L/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -lm
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.eep"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.hex"
Using library PID_v1 in folder: /home/nick/Arduino/libraries/PID_v1 (legacy)

Sketch uses 6,484 bytes (20%) of program storage space. Maximum is 32,256 bytes.
Global variables use 285 bytes (13%) of dynamic memory, leaving 1,763 bytes for local variables. Maximum is 2,048 bytes.

Of interest are the last couple - the xxx.elf file and the xxx.hex file (where xxx is your sketch name).

The xxx.hex file is what is uploaded to your Arduino (well, it is decoded by Avrdude).

The xxx.elf file can be used to get assembly output, like this:

avr-objdump -Sz xxx.elf

That outputs to the screen. I usually output to a file:

avr-objdump -Sz xxx.elf > /tmp/avr_dump.txt

Example output:

void setup() {
      ec:   0f 93           push    r16
      ee:   1f 93           push    r17
  Setpoint = 100;
      f0:   80 e0           ldi r24, 0x00   ; 0
      f2:   90 e0           ldi r25, 0x00   ; 0
      f4:   a8 ec           ldi r26, 0xC8   ; 200
      f6:   b2 e4           ldi r27, 0x42   ; 66
      f8:   80 93 73 01     sts 0x0173, r24
      fc:   90 93 74 01     sts 0x0174, r25
     100:   a0 93 75 01     sts 0x0175, r26
     104:   b0 93 76 01     sts 0x0176, r27
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
     108:   61 e0           ldi r22, 0x01   ; 1
     10a:   70 e0           ldi r23, 0x00   ; 0
     10c:   82 e3           ldi r24, 0x32   ; 50
     10e:   91 e0           ldi r25, 0x01   ; 1
     110:   0e 94 04 04     call    0x808   ; 0x808 <_ZN3PID7SetModeEi>

In this particular  case Setpoint was a double so it took 8 instructions to load a literal into it.


Installing Ports for Arduino Nano on Mac OS X Yosemite Just starting with Arduino and have gotten stuck at the first hurdle: trying to connect an Arduino Nano with my Mac Book Pro which runs 10.10. I can't seem to find the right port as all suggestions have bluetooth in the name and none with USB anything. Also the post list does not change when I plug/unplug the Arduino. Looking at http://arduino.cc/en/guide/macOSX#toc3 it says that I need to install FTDI software to get the USB port to show, however, having done this it still does not work. Any suggestions?

Thanks,
Calum

Had exactly the same problem. Also using 10.10 and just got an Arduino. What worked for me was using a different cable. The one that came with my Arduino Uno only provided power not data. If you have a printer, it might have the right cable, just test it quickly.

Edit: In addition, whilst trying to find solutions, I also installed 64bit mac FTDIUSBSerialDriver_v2_2_18.dmg. I'm not sure if it made a difference. As after installing it and using the original cable the problem persisted.


Is it bad to leave my Arduino UNO on uninterruped? I'm developing a project (Data logger) that requires that the Arduino remains on for several weeks.

Is it okay to leave it on for about 6 weeks? Do I need to frequently reset it?

This question has a very broad answer. As it depends upon your implementation of both hardware and software.

In very short -

That all depends on your code. The hardware should be able to be left on indefinitely, assuming it is all within spec's. Assuming that, then the biggest concern is the code running on it. Where largest problem of concern is running out of resources. Such as memory. If your code as a memory leak then it will be a problem. Or if there is a bug in the code that can cause it to get stuck. The later can be addressed by employing the WatchDog, which will reset (loose all data) if the code gets unexpectedly stuck.


High Frequency Sine Wave Generation I'm new to the world of Arduino and I'm working on a wireless charging project that needs a 5.7MHz sine wave. I've tried using a Due and changing the PWM and DAC, but I can't get a clean sine wave at that frequency using anything I've found online. My signal is either way too low, or too high and horribly distorted.

Any help would be appreciated. I have access to a Mega, Due, Uno, and Mini.

To generate a square wave, you only need to update the output at a rate of two points per cycle. (Technically, when the Arduino's PWM output is configured for 50% duty cycle, that's a square wave at some frequency.)

But to generate a clean sine wave (without a lot of distortion), you need to update a lot more frequenclly than two points per cycle. Personally I wouldn't want to go much below 20 points per cycle.

Imagine the sine wave is generated by a wheel that spins at some rate. Viewed from the edge, a point on the edge of the wheel traces out a sine wave. Viewed from the axle, you see the point going around in a circle.

Now instead of spinning the wheel continuously, suppose the wheel moves in steps of 30 degrees, 12 steps for a complete turn. Instead of a continuous sine wave, you get discrete steps of 0, 0.5, 0.866, 1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5, 0, 0.5, ...   Although this sequence approximates an ideal sine wave, it's pretty coarse because the steps are so large.

Now try 15 degrees per step (24 steps per cycle). Now you get 0, 0.259, 0.5, 0.707, 0.866, 0.965, 1, ... Much smoother, although the steps are still fairly noticeable.

So there will be less phase error, the more steps there are per cycle of the signal. That's not the only source of distortion however. There is also round-off error due to the limited resolution of the Digital-to-Analog Converter (DAC). For example, the value 0.866 I mentioned above should actually be an irrational value, half the square root of 3. Since it's an irrational number, there's no way for a real DAC to get this value exactly right. DAC output step values are ideally based on powers of two (1/2, 1/4, 3/4, 1/8, 3/8, 5/8, 7/8, etc.). And furthermore a real DAC can have offset error, gain error, non-linearity, as well as uncertainty about precisely when the new programmed value is reached.

There's also frequency error when the system's highest-frequency master clock is divided by an integer. If the Arduino UNO's master clock frequency is 16MHz, and the SPI setup function setClockDivider() is used to divide the master clock by 2, that's 8MHz. Divide by 3 and you get 5.333MHz. Divide by 4, that's 4MHz. Divide by 5, that's 3.2MHz. There's no way to get a clock frequency that's between these discrete steps. For small divisors, there's a big jump between steps. So if you needed to be able to smoothly adjust the frequency, you'd need a much higher master clock frequency. And, if you needed to configure the 16MHz Arduino UNO to an SPI clock frequency of exactly 5.7MHz, that's just not possible -- setClockDivider(2) is too fast, setClockDivider(3) is too slow, and setClockDivider(2.807017543859649) isn't supported by the hardware.

If your system could write to a DAC at an update rate of 12MHz, then 12 points per cycle gives a 1MHz output, and 24 points per cycle gives a 500kHz output. Or taking it the other way round, if you need to generate a 5.7MHz output waveform, then the DAC update rate needs to be somewhere around 100MHz to get a clean, low-distortion waveform. This is probably beyond the limit of what you can directly synthesize in software using something like an Arduino or a Raspberry Pi. A 16MHz Arduino UNO could maybe synthesize a few 100kHz using software synthesis, but at 1MHz there's going to be significant distortion.

Software-controlledDirect Digital Synthesis is very sensitive to timing, so the actual DAC update would need to be implemented in an interrupt service routine, run by a periodic timer. ( See https://electronics.stackexchange.com/questions/26363/how-do-i-create-a-timer-interrupt-with-arduino )  If you just used a while loop with a delay statement, then whenever the code needs to do something else, the waveform would just freeze up. This is more of a problem if the Arduino is trying to manage several other tasks at the same time as it is synthesizing the waveform.

Hardware Direct Digital Synthesis (DDS) is possible. Same principles. There needs to be a phase accumulator, which is just a counter that keeps track of the phase angle of the "wheel" that's generating the sine wave. (The phase accumulator needs to be modulus 360 degrees or 2 pi radians, but there's no requirement to count in 1 degree steps. Better to divide the circle into 2^N slices so that 360 degress maps to the natural counter overflow value.) And there also needs to be a lookup table with the sine value for each of those steps. This lookup table only needs to cover 90 degrees of the sinewave, because the waveform is symmetrical -- the other three quadrants can be found by 2's complementing the values and indexing from the other end of the table. Or, the sine can be approximated by a polynomial calculation. More steps x more DAC resolution requires a deeper, wider lookup table. There are integrated circuits available that perform the timing-critical actions, all the software needs to do is send some initial configuration to set it up. Changing the frequency only requires configuring a new frequency divisor value into the DDS chip, so the Arduino can manage other things without causing distortion.

If the original problem only needs one fixed frequency under 200MHz, and doesn't need any adjustment to that frequency, then the hardware gets a whole lot simpler. The crystal oscillator circuits that we use to generate the timing for digital circuits, are in fact analog to begin with. You can contact a crystal vendor and request a custom AT cut crystal; google custom quartz crystal frequency for quartz crystal vendors. Construction requires a careful printed circuit board layout; the white solderless breadboard commonly used in Arduino projects just doesn't work well above 10MHz. Granted, this fixed-frequency solution doesn't involve Arduino in any way, but if it solves the problem, that's what's important.


PWM should be applied to ENA or IN1/IN2 for L298N board for speed control I am new to the Arduino stuff and I am using L298N to drive two DC motors. When I searched online for sample code, I noticed that there are two types of design.

One type uses analogWrite(pin, pwmOutput) to control PWM on IN1/IN2 pin to adjust speed, and the other uses digitalWrite(pin, HIGH/LOW) to control IN1/IN2 but use analogWrite(enA, pwmOutput) to control speed.

I guess probably both can work, but I just feel it is not right to apply PWM on the enable pin. Any suggestion from the experts?

One more thing, many people say L298N is obsolete. Would anyone please recommend a replacement motor drive module?

I'd use PWM on EN input. Motor will be driven in HIGH and left floating in LOW. The other method means it'll be shorted (= full on brake).

L298N is based on bipolar transistors. That means relatively big voltage drop between drivers Emitter and Collector (about 2V on each transistor), so there are big power losses (= heat).

Maybe something like LMD18200 could be used as unipolar replacement.


Including Class with .h and .cpp files I am trying to use a class in .ino file. The code is:
  .ino file

#include <LED.h>

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

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

.h file

#ifndef LED_h
#define LED_h

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

#endif

.cpp file

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

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

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

Arduino compiler picks the object declaration error:

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

How should I declare objects in Arduino then?

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

That version of the IDE (it seems to change from version to version) differentiates between includes with <...> and includes with "...".

If you use <...> it only looks in the system and library areas.  If you use "..." it also looks inside your sketch.

So in your main INO file change the LED include from:

#include <LED.h>

To:

#include "LED.h"

and it should compile.


Huge nested loop in Arduino I am completely new to programming and I am trying a brute force programming on my garage door opener. I want to use an Arduino for learning purposes. I wrote the following program that finally did what it should and now I am wondering whether there is a shorter code that does the same. Is anyone able to help me in that matter?

I do know that about 2^12 possibilities existed so I ran through all of them. I also knew that some parts of the "pulsetrain" (the set of necessary pulses) start with a particular sequence that is always the same (for all "brute forced" trains) and that the closing sequence is also always identical. I then simply wrote that down in the following, nasty code:

/*
  Transmitter is connected to Arduino Pin #2
*/

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

void pulsetrain(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k, int l, int m) {
  PORTD &= ~_BV(PD2);
  //set to LOW, hardwired to make it faster, see http://www.instructables.com/id/Arduino-is-Slow-and-how-to-fix-it/?ALLSTEPS
  delayMicroseconds(283); // (D2)
  PORTD |= _BV(PD2); //set to HIGH
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(283);
  PORTD |= _BV(PD2);
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(a);
  PORTD |= _BV(PD2);
  delayMicroseconds(b);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(c);
  PORTD |= _BV(PD2);
  delayMicroseconds(d);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(e);
  PORTD |= _BV(PD2);
  delayMicroseconds(f);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(g);
  PORTD |= _BV(PD2);
  delayMicroseconds(h);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(i);
  PORTD |= _BV(PD2);
  delayMicroseconds(j);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(k);
  PORTD |= _BV(PD2);
  delayMicroseconds(l);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(m);
  PORTD |= _BV(PD2);
  delayMicroseconds(283);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(566);
  PORTD |= _BV(PD2);
  delayMicroseconds(283);
  PORTD &= ~_BV(PD2);
  delayMicroseconds(566);
  PORTD &= ~_BV(PD2); // last LOW
}

void loop() {
  int signals[2] = {283, 566};
  for (int a = 0; a < 2;  a++) {
    for (int b = 0; b < 2;  b++) {
      for (int c = 0; c < 2;  c++) {
        for (int d = 0; d < 2;  d++) {
          for (int e = 0; e < 2;  e++) {
            for (int f = 0; f < 2;  f++) {
              for (int g = 0; g < 2;  g++) {
                for (int h = 0; h < 2;  h++) {
                  for (int i = 0; i < 2;  i++) {
                    for (int j = 0; j < 2;  j++) {
                      for (int k = 0; k < 2;  k++) {
                        for (int l = 0; l < 2;  l++) {
                          for (int m = 0; m < 2;  m++) {
                            pulsetrain(signals[a], signals[b], signals[c], signals[d], signals[e], signals[f], signals[g], signals[h], signals[i], signals[j], signals[k], signals[l], signals[m]);
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

All those variables a, b, etc. are just the individual bits of a
13-bit number. When you loop through all combinations, you are actually
looping through all the possible numeric values of a 13-bit number.
This can be simplified as this (warning: not tested):

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

// the bitstream is: 0.101x xxxx.xxxx xxxx.0101
void pulsetrain(uint16_t code) {
    uint32_t bitstream = (((uint32_t) code) << 4) | 0x0a0005UL;
    for (uint8_t i = 0; i < 21; i++) {
        PIND = _BV(PD2);    // toggle pin
        if (bitstream & 0x100000)
            delayMicroseconds(566);
        else
            delayMicroseconds(283);
        bitstream <<= 1;
    }
    PORTD &= ~_BV(PD2); // last LOW
}

void loop() {
    for (uint16_t code = 0; code < 0x2000; code++) {
        pulsetrain(code);
    }
}


How to send an email via Arduino without an email account? Assuming I have all the necessary hardware...
I want to develop a system where you type in an email address and the Arduino will send hourly updates on attached sensors to the provided email address.

I can only get this to work if I enter my email account's username and password and send the email from the authenticated account. There's tons of examples online of this. However, I want to share it with others and I do not want my email authentication to be accessible or be attached with sending the emails.
For example, I want the email to be from a generic service like email@web-mail.com that no one can sign into and not my personal email or a Gmail account I made for the project.

Anonymous email senders have the right method, but they require human interaction to bypass Captcha or similar.

Does anyone have an idea of how to do this? Or should I make a separate webserver that handles the requests made by the Arduino and send emails through a Gmail account I made for the project?

You may be able to do this by running the SMTP transaction yourself. You don't actually need a valid from address (though I probably shouldn't be saying that). There are a number of resouces for how to do this, here's a quick list:

Arduino Playground Email Client page
Adafruit
How to send an email with Arduino and a WiFi shield?

If you read an article telling you how to do SMTP in a generic sense (not using a particular provider's infrastructure) and it looks like they want a "real" e-mail address, you can try with a fake one. Chances are decent that it may work.

There are some fine points that may cause you grief if you go for the most simple of implementation (for example, just because my e-mail address is foo@bar.org doesn't mean that bar.org will accept an SMTP connection, the "right" way to do it is to check DNS for an MX record for bar.org).

It would be best to do (and log) any errors that you encounter. There are plenty of things that can go wrong, so tracking where it blows up will help you – or anybody who's trying to help you debug.

If you don't want to roll your own SMTPClient and FullIP look worth checking out.


Relay with NodeMCU is not working I'm using a Relay Channel and NodeMCU(8266-WIFI). When i trigger the connection, LED Turns ON in Node MCU But the Relay connection is not working. I'm not sure what is the issue, Please help to fix it..
My Pin connection as follows.

NodeMCU (VIN) -> Relay (VCC)
NodeMCU (G) -> Relay (G)
NodeMCU (D1) -> Relay (IN4)

My code as follows,
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <FirebaseCloudMessaging.h>
#include <Firebase.h>
#include <FirebaseHttpClient.h>
#include <FirebaseArduino.h>
#include <FirebaseError.h>
#include <FirebaseObject.h>

// Set these to run example.
#define FIREBASE_HOST "xxx-xxxx.firebaseio.com"
#define FIREBASE_AUTH "xxxxxx"
#define WIFI_SSID "xxxx"
#define WIFI_PASSWORD "xxxxx"

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

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());

  pinMode(D1, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.set("LED_STATUS",0);
}

int n = 0;

void loop() {
  // Get value
  n=Firebase.getInt("LED_STATUS");

  if (n==1) {
     digitalWrite(D1, LOW);
     digitalWrite(LED_BUILTIN, LOW);
     Serial.print("LED is ON ");
     Serial.println(Firebase.getInt("LED_STATUS"));
     delay(1000);
  }
 else{
   //LED_BUILTIN
   digitalWrite(D1, HIGH);
   digitalWrite(LED_BUILTIN, HIGH);
   Serial.print("LED is OFF ");
   Serial.println(Firebase.getInt("LED_STATUS"));
   delay(1000);
 }

}

I found that the 3V isn't enough to power the relay.
https://www.instructables.com/Getting-Started-With-ESP8266LiLon-NodeMCU-V3Flashi/ shows the board supplies USB power (pin VU).
You can remove the jumper that connects signal voltage to relay power and connect the relay board to the USB power.
After that change I could turn the relays on and off, but I could not reliably power 4 relays, 2 relays as shown below seems fine.


Light leds on this board one at a time I am playing around with this Tinycircuits 16 LED board and I can figure out how to persistently light two LEDs at the same time. The page comes with an example that i can modify but I can only do 1 at a time

How do I light more than one LED at a time?

/*
TinyDuino Edge LED Demo

April 9 2014, by Ben Rose

This example code is in the public domain.

http://www.tiny-circuits.com

*/

void setup()
{
  LedOn(0);//Pass a zero to turn all LEDs off
}

void loop()
{
  for(int i=1;i<16;i++){
    LedOn(i);
    delay(20);
  };
  for(int i=16;i>1;i--){
    LedOn(i);
    delay(20);
  };
}

void LedOn(int ledNum)
{
  for(int i=5;i<10;i++){
    pinMode(i, INPUT);
    digitalWrite(i, LOW);
  };
  if(ledNum<1 || ledNum>16) return;
  char highpin[16]={5,6,5,7,6,7,6,8,5,8,8,7,9,7,9,8};
  char lowpin[16]= {6,5,7,5,7,6,8,6,8,5,7,8,7,9,8,9};
  ledNum--;
  digitalWrite(highpin[ledNum],HIGH);
  digitalWrite(lowpin[ledNum],LOW);
  pinMode(highpin[ledNum],OUTPUT);
  pinMode(lowpin[ledNum],OUTPUT);
}

This is your circuit.

I think you can take it from here by looking at the diagram, but please note that e.g. 1 0 0 0 0 will light up 3 and 1, so be careful.

To show more than one, turn on multiple LEDs in rapid succession. It will give the effect that more than one are on. This is known as multiplexing.

Update:

After Googling around, I understood it better. I also wrote this code.

int IO1 = 50;
int IO2 = 48;
int IO3 = 46;
int IO4 = 44;
int IO5 = 41;
int del = 1000;

void setup() {

  pinMode(IO1, INPUT);
  pinMode(IO2, INPUT);
  pinMode(IO3, INPUT);
  pinMode(IO4, INPUT);
  pinMode(IO5, INPUT);
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
    displayLED(1);
    delay(del);
    displayLED(2);
    delay(del);
    displayLED(3);
    delay(del);
    displayLED(4);
    delay(del);
    displayLED(5);
    delay(del);
    displayLED(6);
    delay(del);
    displayLED(7);
    delay(del);
    displayLED(8);
    delay(del);
    displayLED(9);
    delay(del);
    displayLED(10);
    delay(del);
    displayLED(11);
    delay(del);
    displayLED(12);
    delay(del);
    displayLED(13);
    delay(del);
    displayLED(14);
    delay(del);
    displayLED(15);
    delay(del);
    displayLED(16);
    delay(del);// light up LEDS 1, 2 and 3.
}

void displayLED(int a){
    clear();
    if (a == 1){o(1); o(2); h(1); l(2); Serial.println('1');}
    if (a == 2){o(1); o(2); l(1); h(2); Serial.println('2');}
    if (a == 3){o(1); o(3); h(1); l(3); Serial.println('3');}
    if (a == 4){o(1); o(3); l(1); h(3); Serial.println('4');}
    if (a == 5){o(2); o(3); h(2); l(3); Serial.println('5');}
    if (a == 6){o(2); o(3); l(2); h(3); Serial.println('6');}
    if (a == 7){o(2); o(4); h(2); l(4); Serial.println('7');}
    if (a == 8){o(2); o(4); l(2); h(4); Serial.println('8');}
    if (a == 9){o(1); o(4); h(1); l(4); Serial.println('9');}
    if (a == 10){o(1); o(4); l(1); h(4); Serial.println(10);}
    if (a == 11){o(3); o(4); l(3); h(4); Serial.println(11);}
    if (a == 12){o(3); o(4); h(3); l(4); Serial.println(a);}
    if (a == 13){o(3); o(5); l(3); h(5); Serial.println(a);}
    if (a == 14){o(3); o(5); h(3); l(5); Serial.println(a);}
    if (a == 15){o(4); o(5); l(4); h(5); Serial.println(a);}
    if (a == 16){o(4); o(5); h(4); l(5); Serial.println(a);}

}

void clear(){pinMode(IO1, INPUT);
  pinMode(IO2, INPUT);
  pinMode(IO3, INPUT);
  pinMode(IO4, INPUT);
  pinMode(IO5, INPUT);}

void o(int o){
    if (o == 1){pinMode(IO1, OUTPUT);}
    if (o == 2){pinMode(IO2, OUTPUT);}
    if (o == 3){pinMode(IO3, OUTPUT);}
    if (o == 4){pinMode(IO4, OUTPUT);}
    if (o == 5){pinMode(IO5, OUTPUT);}
}

void h(int l){
    if (l == 1){digitalWrite(IO1, HIGH);}
    if (l == 2){digitalWrite(IO2, HIGH);}
    if (l == 3){digitalWrite(IO3, HIGH);}
    if (l == 4){digitalWrite(IO4, HIGH);}
    if (l == 5){digitalWrite(IO5, HIGH);}
}

void l(int h){
    if (h == 1){digitalWrite(IO1, LOW);}
    if (h == 2){digitalWrite(IO2, LOW);}
    if (h == 3){digitalWrite(IO3, LOW);}
    if (h == 4){digitalWrite(IO4, LOW);}
    if (h == 5){digitalWrite(IO5, LOW);}
}


Sending Arduino data to MySQL using phpMyAdmin and XAMPP using Windows10 I want to send my Arduino's sensor data to a MySQL database, using XAMPP and phpMyAdmin. I have been using an ESP8266 for the wifi connection. But I am unable to send the value. And actually I have to send four values, but for the time being I am sending only one value. So also please tell how to send multiple values. I have written the PHP file and saved in to Apache's htdocs.

#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>
#include <SPI.h>
IPAddress ip(192,168,8,1);
char ssid[] = "ZONG MBB-E8372-B67D"; // your network SSID (name)
char pass[] = "08522547"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
int photocellPin = 4; // Analog input pin on Arduino we connected the SIG pin from sensor
int photocellReading; // Here we will place our reading
char server[] =  "192.168.8.1";
// Initialize the Ethernet client object
WiFiEspClient espclient;
SoftwareSerial soft(2,3); // RX, TX

void setup() {
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  soft.begin(115200);
  // initialize ESP module
  WiFi.init(&soft);
  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }
  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }
  // you're connected now, so print out the data
  Serial.println("You're connected to the network");
}

void loop() {
  photocellReading = analogRead(photocellPin);
  // Fill the sensorReading with the information from sensor
  // Connect to the server (your computer or web page)
  if (espclient.connect(server, 80)) {
    espclient.println("GET /write_data7.php?"); // This
    espclient.println("value="); // This
    espclient.println(photocellReading);
    // And this is what we did in the testing section above.
    // We are making a GET request just like we would from our browser
    // but now with live data from the sensor
    espclient.println(" HTTP/1.1"); // Part of the GET request
    espclient.println("Host: 192.168.8.1");
    // IMPORTANT: If you are using XAMPP you will have
    //to find out the IP address of your computer and put it here
    // (it is explained in previous article). If you have a web page,
    // enter its address (ie.Host: "www.yourwebpage.com")
    espclient.println("Connection: close");
    // Part of the GET request telling the server
    // that we are over transmitting the message
    espclient.println(); // Empty line
    espclient.println(); // Empty line
    espclient.stop();    // Closing connection to server
  } else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }

  // Give the server some time to recieve the data and store it. I used 10 seconds here. Be advised when delaying. If u use a short delay, the server might not capture data because of Arduino transmitting new data too soon.
  delay(10000);
}

Following is the PHP code:

<?php
//connecting to the database
define('DB_HOST', 'localhost');
define('DB_NAME', 'connected_car_1');
define('DB_USER','Maryam1');
define('DB_PASSWORD','telecom1213');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

$sql = "INSERT INTO connected_car_1.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
mysql_query($sql,$con);
mysql_close($con);
?>

And this is my serial monitor output:

I am very new to coding in Arduino as well as PHP and databases. So kindly tell me what I am doing wrong. And do I have to provide the IP address of the server, ie. 127.0.0.1? If yes, then where?

You should write the PC IP, for example: 192.168.1.53, because 127.0.0.1 is the IP used only for phpmyadmin and the database inside your computer.


Sending serial data to Processing I have a question about using the Arduino and Processing. I want to build a touch sensor using aluminum foil and connect it to an interface built in Processing. However i've come across a problem. I don't know how to send the serial data from the Arduino to Processing. This is the code I'm using to get the sensor value from the aluminum foil:

#include <CapacitiveSensor.h>

CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);

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

void loop(){
  long start = millis();
  long total1 =  cs_4_2.capacitiveSensor(30);

  Serial.print(millis() - start);
  Serial.print("\t");

  Serial.print(total1);
  Serial.print("\t");
  Serial.print('\n');

  delay(100);
}

The foil is connected to dig pin 4 with a resistor of 1M in between and to dig pin 2 with a resistor of 1K. Pin 4 is the send pin, pin 2 is the receive pin. It all works just fine, in the serial monitor in the Arduino software I get the value of the time between refreshes and the sensor value. But how do I use this sensor value in a Processing sketch? I thought of maybe using Firmata on the Arduino, but then I wouldn't know how to use the CapacitiveSensor library and get the sensor values. Does anyone know how to get this to work? Help would be greatly appreciated!

Try to use this code:

// Graphing sketch

import processing.serial.*;

Serial myPort;        // The serial port
int xPos = 1;         // horizontal position of the graph

void setup () {
// set the window size:
size(400, 300);

// List all the available serial ports
println(Serial.list());
// I know that the first port in the serial list on my mac
// is always my  Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600);
// don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\n');
// set inital background:
background(0);
}
void draw () {
// everything happens in the serialEvent()
}

void serialEvent (Serial myPort) {
// get the ASCII string:
String inString = myPort.readStringUntil('\n');

if (inString != null) {
// trim off any whitespace:
inString = trim(inString);
// convert to an int and map to the screen height:
float inByte = float(inString);
inByte = map(inByte, 0, 1023, 0, height);

// draw the line:
stroke(127,34,255);
line(xPos, height, xPos, height - inByte);

// at the edge of the screen, go back to the beginning:
if (xPos >= width) {
xPos = 0;
background(0);
}
else {
// increment the horizontal position:
xPos++;
}
}
}

Also look at: http://www.arduino.cc/en/Tutorial/Graph


Using 5V arduino with 12v solenoid lock I wish to use an arduino like this with a 12v solenoid lock like this. How can I do this. I am told that using this might work, but I am also thinking I can use a transistor's amlification to do that. Can you tell which one is better and if transistor, how to do that?

By sheer luck your lock solenoid looks very similar to this one (similar spec too "Draws 650mA at 12V") and they have a working circuit for it over here so look at that and see what they used to drive it. Apparently it's a TIP120, so the peak/draw current is probably higher than that ballpark figure, which I suspect is for the hold.

Overengineering the transistor by an order of magnitude or so (for a poorly spec'd solenoid part) ensures it doesn't go pop so easily. Also, a Darlington like TIP120 is very easy to drive from the arduino or some other microcontroller.

A similar project using the same solenoid lock used an IRLB8721 (power MOSFET) instead, which is even more beefy in terms of load current it can handle.


Nodemcu connecting to Wi-Fi Problem I am trying to connect to Wi-Fi with Digital pin declaration in setup() function it's not connecting to wi-fi. But connecting to wi-fi without digital pin diclaration. `

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
int m1 = 5;
int m2 = 6;
const char* ssid = "KS Infotech";
const char* password = "kalamsalam";
String readc = "";
void setup () {
pinMode(m1, OUTPUT);
digitalWrite(m1, LOW);
pinMode(m2, OUTPUT);
digitalWrite(m2, LOW);
Serial.begin(9600);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(1000);
Serial.print("Connecting..");

}

}

void loop() {
while (Serial.available()){  //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = Serial.read();
String T = String(readc);
    Serial.println(T);
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

HTTPClient http;  //Declare an object of class HTTPClient

http.begin("http://ksinfotech.co/kslab/write_to_database.php?incoming="+T+"&UID=surya");  //Specify request destination
int httpCode = http.GET();

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

  String payload = http.getString();   //Get the request response payload
  Serial.println(payload);                     //Print the response payload
  if (payload == 'N');
  {
  digitalWrite(m1, HIGH);
  digitalWrite(m2, LOW);
  delay(2000);
  digitalWrite(m1, LOW);
  digitalWrite(m1, LOW);
}
      if (payload == 'F');
  {
  digitalWrite(m1, LOW);
  digitalWrite(m2, HIGH);
  delay(2000);
  digitalWrite(m1, LOW);
  digitalWrite(m1, LOW);
}

http.end();   //Close connection

}

delay(30000);    //Send a request every 30 seconds

}

The above code not working but the below code working.

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

const char* ssid = "KS Infotech";
const char* password = "kalamsalam";
String readc = "";
void setup () {

Serial.begin(9600);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {

delay(1000);
Serial.print("Connecting..");

}

}

void loop() {
while (Serial.available()){  //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = Serial.read();
if (c == '#'){
  break;                   //Stop the loop once # is detected after a word
}//Conduct a serial read
readc += c; //build the string- "forward", "reverse", "left" and "right"
}
String T = String(readc);
    Serial.println(T);
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

HTTPClient http;  //Declare an object of class HTTPClient

http.begin("http://ksinfotech.co/kslab/write_to_database.php?incoming="+T+"&UID=surya");  //Specify request destination
int httpCode = http.GET();
 //Send the request

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

  String payload = http.getString();   //Get the request response payload
  Serial.println(payload);                     //Print the response payload

}

http.end();   //Close connection

}

delay(30000);    //Send a request every 30 seconds

}

use D5 and D6, not 5 and 6. D5 is IO 14, D6 is IO 12. IO 5 is D1 and IO 6 is SDIO_CLK for the flash memory and that is your problem.

the reference


timer library on Arduino DUE I'm trying to call an interrupt routine (let's call it handler() ) every second on my arduino DUE.
I thought the simplest way to do this was to use this library
but it seems that i don't know how to use it...

You are trying to print 6 characters ("test\r\n"), i.e. 60 bits
including the start and stop bits, 1000 times per second. This requires
a baud rate of at least 60 kbit/s, yet the serial port has been
configured for only 9.6 kbit/s. Something has to give...

As Mikael Patel wrote in a comment, it is generally inadvisable to
Serial.print() from within an ISR. It is supposed to work, though, as
long as you don't fill the Serial output buffer. The problem is that
your code does fill the buffer, as it is writing to it faster than the
UART can empty it. Once the buffer is full, the program will
malfunction.


Mega2560 R3 pin functions When I read about mega2560 I saw it has 54 digital that can be used as input or output.
later on I saw the some of them are used for things like communication.

So I would like to know if the communication pin can still be used as output ? (to power leds)

Yes. Any pin can be used as a digital input/output. However, you cannot use certain communications when using those pins.

The types of communication and their effects on the pins:

SPI: This protocol is used for certain communications with certain breakout boards and shields. For example, the ethernet shield uses SPI to connect. On the Mega(2560), it is pins 50-53.
I2C: This protocol is also for connecting to external items. It is much slower than SPI, but uses only two pins. On the Mega, it uses pins 20/21.
UART/Serial: UART is a communication method that uses two wires and transmits bytes of data. It is often used to connect to things that don't need extreme amounts of data passed, but need a stable two way connection.

On all standard boards, the main UART is on pins 0 and 1. This is usually connected to a UART to USB chip which is sent to the computer. Note: you should still be able to upload sketches if they act as an output and random on/off won't hurt the device.
The Mega(2560) also has UART on pins 14/15, 16/17, and 18/19.


Best Data model/Concept to Store Multi-Day Alarm for clock? I'm writing a multiday day alarm program for a project.
I'm not sure how I want to store the format of each of 10 alarms....I need to store it...in SPIFFS retrieve it(at boot) and then compare it to the current day of the week and time so as to fire off the alarm..I was thinking of storing it in a 10 member array.
First alarm would be every day at 2PM and the second is turned off but would be Mon tues Thursday at 10AM. was going to use strtok_r to extract all of the pieces and compare them every minutte to see if an alarm is needed.
Every minute
{"1|M|T|W|T|F|S|S|14|00","0|M|T||T|||S|10|00"}

I would suggest a bit field for storing the days of the week when the
alarm is supposed to fire:

bit 0: fire on Sundays
bit 1: fire on Mondays
...

This numbering is meant to match the one of DateTime::dayOfTheWeek().
Pack this, together with the hour and minute of the alarm, in a struct
(or a class if you prefer). Maybe add a boolean to tell whether the
alarm is active. For example:
struct Alarm {
    bool is_on;
    uint8_t days;  // bitfield: 0 = Sunday
    uint8_t hour;
    uint8_t minute;
    bool matches(DateTime) const;
};

bool Alarm::matches(DateTime t) const {
    bool day_matches = days & (1 << t.dayOfTheWeek());
    return day_matches && t.hour() == hour && t.minute() == minute;
}

Then if (alarm.is_on && alarm.matches(rtc.now())), the alarm fires.


Making AC current with pin 11 I'm trying to make AC current (50Hz) with an Arduino Uno. It seems to be not working (or wrong code).

int up;
int down;
int out = 11;
void setup() {
  pinMode(out, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  for (up = 0; up <= 255; up++) {
    analogWrite(out, up);
    delay(1);
  }
  for (down = 255; down >= 0; down--) {
    analogWrite(out, down);
    delay(1);
  }
}

Update:

Now the code above is giving output voltage of 0-5V (getting increased from 0 to 5 and then decreased) not giving a negative cycle (-5V).
After setting the minimum delay of 1, the output wave is still half wave rectifier with frequency 2Hz.
Without delay LED is blinking so fast I don't know what's its frequency.

How do I make make 50Hz AC current a with negative cycle?

I ran your sketch and this is the output signal:

analogWrite produce a square wave.

As Majenko said, you have to add a low pass filter to get that sine wave.