Multiple definitions of "xxxx" I really need your help. I use VisualStudio and PlatformIo I still get this error:

  Linking .pioenvs\esp12e\firmware.elf
  .pioenvs\esp12e\src\main.cpp.o:(.data.DebugX+0x0): multiple definition of `DebugX'
  .pioenvs\esp12e\src\customFunctions.cpp.o:(.data.DebugX+0x0): first defined here
  collect2.exe: error: ld returned 1 exit status
  *** [.pioenvs\esp12e\firmware.elf] Error 1

I use header guards in my file, so I do not understand why is this part of code redeclared. I had to miss some elementary in cpp programming but I still can't get it to work.

Copy of my project:
https://bitbucket.org/fires/programingtesting/src/master/ESP8266/cpp/RedefinedError/

main.cpp

    #include <Arduino.h>;
    #include "../include/defines.h"
    //#include "../include/customFunctions.h"
    // Time
    uint32_t mTimeToSec = 0;
    uint32_t mTimeSeconds = 0;
    void setup() {
    etc. etc. etc.

customFunction.h

    #pragma once
    #ifndef CUSTOMFUNCTIONS_H
    #define CUSTOMFUNCTIONS_H
    void connectWiFi();
    void initializeOTA();
    #endif

defines.h

    #pragma once
    #ifndef DEFINES_H
    #define DEFINES_H
    #include <jled.h>
    #define BowlingLed 5
    #define StatekLed 4
    int DebugX = 1;
    #endif

Thanks for the help, I read many articles and many issues but I still do not understand why DebugX is redefined if it is in header guard.

Included files are included before compilation, really replacing the #include with the content of the file.

If you write int DebugX = 1; you define a variable. And it is defined in every source file which includes it. Then the linker finds it in more then one unit and ends with "multiple definitions" error.

The variable must be defined only in one compilation unit (.c, .cpp). For example in your case customFunctions.cpp. To make it available in other source files put extern int DebugX; into the .h file.


Setting up the MMA8452 to trigger interrupt I am working with the MMA8452q accelerometer by Freescale.  I am trying to set it up to be in low power mode, to go to sleep when no motion has happened, and to wake up due to motion being detected and trigger the  interrupt that corresponds to it.  I am using Arduino.

I have verified the accelerometer works (i.e. can read off accelerometer data and communicate properly to it via I2C), and I have also verified that the interrupt and handler all work (by manually triggering the interrupt as compared to using the accelerometer).  However, after initializing using the code below, my interrupt due to motion is not getting triggered.

-The datasheet can be found here: http://www.freescale.com/files/sensors/doc/data_sheet/MMA8452Q.pdf

-App note can be found here: http://cache.freescale.com/files/sensors/doc/app_note/AN4074.pdf

My code is as follows:

void MMA8452::initMMA8452(unsigned char fsr)
{
    //CONFIGURE THE ACCELEROMETER
    MMA8452Standby();  // Must be in standby to change registers

    //Set up the full scale range to 2, 4, or 8g.
    if ((fsr==2)||(fsr==4)||(fsr==8))
        writeRegister(XYZ_DATA_CFG, fsr >> 2);
    else
        writeRegister(XYZ_DATA_CFG, 0);

    writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | bmRES1DOT56);  //1.56Hz resolution in both wake and sleep mode (lowest power)
    writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP << SMODS) | (LP << MODS) | (1 << SLPE));  //LOW POWER MODE IN SLEEP & ACTIVE STATES WITH LOWEST SAMPLING

    writeRegister(CTRL_REG3, (1 << WAKE_FF_MT));        //ONLY WAKE UP FROM MOTION DETECTION
    writeRegister(CTRL_REG4, (1 << INT_EN_ASLP) | (1 << INT_EN_FF_MT));  //ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) & MOTION INTERRUPT TO KEEP AWAKE
    writeRegister(ASLP_COUNT, ASLP_TIMEOUT);    //162s TIMEOUT BEFORE SLEEPING

    writeRegister(CTRL_REG5, (1 << INT_CFG_FF_MT) | (1 << INT_CFG_ASLP));  //INTERRUPT SLEEP AND FREE FALL TO INT1 PIN OF MMA8452

    //SETUP THE MOTION DETECTION
    writeRegister(FF_MT_CFG, (1 << ELE) | (1 << OAE));      //MOTION DETECTION AND LATCH THE RESULT WHEN IT HAPPENS AS OPPOSED TO COMBINATIONAL REAL TIME
    writeRegister(FF_MT_THS, MOTION_THRESHOLD);             //MOTION DETECTION THRESHOLDS
    writeRegister(FF_MT_COUNT, MOTION_DEBOUNCE_COUNT);      //TIME MOTION NEEDS TO BE PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED

    MMA8452Active();
};

I played around more with it, and this code works:

void MMA8452::initMMA8452(unsigned char fsr, unsigned char dr, unsigned char sr, unsigned char sc, unsigned char mt, unsigned char mdc)
{
    MMA8452Standby();

//Set up the full scale range to 2, 4, or 8g.
if ((fsr==2)||(fsr==4)||(fsr==8))
    writeRegister(XYZ_DATA_CFG, fsr >> 2);
else
    writeRegister(XYZ_DATA_CFG, 0);

writeRegister(CTRL_REG1, readRegister(CTRL_REG1) & ~(0xF8));
if (dr<= 7)
    writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (dr << DR0));
if (sr<=3)
    writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (sr << ASLP_RATE0));

writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP << SMODS) | (LP << MODS) | (1 << SLPE));  //LOW POWER MODE IN SLEEP & ACTIVE STATES WITH LOWEST SAMPLING
writeRegister(ASLP_COUNT, sc);

// Set up interrupt 1 and 2: 1 = wake ups, 2 = data
writeRegister(CTRL_REG3, (1 << WAKE_FF_MT) | (1 << IPOL));  // Active high, push-pull interrupts, sleep wake up from motion detection
writeRegister(CTRL_REG4, (1 << INT_EN_ASLP) | (1 << INT_EN_FF_MT) |  (1 << INT_EN_DRDY));  // DRDY ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) & MOTION INTERRUPT TO KEEP AWAKE
writeRegister(CTRL_REG5, (1 << INT_CFG_ASLP) | (1 << INT_CFG_FF_MT));  // DRDY on INT1, ASLP_WAKE INT2, FF INT2
writeRegister(CTRL_REG5, readRegister(CTRL_REG5));

//SETUP THE MOTION DETECTION
writeRegister(FF_MT_CFG, 0xF8);     /*MOTION DETECTION AND LATCH THE
                                    //RESULT WHEN IT HAPPENS AS OPPOSED
                                    //TO COMBINATIONAL REAL TIME*/
    writeRegister(FF_MT_THS, mt);       //MOTION DETECTION THRESHOLDS
    writeRegister(FF_MT_COUNT, mdc);    //TIME MOTION NEEDS TO BE
                                        //PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED

    MMA8452Active();
}


Arduino works bad when powered by 9V battery At first I am sorry for my bad English.

I am making robot which can do a lot of things...

If I connect arduino on my robot with PC via USB, the robot works properly. If I use external power supply (9V battery) the robot is doing almost nothing.. The diodes are little bit blinking and sometimes dc motors make motion... And thats all. Batteries are charged. Where's the problem?

Everything I want is make into motion dc motors.. With 5V USB it works. With external power supply not (9V battery).

I got a fresh 9 V out of a packet and measured it.

 9.58 volts

Now with a load of 500 mA (which you quite likely would get with a robot) it dropped to:

 7.4 volts

With a load of 750 mA the voltage dropped to 6.6 V which is below what you are supposed to supply via the power jack.

And that was with a fresh battery, testing for a few seconds.

Those 9 V batteries are just not designed to drive motors.

I suggest a somewhat heavier-duty battery, like 5 x AA batteries, at least for the robot part.


WDT ISR not called when SPI ST7789 module initiated Using the .init function for the ST7789 TFT screen prevents my WDT ISR from firing. What explains this behaviour, and is there something I can do? Any other timer ISR I could use instead?
#include <Adafruit_ST7789.h>    // Includes Adafruit_GFX.h

#define TFT_CS 10 // define chip select pin
#define TFT_DC 9  // define data/command pin
#define TFT_RST 8 // define reset pin, or set to -1 and connect to Arduino RESET pin

Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

void setup()
{
    //Serial.begin(9600);
    pinMode(13, OUTPUT);

    WDTCSR = (24); // Change enable and WDE - also resets
    //prescalers only - get rid of the WDE and WDCE bit.
    WDTCSR = (6); // 1 sec
    WDTCSR |= (1 << 6); //enable interrupt mode - WDT as an interrupt is useful to wake up from sleep
    sei();

    tft.init(240, 240, SPI_MODE2); // comment this out and WDT works fine
    tft.setRotation(0);
    tft.setTextWrap(true);
}

void loop()
{

}

ISR(WDT_vect)
{
  digitalWrite(13, (digitalRead(13) ^ 1));   // toggle LED pin
}

Thanks!

You can't use the LED on pin 13 on Uno, Nano or Nano Every, if you use SPI . It is the clock pin of the SPI.
The init function of the display initializes SPI which dedicates the pin to SPI peripheral and disconnects it from pin IO peripheral.


Can I control a stepper motor with a sensor? Can I control a bipolar stepper motor with an L293d motor driver shield using HC-SRO4 ultrasonic distance sensor on arduino?

Yes, you can, they are completely independent, but that does not mean you can use e.g. an Arduino Uno to do the following:

Read the sensor
Based on the sensor values, control the L293D

In case you have doubt how to start, I suggest the following:

First, only use the HC-SR04 sensor (build the circuit, use an example program, check that it works)
Start over (remove the sensor), only use the L293D motor driver shield (with a motor), use an example program, check that it works)
Now combine both circuits and programs or if you feel confident enough, start making your entirely new program.


Sampling and serial transfer I am trying to get a sampling rate of over 10k Samples per second as well as send each sample over a serial line. Taking a sample and putting it on the serial line each time took too long. I am using Processing 3.3.6 for datalogging into a csv file. I am unable to achieve more than 6k samples per second even at lower prescaler value and high baudrate. What am I doing wrong? Here is my arduino code.

int val[2000];
void setup()
{
  Serial.begin(250000);

  //ADCSRA = 0;             // clear ADCSRA register
  //ADCSRB = 0;             // clear ADCSRB register
  ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
  //ADCSRA |= bit (ADPS0);                               //   2
  ADCSRA |= bit (ADPS1);                               //   4
  //ADCSRA |= bit (ADPS0) | bit (ADPS1);                 //   8
  //ADCSRA |= bit (ADPS2);                               //  16
  //ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
  //ADCSRA |= bit (ADPS1) | bit (ADPS2);                 //  64
  //ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);   // 128
  //pinMode(A0, INPUT);

}

void loop()
{
  for(int i=0; i<2000; i++) {
    val[i] = analogRead(A0);
  }
  for(int i=0;i<2000;i++){
    Serial.print(val[i]);
    Serial.print('x');
  }

}

P.S I am new to arduino.

--edit1>>
I am using Arduino Mega 2560.

Probably the serial port is too slow:

Assuming 250 kbits/s, is (including 3 start/stop bits, maybe 2 in your case) in about 250000 (bits/s) / 11 (bits/byte)= about 22 KBytes/s
Assuming each sample has 3 or 4 digits and an 'x' is added (which is 5 characters), 22 (KBytes/s) / 5 (digits/sample) = about 5-6 Ksamples/s you can transfer, which is what you experienced.

So you have to increase the speed for the serial port.


While using Arduino Ethernet shield, do we need to explicitly select/Deselect SD and W5100 in our code? It has been mentioned here http://arduino.cc/en/Main/ArduinoEthernetShield that corresponding libraries take care of chip select between SD and W5100 in Arduino Ethernet shield. Does it take care properly all the time? What happens if the Chipselect is not properly managed by libraries? Does that cause blocking of code?

Here we have a nice example of a single Shield requiring TWO libraries. The Ethernet.h and SD.h where the later appears as an after thought and is not demonstrated by the Example. As it is done so in the SD examples. However, their styles are slightly different.

The Ethernet libary as mentioned (provided within) the IDE is hardcoded to implement the Chip Select for the W5100 on corresponding pin. When using the typical purchased Ethernet Shield, there is no need to configure it. Unlike the SD library, which requires the pin to configured using the SD.begin(4) member function.

if (!SD.begin(4)) {
  Serial.println("initialization failed!");
  return;
}

Where again on the typical Ethernet shield the SD card is at pin D4.

Note being hardcode that the Ethernet library selects the matching pin to corresponding shield.

private:
#if defined(ARDUINO_ARCH_AVR)
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  inline static void initSS()    { DDRB  |=  _BV(4); };
  inline static void setSS()     { PORTB &= ~_BV(4); };
  inline static void resetSS()   { PORTB |=  _BV(4); };
#elif defined(__AVR_ATmega32U4__)
  inline static void initSS()    { DDRB  |=  _BV(6); };
  inline static void setSS()     { PORTB &= ~_BV(6); };
  inline static void resetSS()   { PORTB |=  _BV(6); };
#elif defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB162__)
  inline static void initSS()    { DDRB  |=  _BV(0); };
  inline static void setSS()     { PORTB &= ~_BV(0); };
  inline static void resetSS()   { PORTB |=  _BV(0); };
#else
  inline static void initSS()    { DDRB  |=  _BV(2); };
  inline static void setSS()     { PORTB &= ~_BV(2); };
  inline static void resetSS()   { PORTB |=  _BV(2); };
#endif
#endif // ARDUINO_ARCH_AVR

And in the case of the UNO (or the else case) Port B Bit 2 is D10.

worth noting that SD library has an alternate method of initializing and using the SD card

if (!card.init(SPI_HALF_SPEED, chipSelect)) {
  Serial.println("initialization failed. Things to check:");

where chipSelect would be D10 in this case.


Find the time between HIGH state & LOW state of push button(switch) I want to find the timing between HIGH state and LOW state of push button. For that, I made a program. You can see my program below. In my program, I made logic like that when switch is pressed then one variable "currentMillis" store the value of millis() and it store value until button pressed. But whenever I pressed button again then it also add previous value. For example, if button pressed for first time then suppose we got 200ms, now suppose if button pressed second time then we got 500ms and if button pressed third time then we got 1000ms. That mean every time value added. No doubt I made a logic which seem to be perfect but I can't figure out what is problem. Please give me some suggestions.

const int  buttonPin = 2;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
unsigned long finalMillis = 0;

int buttonPushCounter = 0;

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

   pinMode(buttonPin, INPUT);
   digitalWrite(buttonPin, HIGH);
}

void loop()
{
  if (digitalRead(buttonPin) == LOW)
  {
    buttonPushCounter++;
    Serial.println("on");
    Serial.print("number of button pushes:  ");
    Serial.println(buttonPushCounter);

    while(digitalRead(buttonPin) == LOW)
    {
      currentMillis = millis();
    }

    finalMillis = currentMillis - previousMillis;
    Serial.println(finalMillis);

    previousMillis = finalMillis;
    //finalMillis = 0;
  }
}

Here, it is my serial monitor output.

on
number of button pushes:  1
0
on
number of button pushes:  2
775
on
number of button pushes:  3
873
on
number of button pushes:  4
1425
on
number of button pushes:  5
1496
on
number of button pushes:  6
2073
on
number of button pushes:  7
2010
on
number of button pushes:  8
2643
on
number of button pushes:  9
3052
on
number of button pushes:  10
3195
on
number of button pushes:  11
3396
on
number of button pushes:  12
3575
on
number of button pushes:  13
3737

First of all, frarugi87 is right.
Second, why not use this:

finalMillis = millis() - previousMillis;
previousMillis = millis();

Instead of what you wrote.

if (digitalRead(buttonPin) == LOW) {
    buttonPushCounter++;
    Serial.println("on");
    Serial.print("number of button pushes:  ");
    Serial.println(buttonPushCounter);
    finalMillis = millis() - previousMillis;
    previousMillis = millis();
    Serial.println(finalMillis);
    while(digitalRead(buttonPin) == LOW){}
  }

It works great.

Hope it helps.

Yoav


Is there any library for use Arduino Uno with esp8266-01 module? I have a Arduino Uno and the esp8266 module,(NOT THE SHIELD).

I was looking for some library that I could use to connect to Wifi and set a webserver, but I can't find anything. I just found for Arduino Wifi Shield which uses SPI.

It is possible to use arduino lets say to read a LM35 and then send that data to the ESP8266 module and serve it in a page as webserver?

I know that I can use AT commands with ESP8266 to connect to wifi and to create a server, but I cannot find any function to set the data to be served.

https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf

Why involve the UNO at all.  The ESP88266 could be programmed with the Arduino IDE to read the sensor and deal with the internet all by itself.  It doesn't need the UNO to do what you want.


Arduino Pico doesn't work with ST7735 screen I am attempting to get the graphicstest example bundled with the Adafruit ST7735 library for the 0.96 inch LCD screen.
The example runs fine and serial communication is up and running. However, nothing outputs on the screen. I verified that the code works with other Arduino boards and that I have it properly wired -> SCK to SCL, MOSI to SDA, etc.
I'm not sure if I am doing something wrong, or if this is a limitation of the board.
Edit: I added the modified graphicstest code to the Internet, it can be found here: https://drive.google.com/file/d/1cFOgQXhhH1vou0KUrFzBDMp0iiIp1Yuy/view?usp=sharing
I also added a crude diagram of how the screen is wired up to the Pico. Note that the LCD is powered externally since the Pico cannot handle the current draw of powering the LCD.
https://drive.google.com/file/d/1RmZSHBcelwC9caLoQC9iE5Lb4eHG9S2O/view?usp=sharing

I found out the problem. I was trying to connect to the SCK and MOSI pins on the back of the Pico. Later research shows that these are meant for programming and burning a bootloader onto the microprocessor.
The Adafruit library allowed me to define my own pins for SCK and MOSI.
Once I switched to using the Adafruit_ST7735(int8_t cs, int8_t dc, int8_t mosi, int8_t sclk, int8_t rst) constructor, it worked after that.


What do these operators do? Going through the "timeouts" example of the elapsedMillis library (https://github.com/pfeerick/elapsedMillis) I found the following statement:

digitalWrite(LEDPIN, flashPattern[ledIndex++] ? ledBrightness : !ledBrightness);

flashpattern is an array of boolean variables  (boolean flashPattern[] = { 1,1,1,1,1,1,1,0,1,1,0 };)
ledBrightness is a boolean as well.

What does the "?" and the ":" do there? are these boolean operators?

They are the conditional operator. If the expression before the ? is true then the result is the expression before the :, otherwise it is the expression after.


Interrupt fires a random number of multiple times for one pulse This is my first time posting on this forum. I have tried to format this question properly, but let me know if I need to correct anything. I searched to see if someone else had a similar problem, but let me know if someone has already answered this question.

Overview: I am sending pulses to my Arduino, but sometimes one single pulse is interpreted as anywhere from 2 to 30 pulses. But after looking at the pulse on an oscilloscope (see Fig. 1) I am not sure why. When I use a really long wire the ratio of false pulses to legit pulses is about 1 to 1. I shortened the length of the wire and improved the situation, so that only 1 in about every 2,000 pulses is registered as a false pulse.

For one test, I added a capacitor to the short wire situation, but that increased the rise time and made the problem worse. I am currently using attachinterrupt and have tested the situation with using both a rising and falling edge. Right now, I mainly want to understand how interrupts work on the Arduino in light of my current problem, although I welcome general advice.

When I set the interrupt to the falling edge, why does the Arduino still sometimes count 1 pulse as several? The falling edge in the photo, which is for the really long wire case, lasts about 40 microseconds and appears to have a clean break. The pulse remains low for about 80 milliseconds. Could the falling interrupt trigger during the rise time based off the oscillatory behavior shown in Fig. 1? I smoothed out the signal by adding in a 1 nF capacitor, but the Arduino still counted false pulses. So could the rise time period have anything to do with it? I also have a 10k Ohm pullup resistor connected to the Arduino's 5 V for the pulse path.

I have the relevant code attached below. I have much more code as well, but it deals with saving pulseCounts to the SD Card and uploading electricity consumption files through the cell network.

Cheers.

//Global Variables
unsigned long pulse_time = 0;
unsigned long last_pulse_time = 0;
byte code = 1; //code let's me see if a false pulse was reported for each
//SD file

void setup() {
  attachInterrupt(digitalPinToInterrupt(3), onPulse, RISING);
}

void onPulse() {
  pulse_time = millis();
  if ((pulse_time - last_pulse_time) > 50 ) {
    Serial.println("Good Pulse");
    pulseCount++;
    last_pulse_time = pulse_time;
  } else {
    Serial.println("Bad Pulse");
    pulseCount++;
    code = 2;
  }
}

Firstly, unless the processor pin is a Schmitt trigger, increasing capacitance will only make the problem worse by allowing any noise to be interpreted as multiple high-low transitions.  For a CMOS logic input the area around the transition point of 1/2 VDD typical is actually an area of linear operation, not digital.

A Schmitt trigger introduces hysteresis such that when the signal is interpreted as a high level, it must go low by more than the hysteresis to be interpreted as a low level again.  This is accomplished with a bit of positive feedback added to a buffer where the output transition from low to high then pulls the input that much higher or a transition from high to low pulls the input that much lower:

The red line represents the typical CMOS threshold and the green lines represent the thresholds defined by the hysteresis of the Schmitt trigger.  The hysteresis defines the noise immunity of the input.  Most processors have pins that are equipped with a Schmitt trigger or and external device like a 74HC14 can be used.

Another way to deal with this type of noise is to lock out any transitions within the expected pulse-to-pulse transitions:  Once triggered, no more transitions are allowed until the lock out time expires.


Can I drive an LM334(Z) from an Arduino with AnalogWrite()? I need programmable current control, fading from zero to 2 milliAmps.  I was hoping to use Arduino's AnalogWrite(), which uses Phase Width Modulation (PWM) to simulate analog output with a sawtooth wave on a duty-cycle; to control an LM334Z to deliver a slowly ramped low current delivery.
[The application is a TransCranial Direct Current Stimulation (TDCS) micro-current delivery to the human scalp. Jumping straight to 2 milliAmps is uncomfortable].
Will PWM work? Or, do I need some sort of smoothing circuitry to soften the PMW before it is applied to the LM334Z's Rset pin to accomplish the above?

If you don't need super high accuracy, using a MOSFET's ohmic region, plus a smoothing filter on the output of your PWM (analog out), could be a solution.


ATTiny85 Interrupt id vs pin when programming with Arduino I am using an Arduino Uno with the Arduino as ISP sketch to program an ATtiny85.

I followed this tutorial to set up to program the ATtiny, and successfully got it to run Blink and an interrupt-free version of my program.

I then added an interrupt triggered by a button and got it working on the Arduino Uno (with a software debounce in the ISR). Now I want to run that sketch, with appropriate pin changes, on the ATtiny. Which pins correspond to which interrupt IDs for attachInterrupt()?

Or can I not use attachInterrupt()? If I can't, how do I do set up an interrupt on an ATtiny85?

You can setup interrupts on the Attiny with some different code, but it works the same way. It's important to note that PIN Change Interrupts are triggered at BOTH Rising and Falling Edge

Pins:

Using the Arduino-Tiny Cores

Below is a sample code which used a Pin Change Interrupt on PB1 which switches an LED on and off on PB4.

//Includes
#include <avr/io.h>
#include <avr/interrupt.h>

#define INTERRUPTPIN PCINT1 //this is PB1 per the schematic
#define PCINT_VECTOR PCINT0_vect  //this step is not necessary
#define DATADIRECTIONPIN DDB1 //Page 64 of data sheet
#define PORTPIN PB1 //Page 64
#define READPIN PINB1 //page 64
#define LEDPIN 4 //PB4

#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) //OR
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) //AND

/*
 * Alias for the ISR: "PCINT_VECTOR" (Note: There is only one PCINT ISR.
 * PCINT0 in the name for the ISR was confusing to me at first,
 * hence the Alias, but it's how the datasheet refers to it)
 */

static volatile byte LEDState; //variable used within ISR must be declared Volatile.

void setup() {
    cli();//disable interrupts during setup
    pinMode(LEDPIN, OUTPUT); //we can use standard arduino style for this as an example
    digitalWrite(LEDPIN, LOW); //set the LED to LOW
    LEDState = 0; //we use 0 for Low state and 1 for High
    PCMSK |= (1 << INTERRUPTPIN); //sbi(PCMSK,INTERRUPTPIN) also works but I think this is more clear // tell pin change mask to listen to pin2 /pb3 //SBI
    GIMSK |= (1 << PCIE);   // enable PCINT interrupt in the general interrupt mask //SBI

    DDRB &= ~(1 << DATADIRECTIONPIN); //cbi(DDRB, DATADIRECTIONPIN);//  set up as input  - pin2 clear bit  - set to zero
    PORTB |= (1<< PORTPIN); //cbi(PORTB, PORTPIN);// disable pull-up. hook up pulldown resistor. - set to zero
    sei(); //last line of setup - enable interrupts after setup

}

void loop() {
  // put your main code here, to run repeatedly:
  //If you connect a debounced pushbutton to PB2 and to VCC you can tap the button and the LED will come on
  //tap the button again and the LED will turn off.

}

//this is the interrupt handler
ISR(PCINT_VECTOR)
{
  //Since the PCINTn triggers on both rising and falling edge let's just looks for rising edge
  //i.e. pin goes to 5v
  byte pinState;
  pinState = (PINB >> READPIN)& 1; //PINB is the register to read the state of the pins
  if (pinState >0) //look at the pin state on the pin PINB register- returns 1 if high
  {
   if (LEDState == 0)
   {
    digitalWrite(LEDPIN,HIGH); //you can use Arduino Code or LowerLevel Code to write to the register
    LEDState = 1;
    }
   else
   {
    digitalWrite(LEDPIN,LOW);
    LEDState = 0;
    }
  }

}

If you're going to be using the ATTiny85, I highly suggest you read through the data sheet to understand better how to program these chips at a lower level of code....It took me a while for it to start to make sense.


How to use ADC interrupt on STM32 blue pill I'm currently using the STM32F1xx boards from http://dan.drown.org/stm32duino/package_STM32duino_index.json
To program my blue pill but I can’t find how to write the interrupt for the ADC. I’ve set the registers to output an interrupt when it finishes but I can’t find how to write the code for the interrupt.
I’ve tried the ”ISR(ADC_vect)” function which works for arduino, but the compiler is complaining that ”ISR” is not recognized. I’ve tried to look for the documentation for the STM32duino, but the little I could find didn’t even mention the ADC or any interrupt routines. I’ve searched though the STM32duino forum without any luck. If anyone knows how to solve this or where to find information about interrupt code for the STM32 boards I would be very happy :)

I couldn't find the function being called directly, but there's a good example explaining how to attach interrupts to the ADC which works well: https://github.com/rogerclarkmelbourne/Arduino_STM32/blob/master/STM32F1/libraries/STM32ADC/examples/SingleConversionInterrupt/SingleConversionInterrupt.ino
If anyone knows the actual function being called directly that would be great to add on here, but until then this example does what I need and will hopefully help others having the same problem.


How fast is flash reading compared to SRAM? I'm working on a project that will eventually scale to 864 LEDs on WS2815 LED strips (three rows of 288 LEDs). I'm currently running it on an Arduino Uno with a single test strip of 144 LEDs.

FastLED stores its data in 3-byte structs, so I obviously cannot simply hold all of the data in SRAM and work with it directly (at least not without upgrading to a controller with more memory). I'm going to use a Raspberry Pi to send the Arduino data, one section at a time. To further save memory, I want to implement an RGB color lookup table in flash, then instead of

CRGB pixels[PIXEL_COUNT];

taking up over 2KiB of memory 800+ values, or

CRGB pixels[PIXEL_BUFFER_COUNT];

with a buffer of 288 RGB values consuming most of my working memory (864 bytes), I would have

CRGB *pixels[PIXEL_BUFFER_COUNT];

Where each pointer would reference a location in a PROGMEM 256-entry table of CRGB values. This is a more manageable 576 bytes in SRAM.

I realize FastLED does not work this way. There's a  lot of work ahead of me if I do this, but before I get started, my question:

Will I run into issues with reading the actual data from flash memory while sending to the LED strips? As currently implemented in FastLED, RGB data is in SRAM, but each pointer dereference will require reading from flash. Is the subsequent delay enough that it will cause an issue with sending data to the strips?

On an Arduino Uno, or other AVR-based Arduino, reading a byte from RAM
takes 2 CPU cycles. Reading it from flash takes 3 cycles. So flash vs.
RAM is not such a high overhead. However, if you store a LUT in flash,
and the color indexes in RAM, then each pixel would require:

2 cycles for reading the color index from RAM
3 × 3 cycles for reading the RGB values from flash.

That's a total of 11 cycles, vs. 6 cycles it would take to read the RGB
values from RAM, as is done in the stock FastLED library.

It sounds bad, but it could be that the precise timing is not such a big
issue. I don't know the WS2815, but if they are similar to the WS2812,
then you don't need to be anywhere as precise with the timings as the
datasheet suggests. C.f. the blog post NeoPixels Revealed: How to (not
need to) generate precisely timed signals.

Edit: there will be a few more cycles needed for the pointer
arithmetic. I estimate something around 7 cycles. At low level, the code
for getting a color should look roughly like this:

uint8_t *pixel = ...;
uint8_t index = *pixel;            // read from RAM: 2 cycles
uint8_t pgm_p;                     // pointer to flash
pgm_p = &pgm_lut + 3 * index;      // pointer arithmetic: ≥ 7 cycles
struct CRGB color;
color.r = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.g = pgm_read_byte(pgm_p++);  // read from flash: 3 cycles
color.b = pgm_read_byte(pgm_p);    // read from flash: 3 cycles


Arduino binary LED 10 bit display I'm working on a simple ADC project, the goal is to adjust the on/off of the LEDs according to the binary reading (1-on,0-off). I've tried this with 8 bit, and it works as intended. But on 10 bit, two of the LEDs with representation of 2^8 and 2^9 won't turn on even though the reading on the serial monitor is 1023 (should be 1111111111 -all LEDs on). I wonder if there's anything wrong with my code or circuit?
(I'm totally new to arduino, sorry for the noobness)
-I'm using Arduino UNO R3, the details are shown in the image
void setup(){
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

  Serial.begin(9600);
}

void loop(){
  int sensorValue = analogRead(A0);
  Serial.print("Decimal=");
  Serial.print(sensorValue);
  Serial.print("\tBinary=");
  Serial.println(sensorValue,BIN);

  if(sensorValue>=0&&sensorValue<=1023){
    digitalWrite(4,(sensorValue&1));
    digitalWrite(5,(sensorValue&2));
    digitalWrite(6,(sensorValue&4));
    digitalWrite(7,(sensorValue&8));
    digitalWrite(8,(sensorValue&16));
    digitalWrite(9,(sensorValue&32));
    digitalWrite(10,(sensorValue&64));
    digitalWrite(11,(sensorValue&128));
    digitalWrite(12,(sensorValue&256));
    digitalWrite(13,(sensorValue&512));
  }
  delay(20);
}

According to the official documentation, the second parameter of
digitalWrite() should be either HIGH or LOW. Thus, in order to be
compliant with the published API, you are supposed to write:
digitalWrite(12, sensorValue&256 ? HIGH : LOW);

In practice, digitalWrite() interprets any non-zero value as HIGH.
However, its prototype is:
void digitalWrite(uint8_t pin, uint8_t val);

Both parameters have the type uint8_t, which means “8-bit unsigned
integer”. If you provide a value that doesn't fit in 8 bits, the
implicit cast to uint8_t will reduce it modulo 28. Thus,
both 256 and 512 become zero through the implicit cast.


waking up arduino mini with a external signal I have an arduino mini with an ultrasonic sensor conected to the pins 2 and 3, and a RGB LED connected to the 4,5, and 6, I want to include a wake up and sleep functionality that wakes up when receive a high signal in another pin as 7.

I have seen that normaly the pins for that are 2 and 3, as in the arduino web: Arduino sleep web

But can it be done with another pin?

Arduino Mini has only two interrupt capable pins: 2 and 3. You have to move your sensor to other pin.

From the AtMega328p datasheet:

  If a level triggered interrupt is used for wake-up from Power-down,
  the required level must be held long enough for the MCU to complete
  the wake-up to trigger the level interrupt. If the level disappears
  before the end of the Start-up Time, the MCU will still wake up, but
  no interrupt will be generated. The start-up time is defined by the
  SUT and CKSEL Fuses.


Run piece of code based on a feature I am an engineering student completely new at using Arduino so my following question might be silly but still. I do not think you'll need to get the entire code so I am only going to expose the idea.
So basically, I would like a customer to choose a feature between three of them (let's name them 1, 2, 3). Depending on the feature he chose, the corresponding setup() and the corresponding loop() have to run. For example, if he chooses the second feature, in the main setup(), the setup2() has to run and in the main loop(), the loop2() has to run only. The other setup() functions and loop() functions have to do nothing. I first thought I could do this using switch cases but I am looking for another way to implement that as a teacher told me this method would take too much time.

void setup() {

      setup1(); //only runs if 1st feature chosen
      setup2();
      setup3();
}

void loop() {

      loop1(); //only runs if 1st feature chosen
      loop2();
      loop3();
}

And also, I wrote the three setup() and the three loop() in different files (of course, setup1() is in the same file as a loop1(), etc., ...). Is it possible to include them in the main file (for instance, like <#include nameoffile.h)?

You probably want to do something like this:

typedef enum { FEATURE1, FEATURE2, FEATURE3 } Feature;

//implement these
Feature getFeatureFromUser(){}
void setup1(){}
void setup2(){}
void setup3(){}
void loop1(){}
void loop2(){}
void loop3(){}

void setup() {
  Feature f = getFeatureFromUser();

  switch (f) {
    case FEATURE1:
      setup1();
      while (true) {
        loop1();
        if (serialEventRun) serialEventRun();
      }
    case FEATURE2:
      setup2();
      while (true) {
        loop2();
        if (serialEventRun) serialEventRun();
      }
    case FEATURE3:
      setup3();
      while (true) {
        loop3();
        if (serialEventRun) serialEventRun();
      }
  }
}

//never reached
void loop() {}

It's good to know that there's no hard rules about how the Arduino functions should be used. Examples like this demonstrate how Arduino's standard requirements of void setup() and void loop() don't quite match every use case.

EDIT: The serialEventRun lines are normally called behind the scenes after each execution of Arduino's normal loop(), so adding them here will result in the standard behavior of serial events


Managing 2 ultrasonic sensors without blocking the other I have an ultrasonic distance sensor. When this sensor is measuring a distance below 25 cm, a second sensor has to be measuring a distance below 5 cm. If not, there should be a one minute timespan, after which a speaker should make noise until the second sensor is measuring a distance below 5 cm.

I am having trouble with this. The first sensor has a lot of code it should be running as well, so using a while-loop to wait out one minute for the other sensor and creating noise after that isn't a possibility.

How do I go about this dilemma? I read into interrupts in Arduino but unfortunately I don't know how I'd make this work.

I strongly advice you to use interrupts and make sure the sensors are in a cylindrical cone in order to prevent interference to each others as much as possible.

Here is code snippet which can give you an idea how the interrupts are set and used. I believe that you can adapt it to yours. It is from Arduino forum (link), credits to "cattledog".

volatile unsigned long LastPulseTimeA;
volatile unsigned long LastPulseTimeB;
int durationA;
int durationB;
//unsigned long startTime;
#define trigPinA 7
#define echoPinA 2
#define trigPinB 8
#define echoPinB 3
void setup() {
  Serial.begin (9600);
  pinMode(trigPinA, OUTPUT);
  pinMode(echoPinA, INPUT);
   pinMode(trigPinB, OUTPUT);
  pinMode(echoPinB, INPUT);
attachInterrupt(digitalPinToInterrupt(echoPinA), EchoPinA_ISR, CHANGE);  // Pin 2 interrupt on any change
attachInterrupt(digitalPinToInterrupt(echoPinB),EchoPinB_ISR, CHANGE);  // Pin3 interrupt on any change
}
void loop(){
  digitalWrite(trigPinA, LOW);
  digitalWrite(trigPinB, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPinA, HIGH);
  digitalWrite(trigPinB, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPinA, LOW);
  digitalWrite(trigPinB, LOW);
  Serial.print("Sensor A  ");
  Serial.print(LastPulseTimeA);
  Serial.print('\t');
  Serial.print((LastPulseTimeA/2) / 29.1,1);
  Serial.println("cm");
  Serial.print("Sensor B  ");
  Serial.print(LastPulseTimeB);
  Serial.print('\t');
  Serial.print((LastPulseTimeB/2) / 29.1,1);
  Serial.println("cm");

  delay(1000);
}
void EchoPinA_ISR() {
    static unsigned long startTimeA;

    if (digitalRead(echoPinA)) // Gone HIGH
        startTimeA = micros();
    else  // Gone LOW
        LastPulseTimeA = micros() - startTimeA;
}
void EchoPinB_ISR() {
    static unsigned long startTimeB;

    if (digitalRead(echoPinB)) // Gone HIGH
        startTimeB = micros();
    else  // Gone LOW
        LastPulseTimeB = micros() - startTimeB;
}


Can Chirp Waves be sent using JSN-SR04T? So i have project for underwater rangefinding using JSN-SR04T. I've read on the datasheet that the module sends square waves. Is it possible to program it so that it sends Chirp waves instead ? (Help with the coding is very appreciated)
Thanks in advance

As I googled the sensor, I found various sites stating, that a JSN-SR04T behaves exactly like the HC-SR04. The difference is mainly the water prooving.

So the answer is: No, you can't do this. The square wave, which drives the ultrasonic transducers, is generated by a hardware circuit and is not meant to be changed. To output a chirp wave you would need to rebuild the signal generation and measurement hardware (leaving only the transducers unchanged). At that point you may just buy the pure ultrasonic transducers and build the rest yourself.


Problem with transmitting 2 byte data in correct way I'm using Atmel Studio with Atmega328P.

I'm trying to send the decimal number 876 continuously from the micro-controller. This was just to learn.

To send 876 I need two bytes which is:

0x036C = 00000011 01101100

So I manipulated a code and here is what I use now:

#include <avr/io.h>
#define F_CPU 16000000
#define USART_BAUDRATE 9600
#define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

void USART0Init(void)
{
    // Set baud rate
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    // Set frame format to 8 data bits, no parity, 1 stop bit
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //enable transmission and reception
    UCSR0B |= (1<<TXEN0);
}

int main (void)
{
    //Initialize USART0
    USART0Init();

    while(1)
    {

        UDR0 = 0b00000011;
        UDR0 = 0b01101100;

    }

}

The problem is at the receiving side the data comes as:

01101100
00000011
00000011
.
.
.

Here is the screen shot of the binary data at the receiving end:

However it should be received correctly as two byte chunks 00000011 01101100.

And here you can see the problem of the data being received as uint16(not only 876 as desired):

How can I fix this and receive the data properly as two bytes with correct order as 876?

First, you want to determine what you are trying to send. Send data in binary form is rare.

Secondly, you want to wait for each transmission to send before starting the next one.


What is the purpose of Galileo (or other unremovable chips) I know the Arduino is a nice quick and dirty prototyping board. You quickly test your idea, and if you want to proceed you can do so with AVRs.

Your options are:

Upload the program to Arduino, then remove the AVR chip and make a PCB (with the bootloader)
Start from scratch with AVR (not always feasible because many libs are in Arduino)

Now what is the purpose of a system that has processors that cannot be removed? For example the Arduino Galileo.

Sure, you can do many things with it, but bottom line, you cannot remove the processor and do something with it.

As an example, imagine you are prototyping a system you wish to, then, market and sell. That is feasible with the Arduino Uno family.

But what if you did in in Galileo? Even if it worked, you couldn't sell your system because you rely on the prototyping board. You cannot remove the processor.

Am i missing something?

Edit: As Chris points out, this answer is more about the simple AVR Arduinos. For comment on the Galileo and other more complex MCUs, please refer to Chris' answer.

For Arduino compatibility you can program the Arduino boot loader into the microcontroller using the ICSP pins. You do not need a chip from an Arduino board, you just solder a blank one in. Once the boot loader is on there you can use the Arduino IDE to upload sketches via the UART.

It is not necessary to use the Arduino system to write programs. You include the Arduino library files in a normal C++ project in many different IDEs and use the avr toolchain to compile and avrdude to upload.

Update:

Here is an example of a board I just got back from PCBA. (The picture was sent by the PCB company for checking). Initially I made the board using an Arduino Pro Mini 3.3V, SD card breakout board, LSM303DHLC accelerometer breakout from Pololu, and Real Time Clock (RTC) breakout. Once everything was working I drew up a PCB in Eagle CAD, using the core of Arduino Pro Mini board plus the individual SD card, LSM303DLHC and RTC chips. I also added a 3.3V boost converter so I could get a constant 3.3V off 2 AA batteries.

The board has the ICSP pins broken out. Actually, you will find they are broken out on most Arduino boards. Using another Arduino as ISP I can program the Arduino boot loader via the ICSP pins, and then sketches can be uploaded via the UART using the Arduino IDE. In the IDE the board that is selected is "Arduino Pro Mini 3.3V 8MHz".

The Arduino boot loader is a small piece of firmware that runs on startup. It allows you to send a program over the UART which it stores into FLASH memory itself. It is not absolutely necessary. You can program the chip using the ICSP as well. It is really convenient however. Using software like xloader you can upload Arduino programs without the IDE. Really handy when other people are using the board and you don't want to share your code. Alternatively, you can write a script for avrdude to do it.

This project is for a university so I'm leaving it as Arduino compatible. In a commercial engineering environment, I would choose a more appropriate MCU (one with lower power consumption for a battery device) and rewrite the program to be more efficient and not rely on the Arduino and third-party libraries.


Check if Arduino Uno connected with PC I'm using Arduino Uno controller

How it is possible to know if controller connected to PC via USB, to detect if wire is plugged and get condition for variable in sketch.

I've tried Serial.available(), but I'm not sure, if I can do it this way:

if (Serial.available())
{
   val = true;
}
else
{
   val = false;
}

I want use this condition to avoid setup() commands by some unexpected reason in case if controller powered only with adapter

You can't determine if there is a valid USB source on the UNO without modifications, because the Atmega328P just receives serial data when the host sends some data. Some approaches that you can keep in mind.

If you want to determine whether you are connected through the USB or barrel connector, you can connect an analog pin to the Vin pin through a voltage divider (you should calculate the values so that you do not exceed 5V on the analog pin). This way if you detect a voltage greater than 6.6V you will know that you are being powered from the barrel jack.
If you want to detect a particular PC, you can write a SW in the PC which scans for new ports, then opens them and sends a particular string. If you receive that within X seconds, you know that you are connected to the PC
If you want to determine if you are connected to any valid PC, then I think you will need to modify the program in the Atmega16u2 which is used as a serial bridge between the two. I'm not sure whether it is possible or not, but I think that the Atmega16u2 knows when a valid USB session is started, and so can tell the Atmega328 this information (through the serial interface)


How to hook up an LED strip to an Arduino I want to add 6 LEDs  under my Arduino case and have the Arduino Uno pulsate the colors. How do I do this?

Depends on what they are and how much you don't know :-)

I'd suggest starting off by looking at the tutorials for NeoPixels and DotStars on Adafruit's site – that should give you a general idea of how things work. Then take a look at the FastLED library, it supports a large number of LED strips and has some decent examples.

The FastLED examples that will show up in the Arduino IDE after you have installed the library.

Once you've gotten as far as identifying the strip you have and reading some of the basic tutorials and trying out some of the examples you'll either know how to do it or have some much more specific questions to ask.

OK, after looking at the info on Amazon and looking more closely at the strip (and the price). I don't think these are individually addressable LEDs. More likely the RGB lines are grounds. So what you would do is to provide a +12V supply on the 12V line and ground one or more the RGB lines to turn on that LED. You could probably control brightness with PWM (pulse width modulation, turning them on and off quickly). The catch here is that the current draw will be more than the Arduino can sink and it's at 12V – two quick ways to kill your board in one tidy package.

You'll need to do more research on this to get the details right, but I think you could use a transistor to do the switching (to protect your Arduino for the 12 V and from the current necessary to drive the LEDs). You would connect an Arduino pin to the base of the transistor to control it. You'd need to select a transistor that can handle the current of all of the LEDs of that color. As a guess I'd figure 60 mA per LED at full brightness (for each color) – this is based on NeoPixels running at 5 V so I could be way off.

If I'm right that these are not individually addressable then the programming would be relatively easy – just turn on the output to turn on the color.

I'd start off by cutting off a strip of the LEDs to experiment with. Use the 12V supply that came with them and see what happens when you connect 12 V to the 12V line and ground one of the color lines. It doesn't look like there is a resistor to limit current, so you should add one to hold the current down. I think the LEDs would be wired in parallel, so you'd be looking at needing to supply 6 times the individual LED current. To be safe you could start at around 20 mA and use a 100Ω 1W resistor – you can find an LED resistor calculator here, be sure to select the parallel calculation and use a low current to start with to be safe.

Once you know that the strip works the way you think it does, try adding a transistor to control each color. Then when you've got that working, hook up to the Arduino. Just remember that you will also need to respect the Arduino's current and voltage limits on the digital pins.


MKR1000 and DS18B20 temperature sensor I am new to Arduino and electronics in general and I can't get my MKR1000 to read correct data from a DS18B20 temperature sensor.

Here is the tutorial I followed.

The issue is: I always get the same readings from the sensor: -127.00.

I should mention I have tried 2 different sensors and get the same readings.

From the sensor, GND goes directly to GND on the board, and I have the 4.7kΩ resistor in between the data and power wires.

According to the sensor manufacturer, output leads: Yellow (VCC), Red (DATA), Black (GND).

Data line is connected to the pin ~2 on the MKR1000.

/********************************************************************/
// First we include the libraries
#include <OneWire.h>
#include <DallasTemperature.h>
/********************************************************************/
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2
/********************************************************************/
// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
/********************************************************************/
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
/********************************************************************/
void setup(void)
{
 // start serial port
 Serial.begin(9600);
 Serial.println("Dallas Temperature IC Control Library Demo");
 // Start up the library
 sensors.begin();
}
void loop(void)
{
 // call sensors.requestTemperatures() to issue a global temperature
 // request to all devices on the bus
/********************************************************************/
 Serial.print(" Requesting temperatures...");
 sensors.requestTemperatures(); // Send the command to get temperature readings
 Serial.println("DONE");
/********************************************************************/
 Serial.print("Temperature is: ");
 Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
   // You can have more than one DS18B20 on the same bus.
   // 0 refers to the first IC on the wire
   delay(1000);
}

Any idea what I am doing wrong?

Looks like you have it wired wrong.  A schematic would really help but it looks like you've got 5V going directly into the sensors data line (yellow wire) it's connected on your breadboard to the orange wire +5V.  The power wire of your temperature sensor (red wire) is running through a 4.7K resistor which is not likely what you wanted here either.


Connecting a Long Stem Thermometer to an Arduino to automate the recording of temperature in an experiment Is there a way to connect and read the output of a long stem thermometer like this one to an Arduino?

Interfacing with a temperature sensor such as the DS18B20 (https://www.sparkfun.com/products/11050) would be much simpler than trying to interface with a thermometer with unknown internals.

Theoretically, yes, you can use the thermometer you posted, but it won't be simple. The only way to know what you would have to do to interface with it is to open it up and see what's inside. You would still have to calibrate it though to make any sense of the readings you get from it.


How to send IR data from Arduino to USB-TTL I have a led receiver KY-022 and led emitter KY-005, I also have a PL2303 (USB-TTL). This is the code of the issuing LED:

#include <IRremote.h>
IRsend irsend;

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

void loop()
{
   for (int i = 0; i < 50; i++) {
     irsend.sendSony(0xa90, 12); // Sony TV power code
     //Serial.print(0xa90,HEX);
     delay(40);
   }
}

The following is the connection scheme:

The output of the KY-022 I have connected to the pin RXD of the PL2303 which has a led that indicates that it receives data, however when using the HyperTerminal program to see the data I receive nothing appears.

I found similar information but they use another LED model, however I think it should work the same. What can I do?

I'm also testing with node js using the node js package, but in the console I only get non-readable characters, or something like this Buffer 00 e0 e0 e0 e0 if I do not apply toString () to the data.

This is my code in node JS.

var SerialPort = require('serialport');
var io = require('socket.io').listen(3000);

var serialPort = new SerialPort("COM9", {
    baudRate: 9600,
    parser: new SerialPort.parsers.Readline("\n")
});

io.sockets.on('connection', function(socket){
    socket.on('message', function(msg){
        console.log(msg);
    });

    socket.on('disconnected', function(){
        console.log('disconnected');
    });
});

var clearData = "";
var readData = "";

serialPort.on('open',function(){
    console.log('open');
    serialPort.on('data', function(data){
        console.log(data);
        readData += data.toString();
        io.sockets.emit('message',data);
    });
});

You are transmitting data by encoding it using one of probably many Sony Consumer Remote Control formats and expecting to decode it using one of many possible RS232 like formats.  You will likely get something between nothing and random values.

Instead, consider sending data using only the RS232 protocols.  This is what is done in this tutorial.  It is recommended you replicate the tutorial before moving on to using a TTL to USB dongle and a computer.  This should validate the transmitter is working.  Note in the tutorial transmitter code example no IR  remote control library is used.  Only the common serial libraries.

A word regarding the tutorial.  Consider using the second of the two examples in the tutorial.  The first does not modulate the IR transmitter and will not work with commonly available IR receivers.  The second does modulate the IR transmitter and discusses how to alter the modulation to accommodate different IR receivers.


Differing Serial Values Between Arduino Uno and TTGO ESP32 SX1276 I'm wanting to analogRead the value off a MQ-135 gas sensor. I have tired this with both an Arduino Uno and an TTGO ESP32 SX1276.

When reading the value of the sensor off the Uno, I get values approximately equal to 400 which is expected, as shown in this video. When doing the same on the TTGO, I get values close to 2000. For some reason, this person gets a similar value range as shown in this video.

What I don't understand is how these values are different when only the board is being changed. Do different boards analogRead differently?

More or less, how do I get the TTGO to read the same values as the Uno?

Below is my code for both boards. Nothing is changed between the boards:

#define sensor 2 //sensor pin

int gasLevel = 0; //int variable for gas level

void setup() {
  Serial.begin(9600); //start serial comms
  pinMode(sensor,INPUT); //set sensor for input
}

void loop() {
  gasLevel = analogRead(sensor);
  Serial.println(gasLevel);
  delay(1000);
}

The following things I have tested:

Multiple boards of both the Arduino Uno and TTGO
Different pins, both analog and digital

I also am powering the sensor using 3.3V pin, so there is no variation in the voltage the sensor is receiving.

Do different boards analogRead differently?

Yes.

Your typical Arduino has a 10-bit ADC. That can give values between 0 and 1023 (210-1), with 400 falling just short of half way.

The ESP32 has a 12-bit ADC. That gives values between 0 and 4095 (212-1), which means that your 2000 falls, yes, just short of half way.

It is not the value from the ADC that is important - it is what the value represents. It is meaningless until you convert it into something meaningful, like a voltage.

Like asking "How heavy is it?" -- "It's 23." Completely meaningless, until you qualify it with units, and the units are different because of the different resolutions, so you need to "convert" it into units that have a meaning.

Typically the value represents a proportion of the supply voltage (but not necessarily: it's actually a proportion of the ADC reference voltage, which is often the same thing as the supply voltage).  On the Arduino the value is 1/1024th of the supply voltage. On the ESP32 it's 1/4096th.


How to stop transmission i2c on LCD 16x4 i2c i want to try to stop communicaton I2C between arduino and lcd I2C but i don't see any command to stop this communication. I try with Wire.endTransmission or Wire.end but the transmission to the LCD continue without problem. I'm using this library NewliquidCrystal and inside no command for end transmission. I need to interupt that communicaton for have a good management of lcd or if know a new library with best features. Thank's for help

I need to interupt that communicaton for have a good management of lcd or if know a new library with best features. Thank's for help

This sounds like a classical X-Y problem. You have decided on a solution and asking about some "magic" functionality without understanding the library or how the I2C bus works.
It would be better to try to describe the original issue, investigate, propose and discuss solutions. Basically better understand the original issue.
Back to your question:

Wire.endTransmission()

does not really do what you think. It marks the end of a block to be transmitted (previous Wire.write()) and starts the actual transmission to the slave.
This is what the manual says:

Wire.endTransmission()
Description
Ends a transmission to a slave device that was begun by beginTransmission() and transmits the bytes that were queued by write().


About multiple void loops and functions I'm still a beginner at Arduino coding -- I've been researching on how to make functions using void instead of doing goto because reasons...

one thing I've noticed about void is that it has this void loop() {...} parenthesis, what is it for? (and can you provide an example of using it?)

say I make a void function void function1() to call the function I have to use function1(); can I make a function that loops? like the ol' void loop() {...} command we all know and love or do all void functions loop? if not then what happens to a void function after it reaches the end of its function?

The void in front of the function definition just tells what type the function returns.  In the case of void it means the function returns nothing.  If the function returned an int then it would be defined with int instead of void.

eg:

int addNumbers(int num1, int num2){
    int retval = num1 + num2;
    return retval;
}

int sum = addNumbers(3, 4);
Serial.print(sum);  // prints 7

No, the loop only loops because main (see main.cpp in the core) is the "real" program that is running on your micro and it calls loop over and over.  It's not that the loop function on it's own repeats.  It is literally being called repeatedly by the main function.

That example also gets to what the parenthesis are for.  That's where the arguments that the function takes go.  In the function definition you tell it what types they'll be and give them names.  In the function call you put in whatever values you want to function to use.  In the case of void loop(), it takes no arguments so the parenthesis are empty.

I would suggest you look at a basic tutorial on C++.  There are many good ones on the web.  The concept of functions isn't something that you can reason your way through by doing.  Go read a little and you'll get it pretty quick.


Is this circuit properly made? I can't get to work a circuit that doesn't look that hard to copy.
This circuit was done for an Arduino extension of my DSC HS2032 system. I was trying the example "Status" on the Arduino's library DSC Keybus Interface v1.2.0.
On the example, we can see this circuit:
 *      DSC Aux(+) --- Arduino Vin pin
 *
 *      DSC Aux(-) --- Arduino Ground
 *
 *                                         +--- dscClockPin (Arduino Uno: 2,3)
 *      DSC Yellow --- 15k ohm resistor ---|
 *                                         +--- 10k ohm resistor --- Ground
 *
 *                                         +--- dscReadPin (Arduino Uno: 2-12)
 *      DSC Green ---- 15k ohm resistor ---|
 *                                         +--- 10k ohm resistor --- Ground

Here on the photos, I'm showing what I have done.

This is the HS2032 panel where (on the YEL and GRN) I connect the Arduino. I changed the Arduino's power source to be from my laptop so I could easily test it on the Serial Monitor. YEL->White/Green wire and GRN->Green wire
Now goes the Arduino's wiring.

Remember from the panel, the yellow is the white/green and the green is the green (they are coming from the right). First, each of both wires goes directly to 15kOhm resistor. Secondly, it splits between a 10kOhm resistor which then ends up into Arduino's ground, or it goes directly to the Arduino's pin 3 or 5, depending on the cable.
Results
The Serial Monitor shows "DSC Keybus Interface is online" and over.
If I connect green and white directly to 3 and 5, it will say sometimes "Keybus disconnected" and "Keybus connected" without any additional messages ever.
So my question is, am I missing something here? Why is the Serial Monitor not responding or what can I do to check where is the problem?
EDIT
This are the serial monitor readings, nothing from the Panel. I had to connect without resistances to get this output, otherwise, the only output would be "DSC Keybus Interface is online."
08:26:32.359 ->
08:26:32.359 -> DSC Keybus Interface is online.
08:26:35.345 -> Keybus disconnected
08:26:42.722 -> Keybus connected
08:26:47.838 -> Keybus disconnected
08:26:51.131 -> Keybus connected
08:26:54.937 -> Keybus disconnected
08:27:12.661 -> Keybus connected
08:27:17.122 -> Keybus disconnected
08:27:34.218 -> Keybus connected
08:27:41.697 -> Keybus disconnected
08:28:19.509 -> Keybus connected
08:28:22.487 -> Keybus disconnected
08:28:25.068 -> Keybus connected
08:28:28.053 -> Keybus disconnected
08:29:23.692 -> Keybus disconnected
08:29:31.175 -> Keybus disconnected
08:29:33.990 -> Keybus connected
08:29:37.005 -> Keybus disconnected

Is this circuit properly made?

No.
A lot of the problem is that you don't have a well-drawn schematic. I think that what you have is a couple of voltage dividers to interface a 5V arduino with a higher voltage device. I suspect a voltage divider isn't the best solution but presumably it works for someone else. So what you need is ...

simulate this circuit – Schematic created using CircuitLab
If I were you I'd pull your existing wiring apart completely and start again, arranging the components and wires so that they match this schematic as closely as possible in terms of position and orientation. Then trace the connections through carefully to make sure everything matches.


Variable scope error guys.

I'm writing here because I cannot find an obvious error, so I'm stuck. Could you please help me?

Here's the code:

int arrayAAA[] = {6, 8, 10, 12};
int arrayBBB[] = {9, 15, 27, 41};

const int arrayAAALength = sizeof(arrayAAA)/sizeof(int);
const int arrayBBBLength = sizeof(arrayBBB)/sizeof(int);

int newArrayLength = 0;

void setup() {

    Serial.begin(9600);

}

void loop() {

  String dir = "AAA";

  if (dir == "AAA"){

      //Copy existing array to the new one...
      newArrayLength = arrayAAALength;              //Get the size of source array
      int newArray[newArrayLength];                 //Make the new array of the same size
      memcpy(newArray, arrayAAA, sizeof(arrayAAA)); //Copy content of the source array to the new one

      /*
      for (int i = 0; i < newArrayLength; i++){
          Serial.print(newArray[i]); //Here everything works just fine...
          Serial.print("   ");
      }
       */
  }

  for (int i = 0; i < newArrayLength; i++){
      Serial.print(newArray[i]); //But here I see this error: 'newArray' was not declared in this scope
      Serial.print("   ");
  }

  Serial.println();
  Serial.println();

}

What I'm trying to do is to copy the array to a new one, but depending on the circumstances I need to take different source arrays (AAA or BBB).

The problem is in checking the values of an newly crreated array:

'newArray' was not declared in this scope

if I try to check its valus outside of if statment.

It seems my stupid mistake, but I can't find it.

After a careful study of C/C++ documentation, I finally managed to use pointers in Arduino :)

So, the final code became like this:

int arrayAAA[] = {6, 8, 10, 12};
int arrayBBB[] = {9, 15, 27, 41};

//Create a pointer, which will point to any of your arrays of your choice
int *newArray;

const int arrayAAALength = sizeof(arrayAAA)/sizeof(int);
const int arrayBBBLength = sizeof(arrayBBB)/sizeof(int);

void setup() {

    Serial.begin(9600);

    //Uses the address of arrayAAA (i.e. inherits the content of arrayAAA).
    //&: points to address of a chosen array.
    //[0]: is a must to grab all values!
    newArray = &arrayAAA[0];

    Serial.print("arrayAAA:");
    for (int i = 0; i < arrayAAALength; i++){
        Serial.print("   ");
        Serial.print(arrayAAA[i]);
    }
    Serial.println();

    Serial.print("newArray:");
    for (int i = 0; i < arrayAAALength; i++){
        Serial.print("   ");
        Serial.print(newArray[i]);
    }
    Serial.println();
}

void loop(){
    //Left empty
}

And it works perfectly, just what I expected!


Frequency measuring using Arduino (AC analog input) What I aim to do:
To measure the frequency of an AC analog signal generated by an electrodynamic shaker, which has a peak voltage of 10V-- using an Arduino Uno.

What I have tried:
Tried using a circuit similar to an optocoupler (using a 2N2222) transistor to take pulse input, using the pulsein() function. However the duration is always returning as 0.

My questions:

Is this method an acceptable way of measuring frequency?
What could I be doing wrong such that the time duration is always returning 0?
Is there an easier way of carrying out this work?

Will put up the code if asked for. However it is basically just defining a few variables (for pins, duration etc), and then using the pulsein function.

This project includes a frequency counter.

https://www.instructables.com/id/Oscilloscope-in-a-Matchbox-Arduino/

From the project page:
This oscilloscope costs the price of an Arduino Nano (£2 and a display (£3) plus a few pence for resistors, etc. It's specification is:

max 1M samples/second, min 1000sps
8-bits per sample
DC 0-5V; AC +/- 550mV, AC +/- 117mV, AC +/- 25mV
USB "PC scope" or built-in display
could be battery-powered
optional logic display
optional frequency meter
optional voltmeter
optional signal generator

My comment: I build it, it's a nice little project and the author is an expert programmer.


ESP8266 connecting keypad and lcd display I have ESP8266 type -

I have added a keypad

With a standard lcd display.

I have connected the keypad from d0 to d7, however after watching some tutorials i have to connect the lcd display(SDA,SCL) to D0 and D1, where i should connect the display to when they are taken by the keypad?

You can read the keypad using a single analog input (A0 in ESP8266) using this circuit:

When you press a key, some resistors are connected between Vcc and Ground. For each key, the total resistence is different, and the voltage at the input pin is different.

To read the keypad, you read the voltage at the input pin A0. You also have a table that associate the readings with keys. You search in the table for the nearest entry to the value you get. That's your key.

Wire the circuit and make a little sketch to read the values for each key you press. That's how you construct your table.

The value at A0 will be a little different each time you read the pin. That's is normal. Don't expect a exact macht.


Arduino can't create file in sd card I need to write and read some data from SD card. I link SD card(LC STUDIO) to Arduino (UNO). I use this link for create my project. In first day I don't have any problem and data correctly save to file. But now my circuit isn't work nicely. When Arduino is running the sketch I don't saw any error message.But when I link the SD card to my laptop, I don't saw any file on card!!
The code is here:

#include <SPI.h>
#include <SD.h>

const int chipSelect = 10;

File file;

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

  Serial.print("Initializing SD card...");
  pinMode(10, OUTPUT);

  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
  }
  Serial.println("card initialized.");
  //creating file
  file = SD.open("test.txt",FILE_WRITE);
  file.close();
  //write data to file
  file = SD.open("test.txt",FILE_WRITE);
  if(file){
    file.println("OK!!");
    file.println("1");
    file.println("2");
    file.println("3");
    file.println("OK!!");
    file.close();
  }
}
void loop()
{
}

Thank you all...
I found solution for my problem.
The circuit and the sketch isn't any problem. But I saw this and I think problem is because of LC Studio's SD card. In previous circuit I connect 5v pin of SD card to 5v pin on arduino. But now I disconnect that and connect 3v3 pin on card to 3v3 on arduino.
Now it's work very nice. And I don't know "why?" . Any idea?


Which input pins can I use on the ESP8266 NodeMCU On the ESP8266 NodeMCU I have GPIO2 , GPIO3 , GPIO1 , GPIO9 free but when I assign them to a button they do not work. I assume it is because those pins have other function behind them. When I look at the schematic I found that they are TXD1, RXD0, TXD0, and SSD2. Is there a way to still use these pins as inputs?

If not, can I use an Arduino Uno for my inputs and send signals from there to the analog pin to my ESP8266 NodeMCU for the connection to the MQTT server?

For the record all my other pins are used so I can't use any other input pin than these 4.

GPIO2 is NodeMCU D4 which is U1TXD, transmit for the second UART, generally available. GPIO3 is NodeMCU U0RXD, receive for the first UART, generally available if you aren't using serial. GPIO1 is NodeMCU U0TXD, transmit for the first UART, generally available if you aren't using serial. GPIO9 is NodeMCU SPIHD and is NOT available, as it is required for the flash memory. All that is well documented in many places. You can easily use serial to move data between modules, or multiplex your input to the one module. Cannot provide much insight without more details.


Can I use an Arduino Uno-style Shield with the Arduino Mega, Tre, or Zero? How about the Intel Edison? Can I use an Arduino Uno-style Shield with the Arduino Mega, Tre, or Zero? How about the Intel Edison?

Zero, Mega and Tre all have the same basic pinout layout as Uno, which provides at least physical compatibility for the pins. Sparkfun has a breakout board for the Intel Edison.

Mini, Micro & Nano obviously have a different pin layout. I would consider them mainly for projects that have challenging space requirements, since their main advantage is their small size. The Micro should be the easiest to plug'n'play (native USB COM serial). Nano is still stuck with FTDI drivers, so it's going to require separate drivers from the Uno/Mega family. And finally Mini doesn't have USB at all.

Maybe take a look at Wikipedia list of Arduino boards and compatible systems to evaluate better what suits your needs best.


Wiring LED strips in parallel & ground Schematic:

I am making some light fixtures controlled by an Arduino UNO. Each fixture will host two approx. 1 meter long analog RGB LED strips with a current draw at full power of ~1.2 A per meter. I have a 12 V power supply that I will wire directly to the strips, with the RGB channels wired to the Ardiino PWM pins via NPN MOSFET (note in the schematic I've only shown one color channel for simplicity, but there would of course be three transistors hooked up to three PWM pins). The Arduino itself will be powered by USB.

My main difficulty in wiring the system is that for so much current I need fairly thick wire. The pads on the LED strips are delicate and I have several times damaged them by mechanical stress from the wire while soldering. The thick wire also crowds the narrow space between the pads creating a risk of a short. Therefore my first question is (bear with me, I'm pretty new to this):

1) How should I wire the LED strips?

My thought is to wire up the strips in parallel with thinner, more flexible wires. This brings up two sub-questions:

1a) How should I join the thinner wires to the thick wire coming from the power supply?

1b) At the junction between the wires leaving the lights and running to the transistor, does the wire need to become thick again? (I think the answer is yes – the current should be the same as coming out of the power supply.)

I also am unsure about the ground.

2) Does the wire coming from transistor to ground need to be joined to the ground pin on the Arduino or can it run directly to the ground terminal of the power supply?

Sub-question:
2a) Does the wire coming from transistor to ground need to be thick?

I don't really understand how transistors work (basically my understanding is that the Arduino uses a small amount of current over the PWM pins to somehow control how much current is allowed to flow through the rest of the circuit.

I've drawn a schematic showing how I think maybe this system needs to be wired up. Do I need to make changes?

I think you are overestimating the size of wire required to attach to the LED strips, I have connected a lot of single color LED strip (in excess of 1mtr) with the wire that was already attach and it was reasonably light gauge.
Look at this Example on Ebay and you can see what i mean.

I am note an Electrical Engineer so i don't know the method to calculate the minimum wire gauge, but if in doubt contact the manufacturers and ask them or search on the web.

As for the Transistor mounting/wiring you would mount that on a small circuit board with terminal block fitted for ease. Any power/connecting wire should not be less that used to the LED strip.

Also you will need a current limiting resistor attached to the Base pin on your transistors. You will have to work out the value of that based on the spec sheet.

There is a bit of learning required first, once you have researched the above you will have you exact answers.


Serial plotter isn't displaying my supplied data I want to use serial plotter feature of Arduino by using DHT11 as humidity sensor at a time. But I'm getting problem as plotter is not loading by the code I have. Please help me what is the problem because of which serial plotter is not loading.

Here is the Code I wrote:-

#include <dht.h>
#define dht_apin0 A0 // Analog Pin sensor is connected to

dht DHT0;

void setup() {

  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity Sensor\n");
  delay(1000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    DHT0.read11(dht_apin0);

    Serial.print("Current humidity = ");
    Serial.print(DHT0.humidity);
    Serial.print("%  ");

    delay(5000);//Wait 5 seconds before accessing sensor again.

  //Fastest should be once every two seconds.

}// end loop()

You can't send arbitrary information (percent signs, text etc) to the plotter. The plotter only understands numeric values. You have to separate these number values from each other with commas, then do a println in your last value:

Serial.print(percent);
Serial.print(F(","));
Serial.print(tankPercent(depth));
Serial.print(F(","));
Serial.print(litres);
Serial.print(F(","));
Serial.println(tankLitres(depth));

In your case, it'd be simply:

Serial.println(DHT0.humidity);

You can go a bit further if you want to switch between either serial output, or serial plotter. In one case, I just set a constant variable for graph or plain data, then have a function for each (my above Serial statements are actually within a function called displayGraph()). The data function would be something like you had originally, example:

void displayData(float depth, float percent, float litres){

  // water level depth (inches)

  Serial.print(F("current missing inches: "));
  Serial.println(mixtureDistance());

  // cubic inches

  Serial.print(F("total cubic inches: "));
  Serial.println(TANK_TOTAL_CUBIC_INCHES);

  Serial.print(F("current cubic inches: "));
  Serial.println(tankCurrentCubicInches(depth));

  // litres

  Serial.print(F("total litres: "));
  Serial.println(TANK_TOTAL_LITRES);

  // ... etc
}

I also have projects where I use a switch that if on, sets a flag to output in serial graph format, and if off, uses the serial data routine.

Then, in your sketch loop(), you'd do something like:

graph
  ? displayGraph(depth, percent, litres)
  : displayData(depth, percent, litres);

...or a bit more verbose rather than using the tertiary operator:

if (graph){
  displayGraph(...);
}
else {
  displayData(...);
}

Here's a Q&D serial plotter example of my displayGraph() function above. In the top-right corner of the image, the four colours represent the four pieces of data I'm sending in, in order:

In my case, those represent the exponential moving average of the percentage of how full a liquid tank is, the second is the raw data I'm building that average on, third is the exponential moving average of how many litres are remaining in the tank, and lastly, again, the raw data for that average.

The sharp movements are simply me slapping the tank to get some variable and unstable readings for example purposes.


Serial not declared in this scope, newbie mistake most likely Ok, newguy with a little VBA coding experience going to pull hair out soon. It is probably a simple thing I have missed but I would like someone to point out where I went wrong. I modified a sketch that used an lcd to use the serial monitor instead but I sometimes run into this "not declared in this scope" issue. Doing something wrong, please point me in the correct direction.

#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;
DateTime now;
char daysOfTheWeek[7][12] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

void showDate(void);
void showTime(void);
void showDay(void);

void showDate()
{
  serial.print(now.day());
  serial.print('/');
  serial.print(now.month());
  serial.print('/');
  serial.print(now.year());
}

void showDay()
{
  serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
}

void showTime()
{
  serial.print("Time:");
  serial.print(now.hour());
  serial.print(':');
  serial.print(now.minute());
  serial.print(':');
  serial.print(now.second());
  serial.print("    ");
}

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

  serial.println("working....")
  //wire.begin();
  //delay(2000);
  if (! rtc.begin())
  {
    Serial.println("Couldn't find RTC Module");
    while (1);
  }

  if (rtc.lostPower())
  {
    Serial.println("RTC lost power, lets set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}

void loop ()
{
  now = rtc.now();
  showDate();
  showDay();
  showTime();
}

Case matters in C/C++. You should write Serial rather than serial.


Connecting BMP280 sensor to microcontroller I am building my own board with integrated pressure sensor.
(microcontroller is 3V3 logic)
I want to know which parts do i need. In datasheet there are only 2 capacitors but on breakout board there are also 4 resistors.
Also in datasheet are 2 100 nF capacitors and on breakout board are 1uF and 0,1uF.
schematics from datasheet:

breakout board schematics:

The capacitors are just decoupling capacitors. The value is not that critical. 100nF are good values to use.  On the breakout they have used just one pair of decoupling capacitors but use that pair for both power pins. The datasheet has one decoupling capacitor for each pin. You can do it either way. Personally I'd do it the datasheet way, but for a small board it really doesn't make much difference.
The resistors are a different matter. The BMP280 can work in a number of communication modes, and which mode you have it in dictates what resistors are needed.
R1 is used to place it into I2C mode. R4 is used to set the I2C address. R2 and R3 are the pullup resistors on the I2C bus. They aren't really part of the BMP280 circuit, but part of any I2C circuit in general.
R1 and R4 could be replaced by direct connections to VCC and GND respectively, but by having resistors gives you the ability to override them and use SPI instead of I2C should you wish it.


Find external router IP from Arduino Yun inside router network I want two Arduino Yuns in different private networks to communicate, i.e., behind two distinct routers of which at least one does not have dynamic DNS, so its external IP may change from time to time.

To be reachable, this Yun could forward its router's external IP to the other Yun which has a fixed DNS name. But for this to work, it must be able to determine its router's external IP.

How can the Yun find out that the external IP of the router has changed? The Yun will be runnning all the time.
If the external router IP has changed (i.e., my Fritz.Box disconnects in the night and may receive a different IP when it reconnects), how can the Yun determine the new external IP?

If this is not the right place to ask, I'm happy for pointers to somewhere else (Server Fault SE forum?).

You can write a program that updates its own external IP every couple of minutes/hours, or when it doesn't get a response from another Yún/PC/server.

You can use this link (or find another site of the web that gives you your external IP address): http://www.realip.info/api/p/realip.php

This link has a beautifully formatted information that you can easily extract. I have a similar solution on one of my servers that have a dynamic IP...


multiple connection with ISP Pin at Arduino Micro Actually I'm not good at English ;-) trying to ask to you. please understand me :)

I needed connect SD card Shield and TFT LCD Screen to Arduino Micro.

successfully finished compile at source code but when i connect MISO together

it doesn't work. only SS pin is connected separate Pin's to Micro

How can i make it work together to Micro..

i've checked each device perfectly work at Micro

Plese Help me!!

Regards and Thanks

Each SPI device must have a separate device/slave select pin. The device must disconnect (high impedance state) when not selected. The SD shield will have a level shifter. It may not correctly disconnect from MISO.

Depending on what libraries you are using you might also need to check that they set the SPI hardware attributes correctly (clock, mode, etc).

For more help please post code and references to the shields and libraries.

Cheers!


Arduino UNO Low-Power Consumption (Multiple Ultra-Sonic Sensors) I've read post that it's possible to connect multiple Ultra-Sonic Sensors to one Arduino.
But I have a few questions:

If I use Arduino Uno, what is the maximum number of Ultra Sonic Sensors that I can connect one Arduino UNO?

Is there any option to power Arduino UNO in some kind of low-power mode so I can achieve power autonomy for at least 90 days.(I'm referring to battey life, or solar powered solutions)

Can Arduino UNO work on the low/high temperatures (e.g. -20 / +50 Celsius degrees), and what is the known work temperature range?

How to secure jumpers/cables to work on extreme temperatures (e.g. -20 / +50 Celsius degrees)
Thanks in advance :D

You did not specified, what kind of ultrasonic sensor you want to use so I assume use of "standard" ultrasonic Arduino modules (like hc-sr04), which need 4 pin (VCC, GND, TRIGGER and ECHO). Since Arduino Uno has got 20 IO pins (6 analog and 14 digital), you can use 10 pins as outputs for TRIG signals and 10 as inputs for ECHO signals and thus connect up to 10 ultrasonic modules to one Arduino Uno.
In general, Arduino Uno is not designed for low-power applications. If you want more specific answer, you should ask more specific question...
Working temperature of Arduino Uno is -40 to 85 °C.
One of the options is using a terminal shield with screw terminals, e.g something like this.


Arduino uno board not detected when connected via USB no matter what OS I was working with Arduino in Win 8.1, when suddenly it stopped work. I tried to reinstall the drivers and IDE several times, but it didn't solved.

In Win 8.1, when I plug the arduino, I get the pop up message:

USB Device Not Recognized in Windows

Also, when I try to upload a sketch, I get this error in Arduino IDE:

avrdude: ser_open(): can't open device "\\.\com5": the system cannot find the file specified

I switched to Linux (Debian Jessie 64 bits), but it also doesn't get recognized, and I getting the same error, only the port Is different.

I am guessing is a problem with avr, but I don't know what can I do about it.

Other  symptoms:

In both systems the port tool in IDE is grey, so I can't choose a port.
When I press the reset button in Arduino, nothing happens.
The led L (13) is constantly shinning. It never blinks or stops.

Solutions I tried:

Reinstall drivers
Modify the preferences.txt file to change the COM port
Fall back to a previous IDE version
Change the usb cable

If the port selector in the IDE is greyed out, and the OS is throwing an error, it's likely the Board is damaged. Either The firmware on the serial device or the chip is fried somehow. What's happening is that the usb part is failing, so the Com port part never works.


Why do ESP boards break out the SPI flash pins? I have an ESP32 development board and a NodeMCU board here. Both breaking out the pins for the SPI flash of the ESP. These pins are mentioned in standard pinout descriptions as must/should not connect. This pinout description states, that they

  are not recommended for other uses. So, don’t use these pins in your projects

The answer to this question suggests, that you can somehow connect other SPI devices to the same bus as the SPI flash. The linked documentation from that answer states, that in that case you cannot control the chip select for the additional SPI device via a digital pin, but have to let the "hardware arbiter" (whatever that is) decide, when to connect to the additional SPI device.

That is the only use of these pins, that I could find, and even this seems pretty niche. It doesn't seem to be a standard way of usage for the pins and also rather difficult.

Considering the very limited and difficult use of the SPI Flash pins, why do ESP boards break these out to the user? Why aren't they just kept internal, making the board a little smaller?

Maybe there is another use of the pins or I just underestimate the importance of adding additional SPI devices to the bus.

Considering the very limited and difficult use of the SPI Flash pins, why do ESP boards break these out to the user? Why aren't they just kept internal, making the board a little smaller?

The ESP32 is not designed specifically for Arduino. There are other boot modes, such as SD card boot, whereby the internal flash is not directly used. In this situation you are free to use those pins as you wish (given that there is a flash chip attached to them).

The "ESP32 Development Board" was not primarily designed for Arduino. Instead it's a generic board designed by Espressif (and copied many times), and is usable with the Arduino core as one of many options.

In short: the pins aren't there for Arduino users, they're there for other users.

Addendum:

The SPI flash pins can also be used for (and are most commonly used for):

Adding more SPI flash chips which then get integrated into the normal memory space and with the internal caching system, and
Adding PSRAM to increase the RAM memory space.

A good example of the latter is the ESP32-CAM which has an SPI-connected PSRAM chip for framebuffering and image analysis connected to the SPI pins.

You can think of them not so much as SPI pins but as the EBI pins of the PIC32MZ or the EMB of the ATMega2560, etc. Used for expanding the memory rather than for adding random peripherals.


Loading Leonardo bootloader to Atmega32U4 running at 8 MHz I am currently using ATMega32U4 running at 16MHz using Leonardo. I can only supply 3.7V (I use LiPo batteries) and everything seems fine but this is not as per specs.

To run at 16 MHz, I have to supply 5V but I can't. I do not want to do any step-up. I am thinking of of using 8 MHz crystal so the processor will require only 3.3V, but I need to use a Leonardo.

Has anyone been successful in doing this?

The bootloader does USB. I don't think you can do USB on the 32u4 on only 8mHz.

You can however set the system clock prescaler to divide the main clock by 2, making it run at 8mHz. The bootloader will however still run at 16mHz, but that's probably still fine (though out of spec).

  The AVR USB has a system clock prescaler, and the system clock can be divided by setting the “CLKPR – Clock Prescaler Register” on page 38. This feature can be used to decrease the sys- tem clock frequency and the power consumption when the requirement for processing power is low. This can be used with all clock source options, and it will affect the clock frequency of the CPU and all synchronous peripherals. clkI/O, clkADC, clkCPU, and clkFLASH are divided by a factor as shown in Table 6-10.

To divide the system clock by 2, set the CLKPS0 bit in the CLKPR register. The code for this would be something like this:

void setup()
{
  cli();
  CLKPR = _BV(CLKPCE);
  CLKPR = _BV(CLKPS0);
  sei();

  ...

just note that everything runs twice as slow. So delay(1000) will take 2 seconds. You'll have to update F_CPU somehow to fix this if this causes a problem.


Arduino Mega 2560 + BL-TB6560+ Stepper I am working on an Arduino Mega 2560 and BL-TB6560-V2.0 driver for running a stepper motor. Initially I was able to run the stepper in both direction with code given and a schematic as per this image.

.

int dirpin = 7;
int dirH = 12;
int steppin = 9;

void setup() {
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  pinMode(dirH, OUTPUT);
}

void loop() {
  digitalWrite(dirpin, LOW); // Set the direction.
  digitalWrite(dirH, LOW);
  delay(1000);
  for (int i = 0; i<32767; i++) {
    // Iterate for 4000 microsteps.(32767)
    digitalWrite(steppin, LOW); // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(50);
  }
  delay(1000);
  digitalWrite(dirpin, LOW); // Set the direction.
  digitalWrite(dirH, HIGH);
  for (int j = 0; j<32767; j++) {
    // Iterate for 4000 microsteps.
    digitalWrite(steppin, LOW); // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(50);
  }
}

But now when I am trying it, the same stepper is not rotating. What could be the reason? I have checked the driver voltage, it's ok, and the code and schematic is the same.

I just removed the ENE(+) pin of the driver, which was connected to the +5V. Now it's working and the stepper is rotating.

I just got a hint from this video.


Why is the regulator very hot? We have an LED strip connected to output 6 and is powered by the Uno board itself.  Shouldn't be drawing too much current, only have 10 elements on the LED strip.  While this LED strip is connected to the Uno, I noticed that the regulator is getting very hot.

One thing we haven't done yet is to power the LED strips from an external source, which will be necessary since there will be many strips.  At the moment, the students are simply trying to debug their program with the small strip.

If you power the Arduino with an external power supply the on board regulator has to dissipate the voltage difference between input and 5VDC at the total current you draw from the board.

As Klaus Warzecha wrote in an answer to another question

  The Arduino is just the brain, not the power station.

If the output voltage of your power supply is 12V, then the regulator will be dissipating 12-5V = 7 V at the total current drawn. Total dissipated power for eg. 150mA (just an estimate) would be P = V × I = 7 × 0.150 = 1W
The regulator will be pretty hot from dissipating 1W.

Mind you that the current is not limited to 150mA, enough LEDs can easily increase current and power. If the regulator is stressed (often) enough, sooner or later it will fail. It is better practice to power any load directly from the external power supply, taking the higher voltage into account.


Can I use GSM and Data Logger Shield at the same time on one Arduino? Me and my classmates are trying to make an arduino base project where we will be using sensors, GSM, and Data logger shield. We want the arduino to store the data collected and at the same time send a message to the user if significant data are collected.My is question is above.

It depends, but high likely yes.

The sensors, GSM and Data Logger may use the I2C, SPI, analog pins or UART (last not likely).

For I2C, the Arduino can handle many of such devices, because it is part of the protocol.

For SPI it is similar, although some cheap SD card reader for Arduino are notorious not being compatible with other SPI devices. And the Arduino has only one SPI port (but can handle many SPI devices, as long as they all are capable to allow other SPI devices).

For analog pins, these are likely only used by sensors, the Arduino has 5. But there are some ways to use more sensors by polling, using multiplexers etc.


I2C 2 way communication between Arduino Uno and Arduino Mega If I remove the transmission code from slave this works properly but I need to transmit from slave.

Here is my master code

#include <Wire.h>
void setup() {
  Wire.begin(3);
  Wire.onReceive(receiveEvent);
}
byte x = 0;

void loop() {
  Wire.beginTransmission(9);
  Wire.write("s");
  Wire.write(x);
  Wire.endTransmission();
  x++;
  delay(500);
}

void receiveEvent(int howMany) {
  if(Wire.available()){
    int x = Wire.read();
    Serial.println(x);
  }
}

Here is my slave code:

#include <Wire.h>
void setup() {
  Wire.begin(9);                // join i2c bus with address #9
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

void receiveEvent(int howMany) {
  if(Wire.available()){
    char c = Wire.read();
    Serial.print(c);
    if(c == 's'){
      int x = Wire.read();
      Serial.println(x);
      //transmit to master
      Wire.beginTransmission(3);
      Wire.write(1);
      Wire.endTransmission();
    } else {
      Wire.read();
    }
  }
}

Is it possible not to use Wire.onRequest(requestCallback); to send data to master? Kindly help.

To join the bus as a master you cannot supply a 7-Bit slave address so your code has two slaves.

Below you will find 2 sketches that successfully sends data to a slave. I would suggest you start looking at the I2C protocol and understand there are 4 Modes:

Master->Transmitter
Master->Receiver
Slave->Transmitter
Slave->Receiver

All communications regardless of how the data is transferred requires a master. It's the master that controls the clock pulses, thats why its always the master that initiates the communcation.

The MasterReader/MasterWriter tutorials on the arduino forum should now possibly start to make a little more sense when understanding those modes.

This code shows how a master sends data to a slave, and then how it requests data from the slave. If we look at this code from the master point-of-view, you can see it essentially says, send this byte to the client (m->t & s->r), then request data from the slave (m->r,s->t)

Master Code

#include <Wire.h>

#define SLAVE_ADDRESS 0x60

void setup()
{
  Wire.begin();
  randomSeed(analogRead(3));
  Serial.begin(9600);
}

byte x = 0;

void loop()
{
  x = random(0,255);
  Serial.print("Sent: ");
  Serial.print(x, HEX);
  Serial.print("\n");
  Wire.beginTransmission(0x60);
  Wire.write(x);
  Wire.endTransmission();
  delay(500);
  Serial.println("Requesting Data");
  Wire.requestFrom(SLAVE_ADDRESS, 1);

  int bytes = Wire.available();
  Serial.print("Slave sent ");
  Serial.print(bytes);
  Serial.print(" of information\n");
  for(int i = 0; i< bytes; i++)
  {
    x = Wire.read();
    Serial.print("Slave Sent: ");
    Serial.print(x, HEX);
    Serial.print("\n");
  }
  delay(500);
}

Slave Code

#include <Wire.h>

#define SLAVE_ADDRESS 0x60
byte x = 0x00;
void setup()
{
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
  Serial.begin(9600);
}

void loop()
{
  delay(100);
}

void requestEvent()
{
  Serial.print("Request from Master. Sending: ");
  Serial.print(x, HEX);
  Serial.print("\n");

  Wire.write(x);
}

void receiveEvent(int bytes)
{
  if(Wire.available() != 0)
  {
    for(int i = 0; i< bytes; i++)
    {
      x = Wire.read();
      Serial.print("Received: ");
      Serial.print(x, HEX);
      Serial.print("\n");
    }
  }
}