Why my arduino board does not blink properly? I have two files
blink1.cpp
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

blink2.cpp
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;
port_type portC = (port_type) 0x28;
port_type ddrC = (port_type) 0x27;
port_type portD = (port_type) 0x2B;
port_type ddrD = (port_type) 0x2A;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

The difference between these two files are the definition of only a few unused ports in blink2.
I compile and upload them to the board by
avr-g++ blink1.cpp -o blink1
avr-objcopy -O ihex -R .eeprom blink1 blink1.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink1.hex

avr-g++ blink2.cpp -o blink2
avr-objcopy -O ihex -R .eeprom blink2 blink2.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink2.hex

The first one does not blink properly but the second one does. What is the problem of the first code?

There are a couple of issues here.
One of them has already been raised in a comment:

 int main()
 {
-    ddrB = (port_type) 0x20;
+    *ddrB = (int8_t) 0x20;

     while(true)
     {

The more serious issue is in the command line you used to compile the
program. When compiling for an Uno, you should add the option
-mmcu=atmega328p. This way the compiler knows which version of the C
runtime it should add to your program. Otherwise the compiler will
include no runtime at all.
The C runtime does some important initializations. For example, it
clears the register r1, which is required by the ABI, and assumed
to be the case by the compiler. For example, when you write *portB = (int8_t) 0x00;, the compiler copies r1 to the port, without first
clearing it. Another important role of the C runtime is to call
main(). Without it, the program will start by executing whichever
function happens to be at the start of the flash. Unless you program in
assembly, you have no control over that. If the first function happens
to be main(), the program may work as expected. If it is another
function, that function may then return to the bootloader. Any seemingly
innocuous change in the program can then change the behavior.
Then a few minor issues, that should not prevent the program from
working:

int8_t is meant to be a signed type. If you want the unsigned
version, use uint8_t instead. Sure, these are your own type
definitions, but creating a type that conflicts with a standard type
can only create confusion. Best option is to drop the definition and
include <stdint.h> instead.

Whereas port_type should certainly be a “pointer to volatile” data,
there is no point in making the pointer itself volatile. That can only
hinder valid optimizations.

portB and ddrB should be const, and that may allow the compiler
to better optimize them. But why not use PORTB and DDRB from
<avr/io.h>?


Save a fingerprint to the database of the fingerprint sensor I'm using the Adafruit Kookye fingerprint module in my project. Since it can only allocate 256 fingerprints I need to make a program to free the memory and add additional users. I have made the following function at the library:

uint8_t Adafruit_Fingerprint::downloadModel(uint16_t id, uint8_t packet_1[], uint8_t packet_2[], uint8_t slot) {
  uint8_t packet[] = {FINGERPRINT_DOWNLOAD, slot};
  writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet);
  uint8_t len = getReply(recvPacket);

  if ((len != 1) && (recvPacket[0] != FINGERPRINT_ACKPACKET))
   return -1;
  if (recvPacket[1] == 0x00) {
    writePacket(theAddress, FINGERPRINT_DATAPACKET, sizeof(packet_1)+2, packet_1);
    writePacket(theAddress, FINGERPRINT_DATAPACKET, sizeof(packet_2)+2, packet_2);
    return recvPacket[1];
  } else {
    return recvPacket[1];
  }
}

This function is working, it puts the fingerprints to the buffer 1 and when I call the function to save with the ID it also works. When I print the fingerprints in the sensor, the structure is exactly the same as if they had been added directly from enrolling. However, when I serach the fingerprints the sensor always returns that the user does not exist.

I don't know what's the problem.

The sizeof() operator doesn't do what you think it does. It's not a function that is executed at runtime, it's an operator that is interpreted at compile time.

It takes a variable and returns the size (in bytes) of that variable. Since you are passing it a pointer it gives you the size of that pointer. That's 2 bytes on an 8-bit system like the Uno.

In C an array is not a single entity with a size. It's a pointer to a block of memory that has been reserved at the time the array is declared. All you get is that pointer, and it's up to your program to remember the size.

You will have to pass the size of the arrays your packet_1 and packet_2 pointers are pointing to, or always assume that those arrays are the same size at all times.


Need help with an Arduino project using a RTC and LEDs I need some help with a project I am doing involving the DS1307 RTC. I am trying to make what is essentially a way to mins quickly check the time which involves nine LEDs slowly lighting up every 10 so that I can quickly check time but looking at it. : So far I've tried TimeAlarms but I can't figure out how to do this. I have a Arduino Uno by the way.

Can someone possibly help?

Use the SQW pin on the DS3231 or DS1307 to create 1sec pulse, read it on your Arduino. There are very good libraries are available (like RTClib from adafruit).


How to Factory reset ESP8266? I want to use ESP8266 to send emails. I tried twice flashing the Firmware to a particular firmware as suggested in a tutorial. Now both my ESP are unresponsive to AT commands. Let me know the way to RESET it. CH_PD + VCC + RST (Tried this combination), No success there any thing i am missing?

AT commands are executed by the AT interpreter firmware. If you've been attempting to flash other firmware to the ESP8266 module, there is no longer any code in it that interprets AT commands. If you want to it to respond to AT commands again, you'll need to re-flash it with that firmware.


MCU to switch single coil latching relay not working (attempting array with common gnd) I have several single coil latching relays, (EC2-5SNU).

I am trying to control them by an MCU; connected directly they work fine, but I am iffy about keeping it this way so I'm trying to power them through a darlington pair array, (ULN2003).

Using the non-latching type, these work fine through the ULN2003, but attempting to interface the code below with the latching type isn't going so well and i can't figure out why:

int right = 12;
int left = 10;

void setup() {
  pinMode(right, OUTPUT);
  pinMode(left, OUTPUT);
}

void loop() {
  digitalWrite(right, HIGH);  //reset
  digitalWrite(left, LOW);
  delay(2000);
  digitalWrite(right, LOW); //set
  digitalWrite(left, HIGH);
  delay(2000);
}

I have four connected with a common pin, but to simplify i've tried and failed to have the code above work on a single relay, as shown below:

Measuring the voltages out of the MCU show the correct levels, keeping in mind the ULN2003 acts an inverter, so i've set the boolean logic accordingly.

The voltages at the output of the ULN seem to stick at 0.6V, I've tried a bunch of permutations, including having one pin (on the common pin setup) connected directly to the MCU.

Does anyone have any ideas?

You need to use an h-bridge as if you were driving a motor. For this kind of relay you need to be able to both sink and source current, which a Darlington pair cannot do, it can only sink.

I guess you may be being thrown by the symbol of an inverting buffer used in the schematic symbol for the ULN2803 in your schematic capture package. It's incorrect, since it's not an inverting buffer, it's a Darlington pair:

simulate this circuit – Schematic created using CircuitLab

As you can see, setting the input HIGH will allow the transistor pair to conduct, but setting it to LOW will stop it conducting - so the output is either connected to ground, or is floating.


Cannot communicate with Serial Monitor - Arduino Yun I connect Arduino Yun to my Computer with WiFi. I was able to get the IP address of my Arduino Yun. However, when I try to print something. It seems to not work at all. The following code is the one that I try:

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

void loop() {
 // print labels
 Serial.print("NO FORMAT");
 delay(100);
}

I did not get any kind of error. However, when I open the Serial Monitor, it shows nothing at all. I try to use the same code with Arduino Uno. It works fine.

When using the Yun over wifi, you cannot user Serial, you need to use Bridge Console object. Serial is bound to the usb cable.

Give a spin to ConsoleRead example.


Arduino Mega LED doesn't light as expected I wrote this for my Arduino Mega 2560:

int LED[14] = { 28,29,30,31,32,33,34,35,36,37,38,39,40,41 } ;
...
... (some other code like setup(), etc. Note:pinmode output for this 14 leds wich pins is defined in
... array named LED[]
...
void intro(){
  for(int j=1; j<100; j++ ){
    for(int r=1; r<15; r++ ){ digitalWrite(LED[r],HIGH); delay(100);  }
    delay(100);
    for(int r=1; r<15; r++ ){digitalWrite(LED[r],LOW); delay(100);}
    delay(100);
  }
  Serial.print("Pattern started");
  delay(1000);
}

So when I run this script, I expect that each LED will light up in the sequence and remain lit until the second loop to turn it off, but I see that when lighting each LED, when lighting the 9th LED, the first 8 LEDs shut off inexplicably and LEDs 9 through 14 light one by one, remaining lit. That I expected but why do the first 8 LEDs shut off before the loop ends and the second loop starts?

While it is true that your loop is incorrect, the coding error is unlikely to cause the behaviour that you have described.

Please ensure that a current limiting resistor is placed in series with each LED. Since you have 14 LEDs, you will need 14 current limiting resistors. 470 Ohm resistors (or similar) should be adequate for this purpose.

As per the other comments, C++ Arrays start at 0, not 1. The last element is the size of the array minus 1. In your case 14 - 1 = 13. Thus the loop can continue as long as the index is < 14 (or <= 13)

Thus your loops should read:

for(int r=0; r<14; r++ ) {
  digitalWrite(LED[r],HIGH);
  delay(100);
}


Detect a camera flash? Light sensor, photoresistor? I'm looking to build an Arduino-based "camera flash logger" to detect when a camera flash goes off, and maintain a log of those events. My thinking is to use a photoresistor to measure light level, and watch for sudden changes using a loop. Something like:

const int ldrPin = A0;

// no idea what this number would end up being
// just putting something here to start with
const int threshold = 10;
int currentLevel, lastLevel = 0;

void setup() {
    Serial.begin(9600);
    pinMode(ldrPin, INPUT);
}

void loop() {
    lastLevel = currentLevel;
    currentLevel = analogRead( ldrPin );

    // look for a sudden change
    if( abs( lastLevel - currentLevel ) > threshold ) {

        // serial out here to simplify the example.
        // I'll be logging outputs (with timestamps) to an SD card.
        Serial.println( currentLevel );
    }
}

A couple of things I'm not sure of though:

will the response time of a photoresistor be fast enough to respond to the very short (sometimes less than 1ms) burst from a camera flash?
is a loop measuring level changes the best way to go about this, or would something like a state change interrupt be better? The ambient light level will vary depending on time of day, so it's an edge detection problem, as opposed to just reading a light level.

Apologies if this comes across as a "you haven't done your homework yet" question. I haven't started the project yet, so all I'm hoping for is a little direction on which way to proceed.

A photo-resistor would not be recommended to detect a camera flash accurately.  For example, the Jameco Part #202403 (Part PDF) has a response time of 50 to 75 milliseconds.  Photo-resistors are more suitable for general light levels, for instance, like how bright it is in a room.  On the other hand, photo-transistors are suitable for very fast reaction times.  The Jameco Part #2129385 (Part PDF) has a response time of 15 microseconds, which is more than 1000 times faster.  A photo-resistor will be able to respond to the light change, but it will be nowhere as sensitive.As with any product, however, search for the product PDF before buying it.


Threshold to wake up signal I have a sketch to put to sleep and wake up an Arduino Pro Mini 5V, but the problem is that sometimes when it is moved fast it wakes up itself, thing that I do not want. I have it configure to be waken up in the pin 2 by a rising signal using an interruption:

#define wakePin 2        // pin used for waking up

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

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

  pinMode(RLEDPIN, OUTPUT);
  pinMode(GLEDPIN, OUTPUT);
  pinMode(BLEDPIN, OUTPUT);
  pinMode(wakePin, INPUT);

  attachInterrupt(0, wakeUpNow, RISING );
}

void sleepNow()         // here we put the arduino to sleep
{

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register  // so sleep is possible. just a safety pin

    attachInterrupt(0,wakeUpNow, RISING); // use interrupt 0 (pin 2) and run function  // wakeUpNow when pin 2 gets LOW

    sleep_mode();            // here the device is actually put to sleep!! // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep: // disable sleep...

    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the // wakeUpNow code will not be executed  // during normal running time.

}

void loop()
{
    digitalWrite(GLEDPIN, HIGH); //set green led high
    digitalWrite(BLEDPIN, HIGH); //set blue led high
    digitalWrite(RLEDPIN, HIGH); //set red led high

  times = millis();

  if((times-times_f)>=12000)
  {
    times_f=times;
    Serial.println(times-times_f);
    digitalWrite(GLEDPIN, LOW); //Reset the LED's
    digitalWrite(BLEDPIN, LOW);
    digitalWrite(RLEDPIN, LOW);
    sleepNow();
  }
}

I think the problem is that it has a bit of rising signal while moving, so a solution could be to have a threshold in the reception of the signal, can it be done?

You should add pull-down resistors generally of 10k on the interrupt pin, this will resist the unwanted signals on that pin.


Burn bootloader on custom ATmega 2560 board I have developed and produced a custom board with a ATmega 2560 on it and a FT232RL for USB communication. I want to burn an Arduino bootloader onto the board without using an external Arduino as ISP. I can't seem to figure out how.
When I just click "burn bootloader" from the arduino software it says:

avrdude: stk500_recv(): programmer not responding

What am I doing wrong and how can I correctly burn the bootloader?

To burn a bootloader you have to use some external device. That can either be another Arduino or a hardware programmer, like an USBASP or something similar.

You can't just magic the bootloader on there through the USB and a dose of wishful thinking. To use the USB you first have to have the bootloader on there.


Parse an element that consists of an array using ArduinoJson I want to parse an json element that consists of an "array".
In this case
solar->solardata->calculatedconditions->band[0-7]
How can i do this?

My attempt was:

String data = root["solar"]["solardata"]["calculatedconditions"]["band"][0]["#text"];

But it returns NIL

Plattform: ESP8266

Library: ArduinoJson

{
   "solar":{
      "solardata":{
         "source":{
            "@url":"http://www.hamqsl.com/solar.html",
            "#text":"N0NBH"
         },
         "updated":"11 Jun 2017 2032 GMT",
         "solarflux":"75",
         "aindex":"4",
         "kindex":"5",
         "kindexnt":"No Report",
         "xray":"A6.8",
         "sunspots":"0",
         "heliumline":"107.7",
         "protonflux":"1.40e-01",
         "electonflux":"9.37e+01",
         "aurora":"2",
         "normalization":"1.99",
         "latdegree":"66.5",
         "solarwind":"416.2",
         "magneticfield":"-2.4",
         "calculatedconditions":{
            "band":[
               {
                  "@name":"80m-40m",
                  "@time":"day",
                  "#text":"Poor"
               },
               {
                  "@name":"30m-20m",
                  "@time":"day",
                  "#text":"Poor"
               },
               {
                  "@name":"17m-15m",
                  "@time":"day",
                  "#text":"Poor"
               },
               {
                  "@name":"12m-10m",
                  "@time":"day",
                  "#text":"Poor"
               },
               {
                  "@name":"80m-40m",
                  "@time":"night",
                  "#text":"Poor"
               },
               {
                  "@name":"30m-20m",
                  "@time":"night",
                  "#text":"Poor"
               },
               {
                  "@name":"17m-15m",
                  "@time":"night",
                  "#text":"Poor"
               },
               {
                  "@name":"12m-10m",
                  "@time":"night",
                  "#text":"Poor"
               }
            ]
         },
         "calculatedvhfconditions":{
            "phenomenon":[
               {
                  "@name":"vhf-aurora",
                  "@location":"northern_hemi",
                  "#text":"Band Closed"
               },
               {
                  "@name":"E-Skip",
                  "@location":"europe",
                  "#text":"144MHz ES"
               },
               {
                  "@name":"E-Skip",
                  "@location":"north_america",
                  "#text":"Band Closed"
               },
               {
                  "@name":"E-Skip",
                  "@location":"europe_6m",
                  "#text":"50MHz ES"
               },
               {
                  "@name":"E-Skip",
                  "@location":"europe_4m",
                  "#text":"70MHz ES"
               }
            ]
         },
         "geomagfield":"MIN STRM",
         "signalnoise":"S4-S6",
         "fof2":"NoRpt",
         "muffactor":"NoRpt",
         "muf":"NoRpt"
      }
   }
}

My code was correct. The problem was that the json array contained an " " as first character. Thats why the parsing failed.


control 3 relays with 1 button Is there a way to control 3 relays with 1 button?

My idea is: There are 3 modes; mode 1 for relay 1, mode 2 for relay 2 and mode 3 for relay 3.

With a long press you switch between modes (After 3 comes 1) and with a short press you activate the relay which is in the activated mode.

I need this for my wheelchair so please help me.

Thank you, Michael

Further question:
Does the relays really need a external power supply?
Because I have a small amount of power to control with the relays.

Sure you can. This site isn't a great place for open-ended questions like this though. Since you have a serious real-world need I'll give you some guidance anyway.

You'd need to break it into pieces and solve each one in turn.

First create code that recognizes long and short presses (not using delay().) You'll probably want to respond on releasing the button, since at that point it's easy to tell if it was a long or a short press.

The pseudo-code might look something like this:

void loop()
   if button_is_pressed
      if !press_in_progress
         press_in_progress = true
         start = millis()
   else
      if press_in_progress //Button has been released
         elapsed = millis() - start
         press_in_progress = false
         if elapsed > long_press_threshold
            long_press_function()
         else
            short_press_function()

For controlling the relays, I suggest getting "digital" relays that are made to be controlled with 5V logic signals. Relays like this work well. (Link). Since you need to control 4 relays, a 4 channel model like this one would be a better choice. Note that you'll need a fairly high current power supply. A 2A 5V regulated supply should be plenty for both your Arduino and your relays, although it's more of a sure thing if you use separate power supplies for the arduino and the relays (that way the voltage to the arduino doesn't bounce around as the relays energize and de-energize.

You'll need a global variable for the currently active relay. The long press would increment that value modulo 4: (going from 0 to 3 and then back to 0)

relay_index = (relay_index + 1) % 4;

You'd need an array of 4 bools for the states of each relay:

bool relay_states[4];

The short press would toggle the state of the current relay

relay_states[relay_index] = !relay_states[relay_index];

Note that if you're more interested in solving your wheelchair problem cost-effectively than tinkering, this is the sort of thing that a maker space would be ideal for. There are lots of tinkerers there who love a challenge, and would likely pitch in and help you.


Generating and reading a PWM signal at the same time on Arduino Uno R3? The code below should generate a PWM signal on digital pin 3. But know I want to see if it is even working. I was thinking about a Event triggering method like ISR. But somehow it does not work. I guess a ISR needs to a Input Pin, e.g. it would work, when I would've a PWM signal coming from somewhere.

Is it even possible to generate a PWM signal and read it to see some results on the serial monitor?

edited code:

byte const PWM_PIN = 3;

volatile unsigned long pwm_value = 0;
volatile unsigned long prev_time = 0;

void setup() {
  pinMode(PWM_PIN, OUTPUT);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(PWM_PIN), rising, RISING);
}

void loop() {
  digitalWrite(PWM_PIN, HIGH);
  delay(400);
  digitalWrite(PWM_PIN, LOW);
  delay(1600);
}

void rising() {
  attachInterrupt(digitalPinToInterrupt(PWM_PIN), falling, FALLING);
  prev_time = millis();
}

void falling() {
  attachInterrupt(digitalPinToInterrupt(PWM_PIN), rising, RISING);
  pwm_value = millis()-prev_time;
  Serial.println(pwm_value);
}

You are declaring the variables prev_time and pwm_value as int, which has (on a standard Arduino) 16 bits. Since you use the signed variant, you get a range of values from -32768 to 32767. But micros() is returning an unsigned long, which has 4 bytes (32 bits) and is not signed. With int there are only 32.767 ms (since it represents microseconds here), without letting the variable overflow. Even the full range would give you only about 65 ms. It simply cannot hold a value like 1000000. If you assign this value to an int, it will directly overflow (which - I think - would give you the value modulo 2^16), effectively loosing big parts of the information. You cannot get meaningful results with this in such a high time scale.

When measuring time (with millis() or micros()) you should always be sure to use unsigned long as type to prevent these problems.

Apart from the variable type, why do you use micros() here? You are measuring times in the hundreds of milliseconds, so why not use millis()? This would keep the values lower.


Code to control servo with shield I recently bought an Arduino MEGA2560 and a SainSmart InstaBots Robot Controller Shield for Arduino MEGA2560 R3 Robot Arm Control.

I understand how to control a servo in the method described in Sweep. However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?

Please help me I am a beginner in robotics and I need this for a project.

However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?

With the limited amount of info you have provided about the shield this will have to be a wild guess. I am assuming that the pins are S(ignal), V(cc) and G(nd) for pins 8-13. On an Arduino Mega these can be used for PWM and therefore Servo control.

Include the Servo library, attach the pin and set the angle.

#include <Servo.h>

Servo servo[6];

void setup()
{
  ...
  for (int i = 0; i < 6; i++)
    servo[i].attach(8 + i);
  ...
}

void loop()
{
   ...
   servo[i].write(pos);
   ...
}

Cheers!

NB: Do not forget to provide the correct power supply. If USB Port is left, then the upper pin is positive and the lower pin negative.


Can a cheap RF module be used for two way communication Can a cheap RF(transmitter and receiver) module be used for two way communication, not at the same time of course but for example arduino A sends string to be printed on lcd the arduino B receives it and prints it on lcd, then after some time arduino B sends a temperature data back to arduino A, then arduino prints the temperature data on the serial monitor. All of this while arduino A is connected to a transmitter and arduino B is connected a receiver.

Each device that will ever transmit anything will need a transmitter. Each device that will ever receive anything, needs a receiver. The devices you show in your question are separate receivers and transmitters, so on Arduino A and Arduino B, you will need both a receiver and a transmitter in order to have real, two-way communication between them.

Some RF devices are "Transceivers" which have both a receiver and a transmitter in the same module. Some of these can operate "full-duplex", meaning they can receive at the same time they are transmitting other data (Typically each direction is on a different frequency, but not necessarily.) Most cheap ones are half-duplex, meaning the module can only receive or transmit at any one time.

ADDITIONAL INFORMATION ABOUT RADIOHEAD

Your comment mentioned the RadioHead library. I was able to find the documentation on the library and see that it supports a wide range of radio chipsets and modules. The cheap ones you note are simple ones that use OOK (on-off-keying) or ASK (amplitude-shift-keying) and don't actually have a protocol. The receiver simply provide a HIGH or LOW output if it detects a signal on it's designated receive frequency. The transmitter simply oscillates at the transmit frequency when it's input pin sees a HIGH value, and stops when it sees a LOW value.

The RadioHead RH_ASK class deals with these simple transmitters. The documentation is at http://www.airspayce.com/mikem/arduino/RadioHead/classRH__ASK.html#details

This page notes the way to connect both a transmitter and receiver thus:

Connecting to Arduino

Most transmitters can be connected to Arduino like this:

Arduino                         Transmitter
 GND------------------------------GND
 D12------------------------------Data
 5V-------------------------------VCC

Most receivers can be connected to Arduino like this:

Arduino                         Receiver
 GND------------------------------GND
 D11------------------------------Data
 5V-------------------------------VCC
                                  SHUT (not connected)
                                  WAKEB (not connected)
                                  GND |
                                  ANT |- connect to your antenna syetem


RTClib now() within while loop does not update I ran into this while trying to make a battery monitor and wondered where I went wrong. Using RTClib available in the Arduino IDE or from adafruit github, I ran into problems when trying to call now within a while loop inside of loop.  Here is a simple example:
#include "RTClib.h"

#define ledPIN 13

RTC_PCF8523 rtc;

void setup() {
  // put your setup code here, to run once:
  pinMode(ledPIN, OUTPUT);
  digitalWrite(ledPIN, LOW);
  Serial.begin(9600);
  while(!Serial) {/* wait for Serial */}
  rtc.begin();
  rtc.start();
  digitalWrite(ledPIN, HIGH);
 }

void loop() {
  // put your main code here, to run repeatedly:
  char fmt[] = "YYYY/MM/DD-hh:mm:ss\n";
  while (millis() < 60000){
    Serial.println((rtc.now()).toString(fmt));
    delay(5000);
  }
  Serial.println("Finished");
  digitalWrite(ledPIN, LOW);
  while(1) { /* do nothing forever */ }
}

The output of this little test will be the same time repeated every 5ish seconds.  If it matters I am using a Feather M0 with the FeatherLogger that has an RTC on it.  Changing this loop function to this:
void loop() {
  // put your main code here, to run repeatedly:
  char fmt[] = "YYYY/MM/DD-hh:mm:ss\n";
  if (millis() < 60000){
    Serial.println((rtc.now()).toString(fmt));
    delay(5000);
  } else {
    Serial.println("Finished");
    digitalWrite(ledPIN, LOW);
    while(1) { /* do nothing forever */ }
  }
}

shows that now does in fact update the time every 5ish seconds.  I looked at the code for now and it appears to do very basic i2c commands to get the time and report it back.  The only thing I can think of is that the compiler created a (not so) temporary DateTime object for me within the while loop and the RTC library does not provide a convenient constructor or operator to overwrite the existing object.
I tested my theory with this
void loop() {
  // put your main code here, to run repeatedly:
  char fmt[] = "YYYY/MM/DD-hh:mm:ss\n";
  while (millis() < 60000){
    DateTime t1 = rtc.now();
    Serial.println(t1.toString(fmt));
    delay(5000);
  }
  Serial.println("Finished");
  digitalWrite(ledPIN, LOW);
  while(1) { /* do nothing forever */ }
}

But again, the time did not change so clearly I don't understand what's happening here.  Why doesn't the rtc now function work as intended within a while loop inside the loop function?

See the documentation of DateTime::toString():

The buffer parameter should be initialized by the caller with a
string specifying the requested format. This format string may contain
any of the following specifiers: [...] The specifiers within buffer
will be overwritten with the appropriate values from the DateTime.
Any characters not belonging to one of the above specifiers are left
as-is.

The important thing to realize is that the buffer parameter is used
both as input (for the format description) and as output (for the
formatted date and time). You initialize it with a format description
("YYYY/MM/DD-hh:mm:ss\n"). Then, after the first call to toString(),
the same buffer contains the formatted date and time. It does not
contain the format description anymore. On the second call to
toString(), as per the rule “Any characters not belonging to one of
the above specifiers are left as-is”, the buffer is not modified.
Solution: Put the buffer initialization within the same while loop
as the call to toString().


Problem : Trigger limit switch to stop DC motor I want to make a project about automatic gate and garage door via Android app and connected by HC-05 bluetooth module.
Each of the gate and garage door have two limit switches(located at each end of travel) to trigger the DC motor to stop.

I have made some code and do researches, but the DC motor will only stop when I pressed it, if I release it again it will start automatically. I want to make it stop until the bluetooth module send the code again.
I have input the pull-down resistor into the limit switch.

Can anybody please help me?

Here's my current code, thank you

// Motor for Gate (MotorA)
int IN1 = 2;
int IN2 = 3;
int EnableMotorA = 9;

// Motor for Garage Door (MotorB)
int IN3 = 4;
int IN4 = 5;
int EnableMotorB = 10;

const int LimitSwitch1 = A1;
const int LimitSwitch2 = A2;
const int LimitSwitch3 = A3;
const int LimitSwitch4 = A4;

int state;

void setup(){
  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(EnableMotorA,OUTPUT);

  pinMode(IN3,OUTPUT);
  pinMode(IN4,OUTPUT);
  pinMode(EnableMotorB,OUTPUT);

  pinMode(LimitSwitch1, INPUT);
  pinMode(LimitSwitch2, INPUT);
  pinMode(LimitSwitch3, INPUT);
  pinMode(LimitSwitch4, INPUT);

  digitalWrite(LimitSwitch1, LOW);
  digitalWrite(LimitSwitch2, LOW);
  digitalWrite(LimitSwitch3, LOW);
  digitalWrite(LimitSwitch4, LOW);

  Serial.begin(9600);
}

void loop(){
  if(Serial.available() > 0){
    state = Serial.read();
    }
    if(state == 'A') {
      OpenGate();
      if(digitalRead(LimitSwitch2) == HIGH){
      StopMotorA();
      }
    }
    else if(state == 'B') {
      CloseGate();
      if(digitalRead(LimitSwitch1) == HIGH){
      StopMotorA();
      }
    }
    else if(state == 'C') {
      OpenGarageDoor();
      if(digitalRead(LimitSwitch4) == HIGH){
      StopMotorB();
      }
    }
    else if(state == 'D') {
      CloseGarageDoor();
      if(digitalRead(LimitSwitch3) == HIGH){
      StopMotorB();
      }
    }
}

//******************   Motor A control   *******************
void OpenGate(){
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  analogWrite(EnableMotorA, 250);
  }
void CloseGate(){
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  analogWrite(EnableMotorA, 250);
}
void StopMotorA(){
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  analogWrite(EnableMotorA, 0);
 }
//******************   Motor B control   *******************
void OpenGarageDoor(){
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  analogWrite(EnableMotorB, 250);
}
void CloseGarageDoor(){
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  analogWrite(EnableMotorB, 250);
}
void StopMotorB(){
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  analogWrite(EnableMotorB, 0);
}
//**********************************************************

DISCLAIMER: I haven't tested the code in this answer, but I hope there are no problems.

Your code has a major problem: what happens when one gate is moving and you trigger another movement? (reply: something bad). This design issue can be solved by using a standard way of designing these kind of state machine.

In your case a small state machine is what best fits your problem. Better give your states a meaningful name, no?

Ok, so just to start, let's define the states and how to transition through them.

You have basically an idle state, open gate, close gate, open garage door, close garage door. What should you do in these states, both when entering the state and during the time you are in the state? Here is a table to summarize

State       | Enter         | During time
----------------------------------------------
Idle        | Stop motors   | -
OpenGate    | Start A dir 1 | -
CloseGate   | Start A dir 2 | -
OpenGarage  | Start B dir 1 | -
CloseGarage | Start B dir 2 | -

The transitions are pretty straightforward. Exit from idle when you receive a (valid) command, exit from the others when you reach the endstop.

The implementation is pretty standard:

// Motor for Gate (MotorA)
const byte IN1 = 2;
const byte IN2 = 3;
const byte EnableMotorA = 9;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 5;
const byte EnableMotorB = 10;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const byte State_Idle = 0;
const byte State_OpenGate = 1;
const byte State_CloseGate = 2;
const byte State_OpenGarage = 3;
const byte State_CloseGarage = 4;
byte currentState;

void setup(){
    pinMode(IN1,OUTPUT);
    pinMode(IN2,OUTPUT);
    pinMode(EnableMotorA,OUTPUT);

    pinMode(IN3,OUTPUT);
    pinMode(IN4,OUTPUT);
    pinMode(EnableMotorB,OUTPUT);

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Serial.begin(9600);
    currentState = 0xFF; // Force a change to enter the idle state
}

void loop(){
    // Check if we need to change state
    byte nextState = currentState;
    switch (currentState)
    {
    case State_Idle:
        { // If we received a valid command, start the operation
            if(Serial.available() > 0)
            {
                switch (Serial.read())
                {
                case 'A':
                    nextState = State_OpenGate;
                    break;
                case 'B':
                    nextState = State_CloseGate;
                    break;
                case 'C':
                    nextState = State_OpenGarage;
                    break;
                case 'D':
                    nextState = State_CloseGarage;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case State_OpenGate:
        if(digitalRead(LimitSwitch2)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_CloseGate:
        if(digitalRead(LimitSwitch1)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_OpenGarage:
        if(digitalRead(LimitSwitch4)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_CloseGarage:
        if(digitalRead(LimitSwitch3)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    default:
        nextState = State_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentState)
    {
        currentState = nextState; // Move in the new state
        switch (currentState)
        { // Entering the new state
        case State_Idle:
            // Stop motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            // Stop motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            break;
        case State_OpenGate:
            // Start motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, HIGH);
            analogWrite(EnableMotorA, 250);
            break;
        case State_CloseGate:
            // Start motor A
            digitalWrite(IN1, HIGH);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 250);
            break;
        case State_OpenGarage:
            // Start motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, HIGH);
            analogWrite(EnableMotorB, 250);
            break;
        case State_CloseGarage:
            // Start motor B
            digitalWrite(IN3, HIGH);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 250);
            break;
        }
    }
}

(Note: I changed some types because your poor 8-bit uC asked me to avoid complicating its calculations unnecessarily)

One modification to your algorithm is to detach the two loops, since they seem, well, detached.

// Motor for Gate (MotorA)
const byte IN1 = 2;
const byte IN2 = 3;
const byte EnableMotorA = 9;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 5;
const byte EnableMotorB = 10;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const byte StateA_Idle = 0;
const byte StateA_Open = 1;
const byte StateA_Close = 2;
byte currentStateA;

const byte StateB_Idle = 0;
const byte StateB_Open = 1;
const byte StateB_Close = 2;
byte currentStateB;

void setup(){
    pinMode(IN1,OUTPUT);
    pinMode(IN2,OUTPUT);
    pinMode(EnableMotorA,OUTPUT);

    pinMode(IN3,OUTPUT);
    pinMode(IN4,OUTPUT);
    pinMode(EnableMotorB,OUTPUT);

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Serial.begin(9600);
    currentStateA = 0xFF; // Force a change to enter the idle state
    currentStateB = 0xFF; // Force a change to enter the idle state
}

void loop()
{
    byte readChar = 0;
    if(Serial.available() > 0)
        readChar = Serial.read();

    stateMachineA(readChar);
    stateMachineB(readChar);
}

void stateMachineA(byte readChar)
{
    // Check if we need to change state
    byte nextState = currentStateA;
    switch (currentStateA)
    {
    case StateA_Idle:
        { // If we received a valid command, start the operation
            if(readChar > 0)
            {
                switch (readChar)
                {
                case 'A':
                    nextState = StateA_Open;
                    break;
                case 'B':
                    nextState = StateA_Close;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateA_Open:
        if(digitalRead(LimitSwitch2)) // == HIGH is not necessary
            nextState = StateA_Idle;
        break;
    case StateA_Close:
        if(digitalRead(LimitSwitch1)) // == HIGH is not necessary
            nextState = StateA_Idle;
        break;
    default:
        nextState = StateA_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentStateA)
    {
        currentStateA = nextState; // Move in the new state
        switch (currentStateA)
        { // Entering the new state
        case StateA_Idle:
            // Stop motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            break;
        case StateA_Open:
            // Start motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, HIGH);
            analogWrite(EnableMotorA, 250);
            break;
        case StateA_Close:
            // Start motor A
            digitalWrite(IN1, HIGH);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 250);
            break;
        }
    }
}

void stateMachineB(byte readChar)
{
    // Check if we need to change state
    byte nextState = currentStateB;
    switch (currentStateB)
    {
    case StateB_Idle:
        { // If we received a valid command, start the operation
            if(readChar > 0)
            {
                switch (readChar)
                {
                case 'C':
                    nextState = StateB_Open;
                    break;
                case 'D':
                    nextState = StateB_Close;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateB_Open:
        if(digitalRead(LimitSwitch4)) // == HIGH is not necessary
            nextState = StateB_Idle;
        break;
    case StateB_Close:
        if(digitalRead(LimitSwitch3)) // == HIGH is not necessary
            nextState = StateB_Idle;
        break;
    default:
        nextState = StateB_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentStateB)
    {
        currentStateB = nextState; // Move in the new state
        switch (currentStateB)
        { // Entering the new state
        case StateB_Idle:
            // Stop motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            break;
        case StateB_Open:
            // Start motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, HIGH);
            analogWrite(EnableMotorB, 250);
            break;
        case StateB_Close:
            // Start motor B
            digitalWrite(IN3, HIGH);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 250);
            break;
        }
    }
}

This second implementation has two parallel state machines (sharing only the serial input). This will allow you to control both gates at the same time (for instance when the gate is closin you can open the garage)


SIlly PID question using the PID library I'm new to PID.
My goal: control the motor to get it to run a given RPM by a potmeter (which is setpoint).
Sensor is optical (detects white line, reflections), counts 100 round in x amount of time. Small calculation gives detected RPM.
I'm using an Arduino and the PID library.

Now my question.
Let's say I've implemented the PID lib on the arduino. It all calculates and so on, but it gives a PID_value which I don't understand.

Ex:
setpoint = 5000
detected = 4999
received PID value = 40

It's my guess that this (or rather: all) PID-lib I'm using always gives a value between 0 and 255 and I have to map/scale that value to my AC trigger.
Could someone point me in the right direction? Thanks!

See PID Library - SetOutputLimits() - you can change the limits.

For a meaningful result you need to make the output do something reasonable to the speed. Since your detected speed is lower than the desired speed, you have found it outputs a positive value, which is good, as far as it goes. But you have to interpret that in the context of what you are currently sending to the motor. If you are using PWM to control the motor you could feed the output (40 in this case) to the motor. If that makes it go even slower hopefully the PID library will compensate.

It's hard to make more suggestions without seeing the code.


Would a 100KΩ resistor connected to ground pull an open analog line down to 0 I have a project that has a photoresistor wired into a voltage divider and connected through a 3.5mm “stereo mini plug”. When nothing is in the mini plug, the analog line is an open circuit, and floats, creating jittery spurious readings.

I’d like to wire a pull-down resistor into the project box to tie it to ground so I get a zero reading when the light sensor is not connected, but want to alter the voltage reading from my photo sensor voltage divider circuit as little as possible.

If I connect a 100KΩ resistor between my analog input and ground, that would give me zero readings on the analog pin when the photo sensor is not plugged in, wouldn’t it? I can’t see how < 20 CM of 26 gauge wire would pick up enough interference to pull my analog pin up from 0 through a 100kΩ resistor.

What is the effective range of an analog pin on an Arduino? (A Mega 2560, if that matters) What’s the lowest voltage that will register above 0?

(The project box is getting crowded, so experimenting is getting tricky. I’d like to make a single change rather than trying different resistor values.)

With a 100 kΩ resistor to GND, it is not guaranteed that the value will be zero. If a (servo)motor is connected, it might get some noise.

The pull down resistor can be any value, because it is possible to calculate the value of the photoresistor.

There is an alternative solution. I think that all the analog pins of the Arduino Mega 2560 are digital pins as well. You can do a pinMode(A0,INPUT_PULLUP); to pull the input high. When a photoresistor is connected, you can turn the internal pullup resistor off with pinMode(A0,INPUT);.


Reliably duplicate custom IR remote control with ATTiny85 This is something I'm struggling with for a while and fail to find solid solution.
The Arduino IR library provides method for recording arbitrary IR code and re-sending it. This gave me different results every time I recorded the IR remote, so I wrote a little code, based on interrupts, that try to record the IR rise/fall as accurately as possible.
I am working with ATTiny85 running at 8Mhz on internal oscillator.

Here is the code:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(4,3);

const int dataSize = 40;
int data[dataSize];
int dataLength[dataSize];

void setup() {
  pinMode(0, OUTPUT); // 0 is IR receiver pin
  mySerial.begin(9600);
  mySerial.println("Start");
  attachInterrupt(0,IR_ISR,CHANGE);
  mySerial.println("Registered");
  sei();
}
volatile unsigned long prev = micros();
volatile unsigned long curr = -1;
volatile unsigned short index = 0;
volatile bool rising = true;
void IR_ISR()
{
  if (!rising)
  {
    dataLength[index] = micros() - curr;
    rising = !rising;
    return;
  }

  curr = micros();

  data[index++] = (int)curr-prev;

  prev = curr;
  rising = !rising;
}

void loop() {

  delay(5000);
  for (int i=1; i<dataSize; i++)
  {
    mySerial.print(data[i]);
    mySerial.print("(");
    mySerial.print(dataLength[i]);
    mySerial.print(")");
    mySerial.print("; ");
  }
  mySerial.println();
  index = 0;
}

Problem is that the milliseconds alter on each record of the remote control, here is an example of the output of 3 attempts of clicking at the same button of the remote control (I pasted only the first 5 IR modulations to avoid too much text, total is about 39):

  Start
  Registered

  14104(9496); 1184(672); 1184(616); 1160(656); 1176(672); ...

  14096(9480); 1184(664); 1208(568); 1136(616); 1184(664); ...

  14096(9384); 1216(576); 1136(616); 1184(664); 1208(560); ...

The format is: [microseconds from previous falling edge](microseconds from rise to fall);

As you can see, the results vary. According to the arduino.cc website, the micros() function has a 8 microseconds resolution on 8Mhz AVR's, but the difference between reads is bigger than that.

This is not reliable enough for me to solidly duplicate a remote control, and I'm looking for a resolution that will provide accurate results, as the magnitude of every deviation increases when the voltages are low (for example, with a 3v 2032 coin battery half discharged).

The exact duration of the pulses don't matter much. In your example, you see that in all three recorded samples that's

about 14000 (about 9400); about 1200 (about 600); about 1200 (about 600) etc.

What matters is that nowhere you have pulses of about 900 : in other words if the receiver detects a 672 pulse it will know that it's definitely a 600, not a 1200.

So if you send exactly those values, the receiver will recognize it.


ESP8266-01 is not working and it's hot it has been so long since I tried to connect the esp8266 through Arduino Uno and get it to work my goal is to send data from the Arduino Uno to web site, I have tried everything and a lot of codes but none worked at first I could get a response  but sometimes it does and sometimes it does not I even bought an other one but the new one did not respond at all so I flashed the old one following the instructions in here and I got response the next day I tried to reuse it and it does not respond at all not even when I put the serial on 115200 and both NR&CR and tried AT but nothing showed in return .i found this tutorial
and I tried to get it to work using a mobile app but as usual, it does not work

AT
AT+RST
ATE0
AT+CWMODE=1
AT+CWQAP
AT+CWDHCP=1,1
AT+CWJAP="RemoteXY","12345678"

but i did not get hte name of it wifi in my wifi list
this is the code

// RemoteXY select connection mode and include library
#define REMOTEXY_MODE__ESP8266_HARDSERIAL

#include <RemoteXY.h>

// RemoteXY connection settings
#define REMOTEXY_SERIAL Serial
#define REMOTEXY_SERIAL_SPEED 115200
#define REMOTEXY_WIFI_SSID "RemoteXY"
#define REMOTEXY_WIFI_PASSWORD "12345678"
#define REMOTEXY_SERVER_PORT 6377

// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
  { 255,2,0,0,0,30,0,8,13,0,
  2,0,70,25,22,11,2,26,31,31,
  79,78,0,79,70,70,0,1,0,10,
  26,12,12,2,31,88,0 };

// this structure defines all the variables of your control interface
struct {

    // input variable
  uint8_t switch_1; // =1 if switch ON and =0 if OFF
  uint8_t button_1; // =1 if button pressed, else =0

    // other variable
  uint8_t connect_flag;  // =1 if wire connected, else =0

} RemoteXY;
#pragma pack(pop)

/////////////////////////////////////////////
//           END RemoteXY include          //
/////////////////////////////////////////////

#define PIN_SWITCH_1 2
#define PIN_BUTTON_1 12

void setup()
{
  RemoteXY_Init ();

  pinMode (PIN_SWITCH_1, OUTPUT);
  pinMode (PIN_BUTTON_1, OUTPUT);

  // TODO you setup code

}

void loop()
{
  RemoteXY_Handler ();

  digitalWrite(PIN_SWITCH_1, (RemoteXY.switch_1==0)?LOW:HIGH);
  digitalWrite(PIN_BUTTON_1, (RemoteXY.button_1==0)?LOW:HIGH);

  // TODO you loop code
  // use the RemoteXY structure for data transfer

}

i wired it like this

one last thing is it gets hot every time so what could be the problem what's wrong with is what should I do

when a chip gets hot as soon as the VCC/GND is connected, it means :

The VCC/GND are internally connected due to a previous failure (it
gets hot AFTER the accident).
An output pin, is connected to a supply rail through a very low resistance load (or short circuited). pins usually sink or
source as low as 20mA of current. so if you connect them to a load
less than (3.3/20)*1000 ~= 150 ohms (in your case with 3.3v supply),
you are going to fry the output driver. always be sure that a pin, even if it's defined as an input, has a little resistor (a 220 ohms res).
this accident happens between output/supply or output/output pins.

you may have misconnected TX pin to a wrong pin.


get current time in nanoseconds On Arduino due, Is this possible to get the current time in nano seconds?
At 84Mhz, I guess it will always be a multiple of ~12ns.

And a perfect solution would read a register/variable rather than call a function. Because I want to avoid the cost of calling a function which is in order of microseconds.
what about counting clocks since start of execution. is this possible?

Yes, it should be.  At least according to the Cortex M3 Technical Reference Manual that I think I downloaded from ARM.  (DDI0337E_cortex_m3_r1p1_trm.pdf)

In section 11.5 of said manual, there is a register called DWT_CYCCNT (Data Watchpoint and Trace Cycle Count Register) which is incremented once per clock cycle when the appropriate flag of the DTW_CTRL (DWT Control) register is set.

This flag is unset on reset of the CPU so it needs to be set manually (unless it is done by the Arduino IDE, but checking the header files of the IDE, it doesn't look like it as unlike many other CPU registers, there is no Arduino REG_ define for these registers).

This untested code should be usable as the basis for your own code.  I suggest you add some serial initialisation in there and dump the value of currentCycles to the serial log to test it.  I am away from my hardware at the moment so can only test that it compiles.

#define REG_DWT_CTRL (*(unsigned int*)0xE0001000U)      /* Data Watchpoint and Trace Control Register */
#define REG_DWT_CYCCNT (*(unsigned int*)0xE0001004U)    /* Data Watchpoint and Trace Cycle Count Register */

#define CYCCNTENA ( 1 << 0 )                            /* DWT CTRL Cycle Count Enable Bit */

void setup()
{
    REG_DWT_CTRL |= CYCCNTENA;
}

void loop()
{
    unsigned int currentCycles = REG_DWT_CYCCNT;
}

Edit:
Note that the counter is a 32 bit register, so at 84 MHz it will reset every 51.13 seconds.  It is a read only register so writing to it will have no effect (you cannot manually reset it that way).


atmega328: external crystal oscillator and uart I need an clearity about external crystal oscilator. I got communication between esp32 and atmega8/88/328 processor, I use atmega wih internal oscillator and looks like it have problem with serial communication (some time it lose data, or replace it with nonsences).

So i have read that should use extercal crystal oscillator to achieve stable uart communication.

Question is that, what frequency to choose, and how that gonna effect uart, and atmega processor lifetime. I know if choose 16mhz processor gonna run faster, but assume it life time will decrease compated with 1mhz or 8mhz.
What about uart, which one of those frequences are best for it, or it make no difference?

There are some specific crystal oscillator frequencies named 'UART friendly'. Using these frequencies would lower % error in UART communications. Please refer to the table in the datasheet, in chapter named "BAUD rate settings" (datasheet of ATMega328: '24.11. Examples of Baud Rate Setting'). There are tables to show error percentage. What to look at is "Error" column. fosc is selected oscillator/crystal frequency. For succesful UART communication you aim for less than 3.5% Error.
 Your crystal speed should depend on your desired communication speed, for example for me the preferred ones are 11059200Hz or 1843200Hz.

or below:

With raising frequency you may expect power consumption and the chip's temperature rise, anyway I wouldn't worry too much about life shortening. More important here would be power consumption rise.
 Do you want the chip(device) to be battery powered? To save on energy you can also consider lower frequencies like 1.8432MHz or 3.6864MHz.


Do I need to use a resistor if I am using a potentiometer to control an LED's brightness? I am currently tinkering with an arduino, and am using a potentiometer to change the brightness of an LED.

I understand that usually, a resistor is added to the circuit to limit the current flowing through the circuit in order to prevent the LED from burning out.

However, as I am currently using a potentiometer to adjust the LED's brightness, AND as a potentiometer is basically a variable resistor, would I still need a resistor to prevent the LED from burning out? Currently, I do not see a difference between using a 220 ohm resistor and not using it, as the LED seems unaffected.

My code:

const int pot=A0;
const int led=11;
int potValue;

void setup(){
  Serial.begin(9600);
  pinMode(pot,INPUT);
  pinMode(led,OUTPUT);
  analogWrite(led,100);
}

void loop(){
  potValue = analogRead(pot);
  potValue=map(potValue,0,1023,0,255);
  analogWrite(led,potValue);
  Serial.println(potValue);
}

PS: My LED is hooked up to the arduino's PWM pin, and connected to ground on a breadboard.

Without a good quality picture of your setup or some schematics, it's hard to tell what's going on, but from your description, what you're doing is potentially harmful for the LED and the output pin D11.

Yes, LEDs almost always need series resistors to limit their current. They don't limit currents and will burn if you don't do it for them.

If you had the pot in series with the LED, which seems to be what you think is going on, you'd still need a series resistance so that when the pot is all the way to one side, effectively behaving like a 0Ω resistor or a short, you'd still be limiting the current with the 2nd resistor. One would usually use Ohm's Law to calculate that 2nd resistance so that it lets the maximum current the LED can take when the pot is at 0Ω position, usually 20mA for common LEDs.

But that's not how your circuit seems to be wired. The pot is indirectly controlling the LED through an analog input and a PWM output via MCU. So it's not limiting the LED current, in the traditional sense. The pot seems to be wired between 5V and GND with the middle lead (the cursor) hooked up to the analog input A0. That's a variable voltage divider configuration that let's you select a continuous voltage between 0 and 5V that is in turn converted to a value between 0 and 1023 by the MCU ADC (Analog to Digital Converter) - that's the result of the analogRead() call.

That value is then fed to a PWM analog output, through the analogWrite() call, that will output a square wave to the LED. The relative position of the pot will determine the duty cycle of the PWM, i.e., how long the square wave is HIGH or LOW. The problem here is that this circuit where the LED is wired should have its own series current limiting resistance.

To me, if you didn't burn the LED or the D11 pin yet, is pure luck. If you were to turn the pot all the way to maximum brightness (don't do it), the PWM output would act like a digital output put in HIGH level (5V continuously), and without a current limiting resistor, the D11 pin would exceed it's 40mA absolute maximum source current and burn. Unless there's another factor limiting the current that I don't know of, that is.

There are some exceptional cases in which you can control the LED voltage closely so you don't need to limit the current (multiplexing, constant-current supply etc.), but these are really advanced configurations for us newbies. So, from know on, do it like I do it: ALWAYS put a series resistor, until you become familiar with these advanced configurations.

Finally, below are some links that you may find helpful about the topic:

SparkFun Tutorial on LED Current Limiting Resistors
WikiPedia Article about LED series resistors


Serial.available() function for Arduino I want to implement a function in another micro-controller which works like serial.available(). I don't know how it works. I read about Serial.available() in this link.

Whenever I write a string on the terminal, it prints the length of the string. Can anyone tell me how it works?

It reports the difference between the head and the tail of the circular buffer the incoming characters are stored in.

The way serial reception on the Arduino works is:

A character is received into the internal hardware RX buffer (UDRx)
An interrupt is triggered
An interrupt service routine (ISR) is executed
The character in UDRx is read and, if there is room, stored in a circular buffer (_rx_buffer).
The head pointer of _rx_buffer is incremented and wrapped if needed.

When you actually read a character with Serial.read() the following happens:

If the head and tail of rx_buffer are equal, return -1
Get the character at tail from _rx_buffer
Increment tail and wrap if needed
Return the character

So when you use Serial.available() it just returns head - tail (taking into account the wrapping, so the sum is slightly more complex than a simple subtraction).

You should examine the files HardwareSerial.h and HardwareSerial.cpp in the Ardino AVR core software.


Arduino Uno serial communication using USB-to-TTL converter How to send data (Hello World) from Arduino Uno to a PC using USB to TTL/UART (PL2303 4 wires)? Why do I need to press the reset button to upload a program using PL2303?

How to send data(Hello World) from Arduino Uno to PC using USB to TTL/UART(PL2303 4 wires)?

Serial.print("Hello World");

That is, assuming it's connected to pins 0/1. Otherwise you would have to use SoftwareSerial.

  why I need to press the reset button during upload a program using PL2303?

Because it lacks a DTR signal to press the reset button for you (resetting runs the bootloader).


Why does Ethernet.begin() require a MAC address when WiFi.begin() doesn't? I am working on an Arduino application which is dependant on a certain library. This library uses the Ethernet class for network communications, but ideally, I would like it to be wireless (I have both an Ethernet and WiFi shield available for testing).

When working on replacing the Ethernet functionality of the library with the corresponding WiFi functionality, I noticed that the Ethernet.begin() function requires a MAC address while the WiFi.begin() doesn't (it instead accepts SSID and password, among a couple of other things).

As both come shipped with a MAC address sticker on them, I couldn't really figure out why this is the case (and if I need to supply the MAC address found on the WiFi shield in some other fashion).

Why is this the case?

The flip answer would be "because it doesn't need it…"

I think what is going on is that older Ethernet shields did not have a MAC address and it was necessary for the code to set one (and I would guess that on at least some of them you can still set the MAC address, overriding the one that is on the sticker).

WiFi cards, I would guess, are newer and the MAC address is always there, so there is no need to require you to assign it.


Arduino encrypted Radio communication Is there any way or library to communicate two Arduino devices with encrypted connection using modules NRF24L01 or "433Mhz RF" ? Similar encryption like CCMP in Wi-Fi network.

Communicating and Encryption are to completely separate things. How you communicate (with what device) has no relevance to encryption. True, there are devices that can themselves encrypt data, but they tend to be higher-end or geared towards a specific purpose (such as WiFi).

What you send is just data. What that data consists of is entirely up to you.  If you want your communications encrypted then send encrypted data before sending it and decrypt it after receiving it.

Of course, you have to then consider such things as sharing of keys, etc.

There are numerous ways of encrypting data, but one of the easiest to implement on Arduino is AES, for which there is a library here.


PT2257 only gives me heavy buzzing sound I have this project where I control a bluetooth audio module with an arduino. In this case, I have used an arduino nano. But then, I have been meaning to add volume control to the project so I use a pt2257. But the sounds that it gives to me is my audio plus heavy buzzing sound and no matter how much attenuation that I set the volume doesnt seems to change. Can anyone help me?
Here is the schematics that I use for the PT2257:

I have tried giving Vdd 5V from arduino, and also 5V from a seperate power supply. But it seems there is no difference.
Here is the code that i use:
    void setup() {
      delay(1000);
      Wire.begin();
      Serial.begin(115200);
    }
    void loop() {
      Wire.beginTransmission(Volume_address);
      Wire.write(0b011100000);    // set low attenuation
      Serial.print("result 1: ");
      Serial.println(Wire.endTransmission());
      delay(2000);
      Wire.beginTransmission(Volume_address);
      Wire.write(0b11111111);  // set full attenuation
      Serial.print("result 2: ");
      Serial.println(Wire.endTransmission());
      delay(2000);
    }

Here is the link to PT2257 datasheet if you need it
EDIT:
Here is how I connect CSR8645 Output to my active speaker, before I add a attenuation IC. It works like a charm like this, but I need to add a volume control.

many amps and BT audio chips use differential input/outputs. none of the inputs nor outputs are considered grounds.
the Lp(left,postivie) Ln, Rp and Rn on your audio chip should be connected to loads directly. Ln or Rn are not audio grounds. so you can't use simple POT volume controls or any processor or amplifier chip that doesn't support differential IOs. so, you can't use PT2257 in this circuit.
for better understanding here are two audio signal types:

the simple, well known one, which consists of GND and an audio IN per channel. you can use many amplifiers, processors (e.h. PT2257) and POT volume controls. and one end of the output (e.g. speaker) is connected to GND.
the differntial audio signal which consists of a GND and a pair of IN+,IN- per channel. you can't use the soulutions mentioned above. for example, if you wanted to amplify the output signal of the bluetooth chip, you have to use something like PAM8302, 2.5W mono class D audio amp per channel. note the IOs:


Can adjustable constant current/voltage source be made with Arduino? I would like to create a 18650 battery automatic management system that can handle and restore used up cells using solar panels for power. To do that I need to create adjustable constant current source that will limit the current/voltage going into the cell/cells to a small enough value.

Since there are more features I would like to implement (like checking cell capacity) I would love to use Arduino with least amount of components as possible to keep the cost down.

My first question is: Will Arduino be fast enough to control a MOSFET that will pump magic pixies into a capacitor to achieve steady value of voltage on said capacitor?

The pseudocode for logic I'm proposing is simpe:

Use ADC to check voltage on the capacitor (or a very small value power resistor when working as current source)
Calculate required voltage adjustment
Use AnalogWrite to set new PWM value into internal PWM controller.

Second question: PWM causes a lot of "switching" in the MOSFET. When MOSFET is not saturated state it's resistance is high and a lot of power is wasted as heat. Would it be possible NOT to use PWM to control it, but instead to turn it OFF or ON each cycle to minimize power loss? Since the batteries have some internal resistance voltage variation of +-20% should be acceptable.

You are basically describing (if you add an inductor and a diode into the mix) a simple switching regulator.  That is, at its simplist, a PWM signal, some smoothing (inductor, diode, capacitor), and feedback.

Use the Arduino's PWM to switch a P-channel MOSFET in the voltage supply. That switched supply is then fed through an inductor, and then smoothed with a capacitor:

simulate this circuit – Schematic created using CircuitLab

M1 does the switching of the power to charge the rest of the circuit.  L1 + C1 smooths the PWM out giving a constant smooth (ish) voltage. D1 completes the circuit between L1 and C1 in one direction only keeping the charge in the right part of the circuit.

R1 keeps the MOSFET turned off when not being driven.

R2 is a very small "shunt" resistor (maybe 0.1Ω for example).

The size of C1 and L1 are determined by the switching frequency of your PWM and the current demands of the circuit.  The higher your switching frequency the smaller your inductor can be, The higher your current demands the larger C1 needs to be.

Reading A1 gives the output voltage of the circuit, so you can adjust the PWM (using PID would be good) to get a specific voltage.

Reading A0 and A1 and subtracting one from another gives you the voltage drop across R2. From that, you can calculate the current through R2 using Ohm's Law. You can then use that to adjust the PWM to give you a specific current.

Of course, you can't do both at once. You either have a constant current (during the first charging phase to bring the cell voltage up to 4.2V), and then switch to constant voltage until the current drops to around 0.3C.  For dead cells, an initial constant current phase of (IIRC) 0.1C can recover the cell.

Some important notes about lithium cells:

They explode (just ask Samsung), so take care. It can be good to do your experimenting with the cell contained within a fireproof container.
Lithium Ion and Lithium Polymer cells don't like being over-discharged, but as long as they haven't been reverse charged they can generally be recovered.
Cells that are used in a series pack and haven't been charged with a proper balancing charger may well have been reverse charged if the pack has "died".

The reverse charge thing is what actually kills a Lithium cell.  Basically, no two cells will have exactly the same capacity. If you have, say, three cells in series and you discharge the whole pack to below the recommended minimum, once cell will have less charge than the others. If that cell hits zero the current from the other cells will start flowing backwards through it, and that backward current causes copper crystals to deposit on the electrolyte layer between the electrodes. Those pierce the electrolyte layer and short the two electrodes together, and at that point the cell is dead. No amount of recovery charging will get it back, it's physically damaged.

So in summary:

A single cell that has been over-discharged by itself will generally be recoverable.
A series pack of cells that has been over-discharged may well have physically damaged one of the cells in the pack through reverse charge flow.

  Will Arduino be fast enough to control a MOSFET that will pump magic pixies into a capacitor to achieve steady value of voltage on said capacitor?

Sure. You should pre-condition your power so it is always within a tolerable limit (i.e., feed your solar panel power through a suitable 5V buck regulator to give a clean 5V supply). There will always be some latency in the circuit due to how long the inductor "resists" changes in the voltage. A typical Arduino takes ~100µs to sample an ADC. In this kind of environment, that time is negligible since it's generally much faster than a single period of PWM. You can't respond faster than one period of PWM anyway.

  When MOSFET is not saturated state it's resistance is high and a lot of power is wasted as heat. Would it be possible NOT to use PWM to control it, but instead to turn it OFF or ON each cycle to minimize power loss?

That's what PWM does. It's ON or OFF. On at the start of a cycle, then off part way through.  Yes, there is a brief period twice per cycle while it does the switching, but that will be minimal compared to the on and off periods. The losses from that switching will be negligible compared to, say, running a MOSFET as an adjustable resistance controlled from an op-amp with feedback from a current shunt (i.e., a linear regulator).


Arduino - Getting error - 'TCCR2' was not declared in this scope This code below:

void setup() {
  #if defined(__AVR_ATmega168__)
    // 62.5KHz PWM for the ATMega168 -> only on Arduino pins 9 and 10

    // set prescaler to 1
    // (sbi means "set bit register", cbi means "clear bit register")
    cbi(TCCR1B, CS12);
    cbi(TCCR1B, CS11);
    sbi(TCCR1B, CS10);

    // set fast PWM
    cbi(TCCR1B, WGM13);
    sbi(TCCR1B, WGM12);
    // with fast PWM, the frequency is (CLK/256*prescaler) = 16MHz/256 = 62.5KHz
    // with slow PWM, it is half that speed (31KHz)
  #else
    // 22KHz for the ATMega8 (this is a low frequency)
    TCCR2 = ((TCCR2 & ~0x07) | 0x01); //<ERROR POINTS HERE!
    TCCR1B = ((TCCR1B & ~0x07) | 0x01);
  #endif
}

when verify, generates an error:

In function 'void setup()':
pwm-control-1:185: error: 'TCCR2' was not declared in this scope
TCCR2 = ((TCCR2 & ~0x07) | 0x01);
^
exit status 1
'TCCR2' was not declared in this scope

So far i know this code generates pwm at pin 9 or 10, and designed for ATmega168 or ATmega8. The code came with a .pde extension and I opened it on 'Arduino: 1.8.3' and saved as an .ino file.

Can any one please tell me how to convert this code to work with 'ATmega328P-PU' and for the latest Arduino IDE. And also if there anything else to consider running with this code

I'm not an expert in pwm and timer/controls in micros... just started to learn..

Note: I've only shown the necessary part of the code

Looks like this code is pretty old. It's assuming that any Arduino that isn't using an ATmega168 is using an ATmega8. In reality, the ATmega8 hasn't been used on any Arduino boards in the last ten years or so -- it's pretty much obsolete.

The easiest fix will be to remove the non-'168 branch (between #else and #endif), and make the '168 branch default (remove the #if line). This will probably still fail on ATmega32U4 boards, but at least it'll now work on ATmega328 hardware.


Sketches won't upload to Uno Today I tried to update the sketch on my Arduino Uno, but was unable to due to this error:

Sketch uses 1,870 bytes (5%) of program storage space. Maximum is 32,256 bytes.
Global variables use 188 bytes (9%) of dynamic memory, leaving 1,860 bytes for local variables. Maximum is 2,048 bytes.
D:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/bin/avrdude -CD:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\User\AppData\Local\Temp\build2f7b4a32c3810b2d8e42648954faba05.tmp/nes_controller.ino.hex:i
An error occurred while uploading the sketch

Nothing will upload to the board now. I tried uploading a simple sketch with empty setup() and loop() functions, I've tried different PCs and gotten the same error, I've swapped USB cables, I've double-checked that I'm using the right COM port, I've disconnected every wire from the Arduino pins - nothing has helped.

The old sketch is still running fine on the Uno. It was uploaded a few days ago using the exact same setup I'm trying right now.

The Arduino IDE doesn't even indicate any errors, everything compiles and looks good until "An error occurred while uploading the sketch"

You can set the verbosity level in the Arduino IDE:

File menu
Preferences
Settings tab
"Show verbose output during" => check "upload"
Click OK

Upload again, and note the additional output telling you what is wrong.

It should also point you to this URL, which points out the most occurring issues.

The issue I have most, is that I forget to switch between Micro and Uno board (as I deploy my sketch on both boards).


error: espcomm_upload_mem failed when uploading a sketch I am new to the whole arduino scene. I have connected my wifi module (esp8266 v01) to my arduino Uno like this:

http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/

And have downloaded the arduino ide framework so that I may be able to use the arduino IDE as opposed to sending AT commands through the serial monitor.

When trying to upload an example sketch that sends a http request that I found on github, I get the following error:

    Arduino: 1.8.4 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

Archiving built core (caching) in: C:\Users\Yasmeen\AppData\Local\Temp\arduino_cache_354217\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____9d1d735445f8d7bf19746e2177d24e71.a
Sketch uses 285417 bytes (65%) of program storage space. Maximum is 434160 bytes.
Global variables use 38688 bytes (47%) of dynamic memory, leaving 43232 bytes for local variables. Maximum is 81920 bytes.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

After looking online and researching, I can see that it has something got to do with flashing the firmware or something. I came across this question:

ESP8266 error: espcomm_upload_mem failed while uploading sketch

and the answer did say that he bought a converter.. what does this mean? Does it mean buying this?:
https://www.amazon.co.uk/gp/product/B06Y3FNGJF/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

I really need help, been stuck on this for the past few days now and seriously contemplating whether to get the arduino wifi shield since it comes prebuilt with wifi.. even though it costs quite a lot!

The ESP8266 has two "modes". "Run" mode and "Flash" mode.  In "Run" mode the firmware installed onto the ESP8266 executes. The default firmware is the AT firmware that allows you to control the device with AT commands through serial.

Note that the site you link to has erroneous information about CH_PD that should be talking about GPIO0.

In "Flash" mode you get to upload new firmware (AKA a "sketch") to make the device do something different.

The basic programming sequence is:

Switch the device to Flash mode (connect GPIO0 to GND)
Upload the sketch using the IDE
Switch the device to Run mode (connect GPIO0 to 3.3V).

Because of these extra steps many people choose to invest in a small USB interface board designed specifically for programming the ESP8266 to make their life easier. These generally have a switch on them to set whether GPIO0 is connected to GND or 3.3V.


Arduino Communication with Sim 900 Im using an arduino uno and a sim 900, the simcard is setup and working as I can make a phone call to it and it rings.

The sim 900 is powered via the power jack and the uno is currently powered using USB.

I am trying to print out incoming text messages however with serial monitor open I only see "Initialising...".

    #include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CNMI=1,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
  updateSerial();
}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

I cant for the life of me figure out why its not printing anything else out? Can anyone give me any guidance or what to check?

The 'Initializing' printout happens because that is sent directly to the UNO's hardware serial port.  The rest doesn't happen because it is directed to the SIM card via SoftwareSerial pins 7 & 8, and the SIM card apparently isn't responding.

Cut the problem in half:  Connect pins 7 & 8 together, and run your program again.  If you get "AT" and the rest, then you know the 'MySerial' port is active and working correctly, and the problem is in the SIM 'half'.  Maybe you have an incorrect wire connection there, or maybe the SIM card's default serial rate isn't 9600, or something like that.  YMMV ;-).

As a test, I ran your program on a UNO, with a jumper wire between pins 7 & 8.  Unfortunately this did not work, but now I knew that the problem had nothing to do with the SIM shield. The result wasn't what I expected, but now I had 'cut the problem in half'.

Now that I had determined that the SIM card wasn't a factor (so far, anyway), I could concentrate on the 'UNO half'.  After some web research I found that 'Software Serial' doesn't support 'loopback' (looping the transmit line back into the receive line) because it cannot simultaneously transmit and receive.  Fortunately, the 'AltSoftSerial' library by Paul Stoffregen does support simultaneous transmit & receive, and so will support loopback.

So, I installed the library on my Arduino setup, and compiled and uploaded the example shown below.

#include <AltSoftSerial.h>

// AltSoftSerial always uses these pins:
//
// Board          Transmit  Receive   PWM Unusable
// -----          --------  -------   ------------
// Teensy 3.0 & 3.1  21        20         22
// Teensy 2.0         9        10       (none)
// Teensy++ 2.0      25         4       26, 27
// Arduino Uno        9         8         10
// Arduino Leonardo   5        13       (none)
// Arduino Mega      46        48       44, 45
// Wiring-S           5         6          4
// Sanguino          13        14         12

AltSoftSerial altSerial;

void setup() {
    Serial.begin(9600);
    //while (!Serial); // wait for Arduino Serial Monitor to open
    Serial.println("AltSoftSerial Test Begin");
    altSerial.begin(9600);
    altSerial.println("Hello World");
}

void loop() {
    char c;

    if (Serial.available()) {
        c = Serial.read();
        altSerial.print(c);
    }
    if (altSerial.available()) {
        c = altSerial.read();
        Serial.print(c);
    }
}

After uploading the code, I 'looped' pin 9 back to pin 8, and found that when I sent characters to the UNO via the hardware USB port, they showed up again 'echoed' to the serial output after having traversed the AltSoftSerial port 8/9.

So at this point I have solved the UNO 'half' of the problem; the rest is up to you! ;-)


ADXL345 I2C setup not returning anything My hookup is like this:

GND - GND  VCC - 5V  CS - 5V  SDO - GND  SDA - A4  SCL - A5

Here is the code:

#include <Wire.h>
#include <ADXL345.h>

ADXL345 accelerometer;

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

  // Initialize ADXL345
  Serial.println("Initialize ADXL345");

  if (!accelerometer.begin())
  {
    Serial.println("Could not find a valid ADXL345 sensor, check wiring!");
    delay(500);
  }
  if (accelerometer.begin())
  {

  // Values for Free Fall detection
  accelerometer.setFreeFallThreshold(0.35); // Recommended 0.3 - 0.6 g
  accelerometer.setFreeFallDuration(0.1);  // Recommended 0.1 s

  // Select INT 1 for get activities
  accelerometer.useInterrupt(ADXL345_INT1);

  // Check settings
  checkSetup();
  }
}

void checkSetup()
{
  Serial.print("Free Fall Threshold = "); Serial.println(accelerometer.getFreeFallThreshold());
  Serial.print("Free Fall Duration = "); Serial.println(accelerometer.getFreeFallDuration());
}

void loop(void)
{
  delay(50);

  // Read values for activities
  Vector norm = accelerometer.readNormalize();

  // Read activities
  Activites activ = accelerometer.readActivites();

  if (activ.isFreeFall)
  {
    Serial.println("Free Fall Detected!");
  }
}

It comes from this Github link: https://github.com/jarzebski/Arduino-ADXL345/blob/master/ADXL345_free_fall/ADXL345_free_fall.ino

Initially, it would return "Could not find a valid ADXL345 sensor, check wiring!" in serial monitor. After messing with some wiring and changing to SPI
and back to I2C, it only returns "Initialize ADXL345".

I've added the second if() statement because it wouldn't say anything other than "Initialize ADXL345" even with the first if() statement, or with the first if() followed by an else. It should print the Free Fall Threshold and Duration but it hasn't. I have to leave and won't be back until tomorrow, so when I get back I'll try removing the checkSetup() command and maybe put something else in it's place to verify it's working. I feel like the answer is staring me in the face.

EDIT: Okay so after I finally got up from my computer for once, a thought popped into my mind and I figured the reason why checkSetup() isn't returning either string is because it's declared after setup() calls checkSetup()? Am I right? I feel like this would be the case in other languages.

You may have damaged the chip with 5 V already. Sparkfun didn't include a regulator in their breakout. Your pull-ups are also too small; significant current flows when the I2C lines are pulled low. Use two 4.7k or 10k resistors instead. Assuming your Redboard is just like the Uno, connect pin 2 to the INT1 pin of the breakout, to make use of the interrupt capabilities. You also need to call attachInterrupt() and register a handler.

However, you bought this module from Sparkfun, as well as your Redboard. You should first follow their tutorial and library before trying any others. Theirs is SPI-based though. If you must use I2C, try out the Adafruit library.


Arduino to Beaglebone black I have an Arduino uno3 which gets data from a digital caliper and shows the data in serial monitor. Now I should make a connection between this Arduino and my Beaglebone black through SPI to get the data sent from caliper in Beaglebone black. and I don't know what to do and how to create codes related to this purpose.

Have a look at the first several links from googling for Arduino and my Beaglebone black through SPI.  Here are a few comments on those first few links:

• SPI - Beaglebone Black Master Arduino Uno Slave (forum.arduino.cc topic 446924.0) – This page asks your question in more detail, and includes Beaglebone master code and Arduino Slave code.  However, the poster makes an egregious error in the Arduino code by saying Serial.println("SPI"); within the SPI interrupt service routine.

• Communicate Beaglebone Black and Arduino via SPI
(ulasdikme.com) – This page addresses your question in rather more detail, and apparently shows working code.  It also explains how to enable SPI in the Beaglebone device tree.  Note, this poster too makes an egregious error in the Arduino code by saying Serial.println(c); within the SPI interrupt service routine.

• SPI communication: BeagleBone Black (as Master) to 4 Arduinos (as Slaves) (adurthi.com) – This page covers level shifting and device tree setup and provides ok code.  It seems to cover BeagleBone concerns nicely, and has ok Arduino code as well.

One or two of the above also make reference to Nick Gammon's excellent SPI pages:

• SPI - Serial Peripheral Interface - for Arduino (gammon.com.au forum id=10892) – This page is where you should start if you have questions about how SPI works.  After you are familiar with SPI basics, scroll down to the “How to make an SPI slave” heading, and set up the master-slave example with two Arduinos.  When you have that working, you can substitute or add a BeagleBone as master.  Other code examples further down the page include  “How to get a response from a slave”, slave SS pin interrupt examples, SPI via USART, speed settings, SPI on ATtinys, sending data structures, and (under the heading “SPI under IDE 1.6.0 and later”), exegesis of SPI library methods.

• Debugging using SPI/I2C and a second processor (gammon.com.au forum id=11329) – This page illustrates master-slave communication between two Arduinos, using one as a slave to forward information sent from a system being debugged.  Also illustrates use of I2C for similar purpose.  Note, Debugging The Arduino With The SPI Interface Instead Of Serial.println() (utopiamechanicus.com) is a follow-on article, by another author, about this debugging technique.


My counting function is not working with the text on my lcd I want the bottom row of my LCD to display the counting function and include text:

lcd.setCursor(0, 1);
lcd.print("Launch in"millis()/1000);

But it comes out with an error, what part is wrong?

Change the last line to:

lcd.print("Launch in " + (millis() / 1000));

The + concatenates the string Launch in with the number that results from millis() / 1000.


ESP8266 cannot read DHT22 I am trying to build a WiFi humidity and temperature sensor. My board is a nodeMCU using the ESP8266 connected via USB. The board is working fine with various WiFi examples and various serial examples. Hence I guest my environment is OK.

Now I am trying to connect a DHT22 to read temperature and humidity. To reduce the error sources I boiled down my code to the standard DHT example:

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");
  dht.begin();
}

void loop() {
  delay(2000);

  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" *C ");
}

Nevertheless I always get the message "Failed to read from DHT sensor!".

Regarding the hardware I tried connecting the sensor with or without the 10k resistor, tried different DHTs and different pins. To rule out the DHTs I connected them with an Arduino Nano where these are working fine (both with and without resistor and using the same code). The only difference I see is that the Arduino is using 5V while the ESP8266 is using 3.3V - which is nonetheless inside the rating of the DHT.

Any ideas?

I found, that the pin mapping printed at the board of the nodeMCU does NOT match the pin mapping in the library/software.

Check out this issue/solution. It states the correct pin mapping (e.g. pin 2 is "D4" at the board) and provides also an according workaround. My DHT22s are working now... :-)


Arduino Timer0 Piggyback As described here
https://learn.adafruit.com/multi-tasking-the-arduino-part-2/timers

I use timer 0 to get my own timer with a milliseconds resolution.

It is setup like this:

void setup (void)
{
    ...
    cli();
    OCR0A  = 0xAB;
    TIMSK0 |= (1 << OCIE0A);
    sei();
    ...
}

The value 0xAB is chosen randomly and should not affect the behaviour.

The interrupt handler looks like this:

ISR(TIMER0_COMPA_vect)
{
    if (myTimer != 0)
        myTimer--;
    return;
}

This works just OK but having a closer look at the actual timing values using millis() I've found that the timer values given by this ISR are about 2-3% too long.

According to adafruit.com this method should exactly follow the built-in millis() timer of the Arduino.
In my program there are no other interrupts active. There are some Serial.print() outputs, maybe they affect the timing?
The solution I've found looks like this:

ISR(TIMER0_COMPA_vect)
{
    static unsigned long timeLast;

    unsigned long timeNow = millis();
    uint8_t timeDiff = (uint8_t)(timeNow - timeLast);
    timeLast = timeNow;

    if (myTimer != 0)
        myTimer -= timeDiff;

    return;
}

Instead of simply decrementing the timer, the timer value is decreased by the actual amount of time since the last call of the ISR.

With this my timer follows exactly the millis().
But why doesn't the first approach give an exact timing? Apparently there are some cases where the time between calls of the ISR is not 1ms but 2ms.

The Arduino core configures Timer 0 for a period of 1,024 µs. Your
ISR will then be called at very regular intervals, and is a good place
to have timing-related code. You just have to keep in mind that the unit
of time is not one millisecond, but 1.024 ms.

If this “weird” unit bothers you, then you could do what the Arduino
timing ISR does: keep track of how late, relative to a 1 ms
period, you are getting. When you notice you are 1 ms late, count
one extra millisecond.


Problem for control speed of a DC motor with a L298N (Not native english speaker here, feel free to edit my sentences)

I try to control the speed of a DC motor with a L298N shield but it doesn't work very well. Here is my scheme :

The power comes from a transfo with an adjustable voltage of ~7v 1.0 Amp. I don't care about the sens of rotation, so I set IN1 to 5v and IN2 to the ground, is it right to do it like that ?

Now here is the code I'm using :

#define CONTROL_M   9  // To Enable input

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

void loop ()
{
    test_analog_motor();
}

void test_analog_motor()
{
    for (int i; i < 250; i=i+25)
    {
        Serial.println(i);
        analogWrite(CONTROL_M, i); // Any value between 0 and 255
        delay(500);
    }
}

With that code, the speed of my motor should progressively increase and then goes back to 0. I'm aware that, maybe if the value is too low, the motor will have trouble to start so I "help" it manually.

If I doesn't use the Enable output of my Arduino and just use the jumper instead, the motor turns with a good torque. This prooves at least that my shield isn't damaged.

Now here is the problem I have : With the scheme I've shown above, it simply doesn't work, nothing happens when I set the grounds in common, why ? Then if I remove the cable that goes to the arduino ground, it works but the motor has a very low torque, it seems also that there is a kind of latency in regards to what display the Serial monitor.

I feel a bit stupid with what I did with the grounds, it seems wrong t me  but I don't know what to do instead :/ What can I do ? My goal is to have the best possible control of the speed of that DC motor in term of reactivity, does a L298N is suited for that ?

EDIT
I did tested the PWM with an oscilloscope and a multimeter, the arduino PIN I was using worked correctly. I don't know why but now, the shield works too, I mean : Problem solved. One theory is that I adjusted the tension of my power supply under 5V. In that cas the shield doesn't nothing Arduino is magic sometimes...

You do need the ground wire. The reason it 'works' without it is that enable input effectively then has an aerial connected and is responding in the same was as if you touch the input jack on an amplifier and hear a buzzing sound.

There is a link behind the blue connectors that enables the onboard 5v regulator. I assume you have this fitted, or it wouldn't work with the jumper as you describe.

There is a tutorial here : http://www.instructables.com/id/How-to-use-the-L298-Motor-Driver-Module-Arduino-Tu/

I can't see anything different from what you're doing that would cause it to fail, but perhaps you have a problem with pin 9 from your board - you might have damaged it by misconnection, as certain ways of wiring that schematic could put 12V on the arduino pin.  You could also try using pin 13 : the arduino LED should then be lit in sympathy with the PWM signal and you'll know it's working.


MakeyMakey + Arduino I am trying to use the MakeyMakey with the Arduino (not as an Arduino) and then use a USB to TTL module to send the keys pressed to the Arduino. Is this possible? Do I have to reprogram?

one possibility is to use HOST SHIELD
http://www.circuitsathome.com/products-page/arduino-shields

Arduino is now as host
Makey is keyboard