Arduino: Connect UNO to A7 AI Thinker I just cannot connect or send AT command from my UNO to A7 AI Thinker module. This is the connection:

UNO    ->    A7
TX     ->    RX
RX     ->    TX
USB    ||    5V    -> External Power Supply
GND    ->    GND

Without any sketch, I tried to send AT command from serial monitor, and nothing happened.

Different case if I use USB TTL to A7

USB TTL   ->   A7
VCC (5v)  ->   5V
GND       ->   GND
TX        ->   RX
RX        ->   TX

Then it is OK, I can send all AT command, SMS, Call, etc from the serial monitor.

Just what is happening with UNO? Does my UNO RX TX Faulty? How to check it?

Without any sketch, I tried to send AT command from serial monitor, and nothing happened.

The problem is with your connections to the Uno. Although it seems wrong, the correct connection when you're using the Uno as a USB-serial adapter to communicate with the A7 AI Thinker module from Serial Monitor is:

Uno                A7
TX (pin 1)   ->    TX
RX (pin 0)   ->    RX

The RX and TX markings on the Uno refer to the pins on the ATmega328P microcontroller. But you're not using that microcontroller, you're communicating between the USB-serial chip on the Uno and the A7. The RX line of the USB-serial chip is connected to the TX pin of the ATmega328P and thus to pin 1, the TX pin of the USB-serial chip is connected to the RX pin of the ATmega328P and thus to pin 0. For this reason the connection between the Uno and A7 shown above are actually an RX-TX, TX-RX connection between the USB-serial chip and the A7.

If you were communicating between the ATmega328P on your Uno and the A7 then the connections you used would have been correct.


Infra Red sketch "not declared in this scope" I'm pretty new at Arduino and I'm trying to upload a sketch with IR sensor to control LED-s.
I copy the code from internet,download library,I put my infrared codes for TV remote where I want and it says:"not declared in this scope"

Code and error:

#include <IRremote.h>

const int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
const int redPin = 6;
const int greenPin = 9;

void setup(){
  irrecv.enableIRIn();
  irrecv.blink13(true);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
}

void loop(){
    if (irrecv.decode(&results)){

        switch(results.value){
          case E0E036C9: //Keypad button "5"
          digitalWrite(redPin, HIGH);
          delay(2000);
          digitalWrite(redPin, LOW);
          }

        switch(results.value){
          case E0E028D7: //Keypad button "2"
          digitalWrite(greenPin, HIGH);
          delay(2000);
          digitalWrite(greenPin, LOW);
          }

        irrecv.resume();
    }
}

Error:

C:\Users\Kandzija\Desktop\saneta\saneta.ino: In function 'void loop()':
saneta:21: error: 'E0E036C9' was not declared in this scope
           case E0E036C9: //Keypad button "5"
                ^
saneta:28: error: 'E0E028D7' was not declared in this scope
           case E0E028D7: //Keypad button "2"
                ^
exit status 1
'E0E036C9' was not declared in this scope

Can you help me guys pls?
Thank You!

Numeric values in HEX need to be prefixed with 0x:

case 0xE0E036C9: //Keypad button "5"

and

case 0xE0E028D7: //Keypad button "2"


Ethernet shield and IPv6 support Have you heard about support for IPv6 protocol for any Ethernet shield?
As far as I know only IPv4 is supported.
Maybe some one would like to write library?

There is no library, and there physically cannot be one. IPv4 is built into the Ethernet shield itself. (It has a Wiznet 510 chip.)

  Shields based on the MicroChip ENC28J60 chip (such as those sold by Ekitszone and Nuelectronics) are suitable for the implementation of an IPv6 or dual IPv4/IPv6 stack. This approach requires the TCP state machine to be implemented in software and results in more complex arduino code.

Source: this tutorial. (You may find it useful, I'd recommenced reading it.)

There is this library for IPv6 on other hardware, not for the official Ethernet shield.


Hardware interrupt calling two ISRs I've spent three days on this, and either I'm blind to something, or something just ain't right.
Doorbell. Front door switch and back door switch. Two interrupt service routines, one attached to each pin. Rudimentary debouncing in the ISR seems to work.
But for some reason, both interrupt routines are firing off when either of the switches is pressed. I've tried RISING, FALLING, LOW, CHANGE, and it all works the same. I tried INPUT_PULLUP and INPUT_PULLDOWN and changed the polarity on the switches. No change. I've tried different pins, digital, analog. Nothing seems to keep both ISRs from firing.
Pressing front door button, it should print:
front door high
Releasing front door button
front door low
Pressing back door button
back door high
Releasing back door button
back door low
But for some reason, both interrupt service routines are called when pushing either button. Here's what I actually get:
Pressing front door button:
back door low
front door high
Releasing front door button
front door low
Pressing back door button
front door WTF?
back door high
Releasing back door button
front door WTF?
back door low
Here's the code. I hope someone can see something I can't:
#include <Arduino.h>

#define FRONT_DOOR_SWITCH A2
#define BACK_DOOR_SWITCH A3

volatile int frontDoorStatus = 0;
volatile int backDoorStatus = 0;

void frontDoorIsr()
{
    static unsigned long last_interrupt_time = 0;
    unsigned long interrupt_time = millis();
    // If interrupts come faster than 200ms, assume it's a bounce and ignore
    if (interrupt_time - last_interrupt_time > 200) {
        if (digitalRead(FRONT_DOOR_SWITCH) == HIGH) {
            frontDoorStatus = 1;
        }
        else if (digitalRead(FRONT_DOOR_SWITCH) == LOW) {
            frontDoorStatus = 2;
        }
        else {
            frontDoorStatus = -1;
        }
    }
    last_interrupt_time = interrupt_time;
}

void backDoorIsr()
{
    static unsigned long last_interrupt_time = 0;
    unsigned long interrupt_time = millis();
    // If interrupts come faster than 200ms, assume it's a bounce and ignore
    if (interrupt_time - last_interrupt_time > 200) {
        if (digitalRead(BACK_DOOR_SWITCH) == HIGH) {
            backDoorStatus = 1;
        }
        else if (digitalRead(BACK_DOOR_SWITCH) == LOW) {
            backDoorStatus = 2;
        }
        else {
            backDoorStatus = -1;
        }
    }
    last_interrupt_time = interrupt_time;
}

void setup() {
    pinMode(FRONT_DOOR_SWITCH, INPUT_PULLDOWN);
    pinMode(BACK_DOOR_SWITCH, INPUT_PULLDOWN);

    attachInterrupt(digitalPinToInterrupt(FRONT_DOOR_SWITCH), frontDoorIsr, CHANGE);
    attachInterrupt(digitalPinToInterrupt(BACK_DOOR_SWITCH), backDoorIsr, CHANGE);
}

void loop()
{
    switch (frontDoorStatus) {
        case 0:
            break;
        case -1:
            Serial.println("front door WTF?");
            frontDoorStatus = 0;
            break;
        case 1:
            Serial.println("front door high");
            frontDoorStatus = 0;
            break;
        case 2:
            Serial.println("front door low");
            frontDoorStatus = 0;
            break;
    }

    switch (backDoorStatus) {
        case 0:
            break;
        case -1:
            Serial.println("back door WTF?");
            backDoorStatus = 0;
            break;
        case 1:
            Serial.println("back door high");
            backDoorStatus = 0;
            break;
        case 2:
            Serial.println("back door low");
            backDoorStatus = 0;
            break;
    }
}

Board is Adafruit Feather Express M4 (SAMD51)

Turns out that, in the Cortex Mx processors, interrupts don't work the same way as older 8- and 16-bit Arduino-style chips work.
As far as I can tell, there's only one ISR that's connected to the pins. In that routine, you've gotta check the status of the pins you are monitoring and set a global variable accordingly.
I'm not sure this is the only way to do it (seems kludgy), but it does work and it looks like it can scale to any number of pins. I'm using only two.
Here's my demonstration code if anyone is having the same problem. I put the debouncing code in the ISR. I know that's probably not best practice, but it doesn't take a lot of cycles and it's a lot easier than putting it in the loop.
#include <Arduino.h>

#define FRONT_DOOR_SWITCH A2
#define BACK_DOOR_SWITCH A3

volatile bool frontDoor = LOW;
volatile bool backDoor = LOW;

void isr()
{
    static unsigned long last_interrupt_time = 0;
    unsigned long interrupt_time = millis();
    // If interrupts come faster than 200ms, assume it's a bounce and ignore
    if (interrupt_time - last_interrupt_time > 50)
    {
        int fds = digitalRead(FRONT_DOOR_SWITCH);
        int bds = digitalRead(BACK_DOOR_SWITCH);
        if (fds == HIGH) frontDoor = HIGH;
        if (fds == LOW) frontDoor = LOW;
        if (bds == HIGH) backDoor = HIGH;
        if (bds == LOW) backDoor = LOW;
        last_interrupt_time = interrupt_time;
    }
}

void setup()
{
    Serial.begin(115200);
    while (!Serial);
    Serial.println("in setup...");
    pinMode(FRONT_DOOR_SWITCH, INPUT_PULLDOWN);
    pinMode(BACK_DOOR_SWITCH, INPUT_PULLDOWN);

    attachInterrupt(digitalPinToInterrupt(FRONT_DOOR_SWITCH), isr, CHANGE);
    attachInterrupt(digitalPinToInterrupt(BACK_DOOR_SWITCH), isr, CHANGE);
}

bool lastFrontDoor = LOW;
bool lastBackDoor = LOW;

void loop()
{
    if ((frontDoor == HIGH) && (lastFrontDoor == LOW))
    {
        Serial.print("fd+");
        lastFrontDoor = HIGH;
    }
    if ((frontDoor == LOW) && (lastFrontDoor == HIGH))
    {
        Serial.println("fd-");
        lastFrontDoor = LOW;
    }
    if ((backDoor == HIGH) && (lastBackDoor == LOW))
    {
        Serial.print("bd+");
        lastBackDoor = HIGH;
    }
    if ((backDoor == LOW) && (lastBackDoor == HIGH))
    {
        Serial.println("bd-");
        lastBackDoor = LOW;
    }
}


sketch uploading give error? avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x20
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x0f
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x10
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x20

This Instructables post has a list of potential causes for this error. Is this a new board? What board are you using? Is it a genuine Arduino board or a clone? Have you been able to upload to the board previously?


Is an Arduino Uno required to send any sort of command to a NodeMCU? I have an Amica ESP8266 NodeMCU I want to send some commands to. I have tried sending some commands like 'AT' and 'AT+CWLAP' but I do not get any sort of output for any command I send to it.

Actually I did not send commands the first time I bought it. I flashed it with a deauther program made by spacehuhn then I erased the chip using the esptool.py --port /dev/tty.SLAB_USBtoUART erase_flash command multiple times. Then I heard that you can send commands to the NodeMCU using the Serial Monitor using Arduino. So I tried it but no output. So my question is whether I need an Arduino Uno or has the command which I used to erase the factory code of the NodeMCU broken something?

PS. I am a newbie so I don't know much of this stuff.

With erase_flash you deleted the AT firmware from flash. You can load it back with esptool or with Flash Download Tool (Windows only).

AT firmware download page

Addresses for 4 megabyte flash (more in readme.md of AT firmware):

esptool.py -p /dev/tty.SLAB_USBtoUART write_flash 0x0 boot_v1.7.bin 0x01000 at/512+512/user1.1024.new.2.bin 0x3fc000 esp_init_data_default.bin 0xfe000 blank.bin 0x3fe000 blank.bin


Arduino Analog Input Oscillating I'm making a simple Infrared detector using a thermopile. I have a few extra capacitors than what that schematic says. I'm currently following another, but this is the gist.

Schematic and Breadboard-

I can add breadboard picture if needed. I don't have 10 points in this Stack so I can't post more than 2.

I'm using a 9V battery through a 24v - 5v regulator (had one around) to power my op amp and schematic. The signal from the OPAMP will be between 0-5V so voltage hasn't damaged the Arduino Uno. The final project will be something like: output > A then power green, A < output < B power yellow, B < output red.

The issue is that I'm getting an oscillating value from my Serial Monitor that goes from 0 to 1023 (or I have a conversion to change it back to output voltage. So 0V to 5V. See code).

It does this oscillation when I have the board connected to any of the AX pins (X=0-5) or nothing plugged in at all (I understand it will output weird numbers with the pin floating).

I had a picture of the serial monitor but I don't have 10 points to add more than 2 pictures. Please see image below

I know that the output from the OPAMP works because when I use a VoltMeter to read the output, it works fine. 0.3XXV when no flame, 5V when flame is directly on top of my theromopile.

Would anyone happen to have a suggestion to why the Arduino is acting this way? The volt meter reading is directly out of the Op amp pin 1. no more than 2 links. AD822 op amp

Here's my code before adding if statements for the LED's. It was incorrect.

int TP=A2; // Assign Thermopile to pin A2
int val; // Declare readValue Variable
float Voltage; // Declare real world voltage variable - Float = in between variable
int ledG = 11;
int ledY = 12;
int ledR = 13;

void setup() {
 pinMode(TP,INPUT); // Declare Thermopile pin as input
 pinMode(ledG, OUTPUT);
 pinMode(ledR, OUTPUT);
 pinMode(ledY, OUTPUT);
 Serial.begin(9600); // Start your Serial Port
}

void loop() {
  val = analogRead(TP); // Read Thermopile pin and place value into readValue

  Voltage = (5./1023.)*val; // To do "floating point math" have a "." //after the number. If not, it will return real number (5/1023 = 0) according to Arduino

Serial.println(Voltage); // Print readValue to Serial Monitor
  delay(100); // Delayed output to 1/4 a second
}

It seems you haven't connected the circuit ground to the Arduino ground.  This is essential to complete the circuit between your breadboard and the Arduino.  Without the ground connection the electrons that you send to the Arduino have no way of getting back again.
Here's a couple of diagrams that I drew for another question which deals with the Arduino driving a remote device, but the theory holds true no matter which way around it is.

In that diagram the red arrows (not the aerial display team I hasten to add) represent the connection between your breadboard circuit and the Arduino.  Without the ground connection there is no circuit, and a circuit is always needed for current to flow (and hence your signal).  With the ground connection the red arrows become a loop which allows the current to flow and transfer your signal.


NodeMCU ESP8266 button wiring problem Hello guys, this is my code and I am basically doing if-else statement.

int led = D2;
int but = D1;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(but, INPUT);

}

void loop() {
  if (digitalRead(but) == HIGH){
    digitalWrite(led, HIGH);
  }else{
    digitalWrite(led, LOW);
  }

}

I have also attached the photo so that you can diagnose the situation.

The led show only glow if the button is pressed. But the led keeps glowing for longer time and I don't know why.
I think there is current leak somewhere in the circuit or the internal processing is slow.
Please help me guys.

Your button and pull-up configuration is not correct, so when the button is not being pressed, the pin D1 is floating, being pulled neither HIGH nor LOW.

Instead, use a pull-up resistor as shown. When the button is not pressed, D1 is connected to GND through a resistor. When the button is pressed, the 3.3V source has a direct path to D1.

simulate this circuit – Schematic created using CircuitLab


Read and parse continuous serial stream I'm trying to read in and parse a message in the form of X123987 continuously streaming into a serial port. There are no new lines or control characters other than the X which marks the beginning/end of the message. The message contains two, three-character components, ex: 123, and 987. I'm trying to copy bytes as their read into a char array, and then on the control character, return the result, but while this compiles, I don't get any output, and it crashes constantly.

#include <SoftwareSerial.h>

SoftwareSerial RS485Serial(10, 11);

char _byte_received;
char _buffer[10];
char _value[10];

bool OnReceive()
{
  if (RS485Serial.available())
   {
    digitalWrite(13, HIGH);
      _byte_received = RS485Serial.read();
      if (_byte_received == 'X') {
        strcpy(_value, _buffer);
        memset(_buffer, 0, 10);
        return true;
      } else {
        strcat(_buffer, _byte_received);
        return false;
      }
    digitalWrite(13, LOW);
   } else {
    return false;
   }
}
void setup() {
  Serial.begin(9600);
  Serial.println("Restarting...");
  pinMode(13, OUTPUT);
  pinMode(3, OUTPUT);
  digitalWrite(3, LOW);
  RS485Serial.begin(9600);
}

void loop()
{
  if (OnReceive())
  {
    Serial.print("value: ");
    Serial.write(_value);
    Serial.println("");
  }
}

Output:

Restarting...
value:
Restarting...
value:
Restarting...
value:
Restarting...
value:
Restarting...
value:

I expect to see value: 123987

In OnReceive, you are concatening a string with a char. This may be the cause of the resets.

As a side note, you don't really need to use strcat, strcpy and other str functions. You can make your sketch lean by accesing the arrays directly, like this:

char _buffer[10];
int index = 0;

bool OnReceive()
{
  bool status = false;
  if (RS485Serial.available())
  {
    digitalWrite(Pin13LED, HIGH);
    char _byte_received = RS485Serial.read();
    if (_byte_received == 'X') {
      _buffer[index] = 0; // Mark the end of string.
      index = 0;
      status = true;
    } else {
      _buffer[index++] = _byte_received;
      // ToDo: check for overflow;
    }
    digitalWrite(Pin13LED, LOW);
  }

  return status;
}
void setup() {
  Serial.begin(9600);
  Serial.println("Restarting...");
  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Receive);
  RS485Serial.begin(9600);
}

void loop()
{
  if (OnReceive())
  {
    Serial.print("value: ");
    Serial.print(_bufer);
    Serial.println("");
  }


Sending hex data serially and receive it back Below is my code. I want to send the hex data serially to some device and also expecting a reply. I want to see the reply in hex form on a serial monitor. Any comment will be appreciated. Thanks.

const byte numChars = 88;
word receivedChars[numChars]; // an array to store the received data
boolean newData = false;

void setup() {
  Serial.begin(9600);
  Serial.println("<Arduino is ready>");
}

void loop() {
  uint8_t message[] = {0xA5, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x0d };
  Serial.write(message, sizeof(message));
  delay(500);
}

void recvWithEndMarker() {
  static byte ndx = 0;
  char endMarker = '\n';
  word rc;
  while (Serial.available() > 0 && newData == false) {
    rc = Serial.read();
    if (rc != endMarker) {
      receivedChars[ndx] = rc;
      ndx++;
      if (ndx >= numChars) {
        ndx = numChars - 1;
      }
    } else {
      receivedChars[ndx] = '\0'; // terminate the string
      ndx = 0;
      newData = true;
    }
  }
}

void showNewData() {
  if (newData == true) {
    Serial.print("data ");
    Serial.println(receivedChars);
    newData = false;
  }
}

The error I get is call of overloaded println(word [88]) is ambiguous. Thank you for your help.

Here is your code fixed: if you want to send numbers encoded as hex strings that's exactly what you have to do on both ends.
The standard function itoa() is what converts numbers to their string representation, but operating this way you are wasting a lot of resources because to send the number 1 (which can be accomplished by sending exactly one byte) you are sending the string 0x01 (which now requires 4 bytes to be transferred).

const byte numChars = 88;
word receivedChars[numChars];   // an array to store the received data

boolean newData = false;

void setup() {
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
}

void loop() {
    uint8_t message[] = {0xA5, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00, 0x0d };

    char buf[4];
    for (uint8_t i = 0; i < sizeof(message); i++) {
        itoa(message[i], buf, 16));
        Serial.write(buf, sizeof(buf));
    }
    delay(500);

    recvWithEndMarker();
    showNewData();
}

#define END_MARKER '\n'
void recvWithEndMarker() {
    static byte ndx = 0;
    char rc;

    while (Serial.available() > 0 && !newData) {
        rc = Serial.read();

        if (rc != END_MARKER) {
            receivedChars[ndx++] = rc;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        } else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData) {
        Serial.print("data ");
            for (unsigned int i = 0; i < numChars; i++) {
            Serial.print(receivedChars[i], HEX);
        }
        Serial.println();
        newData = false;
    }
}


How to repeat an IF statement My LCD info is called from an IF statement but since it's clock and temperature info i don't want to just show the information but update the information constantly in real time.
i don't want to use (while) loop or any other "code-blocking".

Here's the whole code:

#include <OneWire.h>
#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 2
int Heater= 3;
int Switch1= 4;

Time t;
LiquidCrystal_I2C lcd(0x27, 16, 2);
DS3231  rtc(SDA, SCL);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

// Push button

boolean oldSwitchState = LOW;
boolean newSwitchState = LOW;
boolean lcdScroll = LOW;
boolean lcdBacklight = LOW;
boolean lcdWelcome = LOW;

unsigned long previousMillis = 0;
const long BacklightTime = 10000;

void setup() {
  Serial.begin(115200);
  pinMode(Heater, OUTPUT);
  pinMode(Switch1, INPUT);
  lcd.begin();
  rtc.begin();
}
void loop() {
  float testTemp = sensors.getTempCByIndex(0);
  sensors.requestTemperatures();
  t = rtc.getTime();
  if(lcdWelcome == LOW){
      lcd.setCursor(0,0);
      lcd.print("Welcome, Admin!");
      lcd.setCursor(0,1);
      lcd.print("press Start");
  }

  // LCD
  newSwitchState = digitalRead(Switch1);
    if (millis() - previousMillis >= BacklightTime) {
      lcd.noBacklight();
      lcdBacklight = LOW;
    }
    else if ( lcdBacklight == LOW ){
      lcd.backlight();
      lcdBacklight = HIGH;
    }
    if ( newSwitchState != oldSwitchState ) {
       if ( newSwitchState == HIGH ){
       previousMillis = millis();
       lcdWelcome = HIGH;
       lcd.clear();
      if ( lcdScroll == LOW ){
        lcd.setCursor(0,0);
        lcd.print(testTemp);
        lcd.print("   ");
        lcd.print(rtc.getTimeStr());
        lcdScroll = HIGH;
      }
      else{
        lcd.setCursor(0,0);
        lcd.print(rtc.getDOWStr());
        lcd.print("   ");
        lcd.print(rtc.getDateStr());
        lcdScroll = LOW;
      }
       }
       oldSwitchState = newSwitchState;
    }
}

How can i update the functions inside the if(lcdScroll == LOW){} and else{} statements constantly to show on display?

Like you suggested in your comment, you can implement a state machine, but the simplest would probably be setting a flag bool a_flag in this if(lcdScroll==LOW) clause and checking if(a_flag) in the highest scope of the loop() section. This is where you print("test");.

In respect to your code this will look like:

bool a_flag=false;
void loop() {
  // some irrelevant stuff
  if ( newSwitchState != oldSwitchState) {
    // some stuff
    if ( lcdScroll == LOW ){
      // stuff you would handle here
      a_flag=true;
    }
    else {
      // stuff you would handle here
      a_flag=false;
    }
  }
  if (a_flag) Serial.println("lcdScroll is LOW");
  else Serial.println("lcdScroll is HIGH");
}

Beside this general solution you could simply do the following in your specific case:

loop(){

  // your actual code

  if (lcdScroll) Serial.println("lcdScroll is LOW");
  else Serial.println("lcdScroll is HIGH");
}


nodeMCU - Millis() - Simple Counter - How long is LED on? PROGRESS, now I have this (WITH GREAT HELP):

void setup() {
   Serial.begin(9600);
// initialize digital pin 13 as an output.
}
uint32_t timer_start = 0;
int timer_running = false;

void loop()
 {
// Get LDR information
  int sensorValue = analogRead(A0);         // read the input on analog pin 0
  float voltage = sensorValue * (5.0 / 1023.0);     // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V)
  float lux = voltage * 100;

 if (lux>150) {
    if (!timer_running) {
      // Timer is not already running, so capture the start time
      timer_start = millis();
      timer_running = true;
    }
  } else {
    if (timer_running) {
      // The timer is currently running; stop it calculate/print the run time
      timer_running = false;
      Serial.println((millis()-timer_start) / 1000.0, 3); // format however you like here

    }
  }

 }

This now tells me how many millis the gymnast is in the air, divided by 1000.0 with 3 decimals. If I start the Serial Monitor when the gymnast is in the trampoline bed, then I can get the seconds of air_time the gymnast has. Is there a way to have this script running ONLY for 10 loops?

Declare a global (or static) boolean variable to keep track of whether the timer is running or not, as well as a variable to hold the start millis() value. When the lux drops below your threshold, subtract the current millis() from the start value, and you have the duration in milliseconds, which is trivial to convert to mm:ss.sss format.

Example code (not a complete sketch)

uint32_t timer_start = 0;
uint8_t timer_running = false;

void loop() {
  if (lux>150) {
    if (!timer_running) {
      // Timer is not already running, so capture the start time
      timer_start = millis();
      timer_running = true;
    }
  } else {
    if (timer_running) {
      // The timer is currently running; stop it calculate/print the run time
      timer_running = false;
      Serial.print(millis()-timer_start); // format however you like here
    }
  }
}

  This now tells me how many millis the gymnast is in the air, divided
  by 1000.0 with 3 decimals. If I start the Serial Monitor when the
  gymnast is in the trampoline bed, then I can get the seconds of
  air_time the gymnast has. Is there a way to have this script running
  ONLY for 10 loops?

Certainly. If it is assumed that you want a cumulative total air-time, then you need to declare another global or static variable to hold the cumulative air-time, and you need to have another variable to keep track of how many cycles have passed.

void setup() {
   Serial.begin(9600);
// initialize digital pin 13 as an output.
}
uint32_t timer_start = 0;
int timer_running = false;
uint32_t total_time = 0;
uint8_t jump_count = 0;

void loop()
{
// Get LDR information
  int sensorValue = analogRead(A0);         // read the input on analog pin 0
  float voltage = sensorValue * (5.0 / 1023.0);     // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V)
  float lux = voltage * 100;

  if (jump_count<10) {
    if (lux>150) {
      if (!timer_running) {
        // Timer is not already running, so capture the start time
        timer_start = millis();
        timer_running = true;
      }
    } else {
      if (timer_running) {
        // The timer is currently running; stop it calculate/print the run time
        timer_running = false;
        // Add this-jump air time to the cumulative total:
        total_time += millis()-timer_start;
        // Increment jump_count
        jump_count++;

        Serial.println((millis()-timer_start) / 1000.0, 3); // format however you like here
      }
    }
  } else {
    // Print the total air-time for 10 jumps;
    Serial.println((total_time)) / 1000.0, 3);
  }
}


I2c device disappear from bus after writing I am currently experiencing a really odd I2C problem on a Atmega32u4 based card. I'm trying to use a TLV493D connected by I2C. I know from this thread that before using this device, I have to set the powermode :

Wire.beginTransmission(HallAddressWrite);       // Address the sensor
Wire.write(configReg);              // Address the Configuration register
Wire.write(powerMode);              // Set the Power Mode to Low
errorCode = Wire.endTransmission();             // Stop transmitting

But each time I'm trying to write on the TLV493D register, the device simply disappear from I2C bus ! I know it sounds strange, but I can demonstrate it with a modified version of default I2C scanner

if (error == 0)
{
  Serial.print("I2C device found at address 0x");
  if (address<16)
    Serial.print("0");
  Serial.print(address,HEX);
  Serial.println("  !");

  Serial.println("Beginning write test...");
  Wire.beginTransmission(address);
  // no register writing
  errorCode = Wire.endTransmission();
  Serial.print("Test ended with code : ");
  Serial.println(errorCode);

  Serial.println("SECOND Beginning write test...");

  Wire.beginTransmission(address);       // Address the sensor
  Wire.write(0x00);              // Address the Configuration register
  Wire.write(0x05);            // Set the Power Mode to Low
  errorCode = Wire.endTransmission();
  Serial.print("Test ended with code : ");
  Serial.println(errorCode);

  nDevices++;
}

which gives the output:

I2C device found at address 0x5E  !
Beginning write test...
Test ended with code : 0
SECOND Beginning write test...
Test ended with code : 0

And next scan doesn't find anything. As you can see, I don't lost my device when I don't write anything. But it disappears from my bus as soon as I write something (here, it's for setting low power mode, but any value will do the same).

More informations :

My code is correct. I know that because I don't have any problem when using an Arduino Uno or Arduino Mega. Unfortunately, I don't have an Arduino Leonardo to see if my problem comes from Atmega32u4.
My wiring is correct. I checked the signal on SDA and SCL pin on the TLV493D with an oscilloscope and everything is as expected : 3.3V and 100kHz.
I also have a SRF02 on my I2c bus : it is working as expected.
I don't think my TLV493D is damaged. In deed, I thought it was because of that. So I changed it for another one but the problem is still here.
I noticed than when beginning an I2C transmission at address 0x00, I am able to see my TLV493D again. But it is pointless since I have to set power mode again and thus, it disappears from bus once again.

By default the FAST register is set to 0 at power up.
When the FAST mode is 0 and you set LOW to 0 you are entering Power Down mode.

Looking at your code it looks like you are not altering the FAST register which means I can simplify your question to "Why does my device disappear from the I2C bus every time I turn it off".

Just looking at page 34 of the English User Manual I would say you have to set FAST to 1 before setting LOW to 0.

Also - Do you have pull-up resistors on the I2C bus?  You might encounter problems without them.  They are normally around 4.7K for 5V, but I don't know what they should be for 3.3v systems.


Why is the loop() stopping? I would like to move my servo motor (SM-S2309S) between random angles. In order to do so, I used this simple code:

#include <Servo.h>
Servo servoMain; // Define our Servo

// SM-S2309S angular speed
float speed = 0.12/60;

void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * int(from-to));
}

void setup()
{
   servoMain.attach(10); // servo on digital pin 10
   Serial.begin(115200);
   // move to center as a start
   servoMain.write(90);
   delay(1000);
}

void loop()
{
  // the previous angle, initially set as center (per the setup() call)
  static int oldangle = 90;
  // apparently 15 to 165 deg is a safe range
  int newangle = random(15,165);
  Serial.println(newangle);
  move(oldangle,newangle);
  oldangle = newangle;
}

It starts by placing the arm in the center (in the setup() function) and then should generate a random number (the new angle to go to), in a loop.

What I get is the initial position, then two moves (counterclockwise, then clockwise). The output on the serial console shows 22 and 64, which is consistent with the two moves.

Then everything stops. There is no error message on the console (I do not expect one to be, but I am not sure if there could be any feedback from the Arduino, being a complete beginner). What can be the reason for this stop, after two successful loops?

Just a small mistake! Not much big of a deal :D

In the move function

void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * int(from-to));
}

suppose the values passed are 20, 35 then the last line would be 1000*speed*(-15) Which is negative therefore the arduino delay function converts the - signed bit to a very large unsigned number.

All you have to do is to take the magnitude of from - to ie |from - to | by calling the abs() function.

your move function would look like this:

void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * abs(int(from-to)));
}

Just alter your move function or copy mine and you'll have no problem at all!


Can't power mg2639 cellular shield with battery I have a SparkFun MG2639 cellular shield attached to an Arduino Uno R3.  I have had both the cell modem and the GPS unit working when the shield is powered from the Uno.  I followed the instructions on SparkFun's site to switch the shield to be powered by battery (cut SJ2, short SJ3) and connected a fully charged Li-ion battery.  I measure over 4.1 volts at the battery connection pads on the shield but the power LED isn't on and the shield isn't responding.  It looks as though it's not getting any power.  I also powered it from my bench supply with 5V and it shows no current draw.

Did I miss something in the conversion instructions?

Turns out the soldered short of SJ3 was not complete.  After resoldering the shield powers up as expected.


Serial Port greyed out Ubuntu 16.04 I am running Ubuntu Mate 16.04 LTS, with an Arduino Uno R3 clone. I am having the dreaded serial port graying out problem, and have not found a solution for fixing it. Currently, The serial port will grey out sometimes, and sometimes it will be not grayed out, and I can see that I have selected ttyUSB0. Usually when it is not grayed out, uploading a sketch will not work, and I get the error like it is grayed out:

  avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory
  An error occurred while uploading the sketch

chmod a+rw /dev/ttyUSB0

doesn't solve the issue, with log out included

gpasswd -a aaron dialout

doesn't solve the issue, with log out included

I searched preferences.txt and serial.debug rate is set to 9600

I have tried entering preferences.txt and deleting all of the serial entries. They are recreated the same after deletion, and this doesn't solve anything.

I tried running as sudo, doesn't work.

I tried solving this originally on Arduino IDE 1.0, didn't work.

I have upgraded to Arduino IDE 1.6.10, still not working.

running lsusb in terminal yields this while Arduino is plugged in:

Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0a5c:21e6 Broadcom Corp. BCM20702 Bluetooth 4.0 [ThinkPad]
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Checking var/log/syslog after plugging in Arduino:

  kernel: [42043.787178] usb 3-2: new full-speed USB device number 109 using xhci_hcd

  kernel: [42043.916241] usb 3-2: New USB device found, idVendor=1a86, idProduct=7523

  kernel: [42043.916249] usb 3-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0

  kernel: [42043.916253] usb 3-2: Product: USB2.0-Serial

  kernel: [42043.916964] ch341 3-2:1.0: ch341-uart converter detected

  kernel: [42043.918199] usb 3-2: ch341-uart converter now attached to ttyUSB0

  mtp-probe: checking bus 3, device 109: "/sys/devices/pci0000:00/0000:00:14.0
  /usb3/3-2"

  mtp-probe: bus: 3, device: 109 was not an MTP device

Ran to add to dialout group, then logged out

sudo usermod -a -G dialout aaron

No solution.
So it looks like Arduino board is not being recognized. Not sure what to try next. It is important that I have uploaded sketches before, but am not sure if there is a pattern to when it does not work. It does not work 95% of the time.

Thanks for the help!

I have the same problem,
I believe that the problem is related to the 4.x kernel, since I have already tried another distribution with the kernel mermo and the problem persists. Using a windows virtual machine as guest works, which excludes communications and hardware issues.


MG2639 & Arduino Uno not GPS-ing? is there any way I can run an MG2639 GPS Cellular Shield (the one SparkFun makes) on an Arduino Uno for GPS tracking purposes? It seems whether I use New or AltSoftSerial, the unit just can’t read what’s streaming in through from the GPS on the 115200 baud rate, which the shield is hard-wired to.

Try sending a command that sets the GPS baud rate to something a little lower:

altss.write( F("$PMTK251,38400*27\r\n") );
altss.end();
altss.begin( 38400 ); // change to match above command

Are you sure you're having trouble reading, because there are many other things you may be doing in your sketch that cause input buffer overflow.  Please post your code and some sample output for us to examine.  It may be failing for a different reason.

For example, you may just be losing data because you're trying to do too many things in loop().  Please take a look here.

To solve this kind of problem, I have posted a modified version of AltSoftSerial on github, here, that let you process GPS data in the background (i.e., during interrupts).  When coupled with NeoGPS, it can save you quite a bit of program space, RAM and execution time.  There is an interrupt-driven example here.  Just change which include is uncommented on lines 30-31:

#else
  // Only one serial port is available, uncomment one of the following:
  #include <NeoICSerial.h>
  //#include <NeoSWSerial.h>
#endif
#include "GPSport.h"

...and the baud rate below, on line 140:

  // Start the UART for the GPS device
  gps_port.attachInterrupt( GPSisr );
  gps_port.begin( 115200 );
}


Triggering an SPI transfer with an interrupt in Arduino Due I have a DDS that is controlled by an Arduino DUE,  loop() waits for Serial commands and based on them calls one or another function that sets the DDS's frequency, phase, amplitude etc via SPI. In addition to that I want to be able to use an external interrupt triggered by a TTL signal to reset the DDS's phase accumulator. The phase reset is done by writing an SPI register - resetPhase().

Somehow the resetPhase() is triggered correctly, but as soon as I add a SPI.transfer to it the SPI communication stops working altogether, not just through interrupts, but also the functions triggered via serial commands stop working.

Is there a way to get it to work?

SPISettings spiSettings = SPISettings(10000000, MSBFIRST, SPI_MODE0);

void setup()
{
    pinmode(chipSelect, OUTPUT);
    int syncPIN = digitalPinToInterrupt( interruptPin);
    SPI.usingInterrupt(syncPIN);
    attachInterrupt(syncPIN, resetPhase, RISING);
}

void resetPhase():
{
    SPI.beginTransaction(spiSettings);
    digitalWrite(chipSelect, LOW);
    SPI.transfer(controlRegister);
    digitalWrite(chipSelect, HIGH);
    SPI.endTransaction();
}

In general, it's best to do as little as possible in your interrupt service routine (ISR).

resetPhase is your ISR here, and typically it would set a flag or semaphore to signal lower priority code that certain work needs to be done and, in this case, probably nothing more. Then your loop code on noticing the flag is set would clear the flag and do its work.

I imagine the library authors thought SPI.usingInterrupt would ease use of SPI, but performing I/O in an ISR seems a bit contrary to best practices. These concerns are echoed here, along with some other caveats regarding interrupts and ISRs. Possibly not the answer you're looking for, but I hope it helps.


I²C with ATTiny85 at 8MHz using TinyWireM library Hello fellow Arduino enthusiasts, I am trying to make the ATTiny85 talk I²C with a MMA7660 breakout board I have (it's an accelerometer, this is a follow up question to my previous one).

I would state in advance that the I²C chip works perfectly with Arduino Nano, that I am using the Arduino IDE v1.5.6-r2, using the arduino-tiny core (from here) and that until now I had no special issues working at 8MHz.

The official documentation for the TinyWireM library (at the Arduino playground website) states that:

  By default the I2C master library (TinyWireM) is set to run at 1MHz.
  To run at 8MHz, #defines in USI_TWI_Master.h / .cpp must be changed.

I have made the following changes in USI_TWI_Master.cpp:

#define F_CPU 8000000UL // was 1000000UL

I have made the following changes in USI_TWI_Master.h:

#define SYS_CLK   8000.0 // was 1000.0
#define T2_TWI    1.3 // was 5
#define T4_TWI    0.6 // was 4

My guess is that the T2_TWI & the T4_TWI values are wrong. I also tried T2_TWI 40 and T4_TWI 32 (as stated here), and T2_TWI 2 & T4_TWI 1 (as stated here) but no luck. I also tried some other values in between that I thought might make sense but it won't work.

The code I am running is the I²C scanner from here (which as I mentioned works perfectly with the Nano and finds the device), the blow is a modified version for interfacing the TinyWireM library instead of the Wire library:

#include <TinyWireM.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(-1,4);

void setup()
{
  TinyWireM.begin();
  mySerial.begin(9600);
  mySerial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;
  mySerial.println("Scanning...");
  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    TinyWireM.beginTransmission(address);
    error = TinyWireM.endTransmission();

    if (error == 0)
    {
      mySerial.print("I2C device found at address 0x");
      if (address<16)
        mySerial.print("0");
      mySerial.print(address,HEX);
      mySerial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      mySerial.print("Unknow error at address 0x");
      if (address<16)
        mySerial.print("0");
      mySerial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    mySerial.println("No I2C devices found\n");
  else
    mySerial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}

As a side note I would say that my logic analyzer was broken recently and I'm sure it would have helped here... Also I am aware of the sound-card hack to be used as logic analyzer, but would prefer to avoid adding more error-prone variables to the system, if possible, for now.

Here is a picture of probing with Saleae logic analyzer of the two channels. The result of the code above is "No I2C devices found":

(Full size picture)

Would appreciate the insights of anyone with experience using ATTiny85 at 8Mhz with I²C successfully.

You really just need to scope the signals, even if it's with a DSO Nano-type scope.

Without downloading the datasheets:

I would guess your pull-up is probably too small, but possibly too large (scope it)
Slew rate may be either insufficient or too steep (scope it)
Be aware that the ATTiny runs at "8MHz", and not 8.00MHz. The timing error can be off enough to cause communication issues at high speeds while working well at lower speeds (scope it, and/or start at default and incrementally increase speed by 0.5MHz until it stops working)
MMA may not support a typical protocol feature being used, i.e. 'repeated start', burst transfers, etc. (datasheet register/programming section)

Edit: Both the ATTiny and the MMA should have bypass capacitors near the power pins.


Creating date string for error log Well, googling didn't do much to help me here and I'm shocked that something I can do in two lines of code in C#

DateTime dateTime;
string text = dateTime.ToLongDateString();

is this difficult for Arduino, but how do you get a string version of a date time stamp?

I want the current date and time as a string in this format

  May 4, 2016 17:15:33

Since I can't use any of the C++ includes, like ctime, I'm not sure how to accomplish this.

You need additional hardware like a RTC for example an DS1307 or on the other hand an arduino/shield with ethernet or wifi so you could get the time by NTP another option might be DCF77 time via the air - sorry forgot GPS could also be used to get the time .... the rest then should be simple creating a string.


Problem “Didn't find PN53x board” Arduino NFC Card Reader i am using the elechouse PN532 RFID Module with an Wemos D1 mini in the Arduino IDE.
I use the ISO1443a_uid example from the elechouse library. All works fine if i plug the USB Cable into the wemos and the demo runs. But if i press the reset button on the Wemos D1 mini then the Serial brings this output:

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v0fd86a07
~ld
Hello!
Didn't find PN53x board

Sometimes it works fine but mostly comes this error.

Here is the sample code (i am using the I2C Mode):

* When the number after #if set as 1, it will be switch to SPI Mode*/
if 0
 #include <SPI.h>
 #include <PN532_SPI.h>
 #include "PN532.h"

 PN532_SPI pn532spi(SPI, 10);
 PN532 nfc(pn532spi);

* When the number after #elif set as 1, it will be switch to HSU Mode*/
elif 0
 #include <PN532_HSU.h>
 #include <PN532.h>

 PN532_HSU pn532hsu(Serial1);
 PN532 nfc(pn532hsu);

* When the number after #if & #elif set as 0, it will be switch to I2C Mode*/
else
 #include <Wire.h>
 #include <PN532_I2C.h>
 #include <PN532.h>
 #include <NfcAdapter.h>

 PN532_I2C pn532i2c(Wire);
 PN532 nfc(pn532i2c);
endif

oid setup(void) {
 Serial.begin(115200);
 Serial.println("Hello!");
 pinMode(D2,INPUT_PULLUP);
 pinMode(D1,INPUT_PULLUP);
 nfc.begin();

 uint32_t versiondata = nfc.getFirmwareVersion();
 if (! versiondata) {
   Serial.print("Didn't find PN53x board");
   while (1); // halt
 }

 // Got ok data, print it out!
 Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
 Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
 Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

 // Set the max number of retry attempts to read from a card
 // This prevents us from waiting forever for a card, which is
 // the default behaviour of the PN532.
 nfc.setPassiveActivationRetries(0xFF);

 // configure board to read RFID tags
 nfc.SAMConfig();

 Serial.println("Waiting for an ISO14443A card");

oid loop(void) {
 boolean success;
 uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
 uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

 // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
 // 'uid' will be populated with the UID, and uidLength will indicate
 // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
 success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);

 if (success) {
   Serial.println("Found a card!");
   Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
   Serial.print("UID Value: ");
   for (uint8_t i=0; i < uidLength; i++)
   {
     Serial.print(" 0x");Serial.print(uid[i], HEX);
   }
   Serial.println("");
   // Wait 1 second before continuing
   delay(1000);
 }
 else
 {
   // PN532 probably timed out waiting for a card
   Serial.println("Timed out waiting for a card");
 }

What is wrong? why is it not alltimes working after a reset?

EDIT:
Try using Elechouse library, it worked better for me.

This might be irrelevant, but I wanted to share.

I had a similar issue, not related to the sketch code.

So make sure:

Connect wires to the NFC module at 90 degrees - there should be angular headers included. Also the wires should be above the antenna - the white strip.
There shouldn't be any wires underneath the NFC module or they should on significant distance.
Soldered wires work better on the NFC module.


timer0_millis always returns 0 I am trying to make a simple debounce function as explained here but the condition if((millis()-timeCheck)>reboundDelay) is never met.

As you can see in my code below, I am trying to control a PWM with two push buttons. I am currently sending it on a LED.

With AS7 and vMicro I put some breakpoints and realized that timeCheck was stuck at 0 and was an unsigned int instead of the unsigned long I declared. With the debugger I looked inside of the millis() function and saw that timer0_millis wasn't increasing neither, stuck at 0.

Here is my short code (it's a sketch, it can surely be rewritten in a more efficient way) :

int PWM=9;
int dutyP=2;
int dutyM=3;
int duty=123;
bool stateP=0;
bool stateM=0;
bool prevStateP=0;
bool prevStateM=0;
unsigned long reboundDelay=500;
unsigned long timeCheck=millis();

void setup() {
  pinMode(PWM,OUTPUT);
  pinMode(dutyP,INPUT);
  pinMode(dutyM,INPUT);
}

void loop() {
  stateP=digitalRead(dutyP);
  stateM=digitalRead(dutyM);
  if(stateP != prevStateP || stateM != prevStateM) {
    timeCheck=millis();
  }
  if((millis() -  timeCheck) > reboundDelay) {
    if(stateP==1) {
      duty=duty+25;
    } else if(stateM==1) {
      duty=duty-25;
    }
    analogWrite(PWM,duty);
    prevStateP=stateP;
    prevStateM=stateM;
  }
}

And finally, the strange part. When I upload it on my Genuino Uno for like 30 seconds, the pushbuttons do nothing (it may be that the if works) and afterwards I can increase and decrease the duty cycle but without the delay that the condition should bring (the LED flashes really fast due to an overflow in analogWrite).

Any help is welcomed, the strange part is secondary to me but I would really like to make millis() work properly.

I would suggest a few things:

1) comment on your code -> lay out the basic logic so that you and others can help you debug it;

2) use brackets liberally -> don't rely on memory (=faulty) on the order of operations. instead, define it explicitly;

3) check your logic -> make sure that your code does what you want it to do;

4) pay attention to data type: 8-bit vs. 16-bit, etc.

5) modularize your code -> this allows more efficient debugging and code reusing.

for example, your code can be simply described as

  button_state = read_button(); //read button state, with debouncing
  if (button_state = BUTTON_UP) pwminc_dc(pwm_dc); //increase duty cycle, with boundary checking
  if (button_state = BUTTON_DOWN) pwmdec_dc(pwm_dc); //decrement duty cycle, with boundary checking

with the code modularized, you just need to worry about getting individual pieces right.


What if I just connect 5V DC to my UTP? Here is the image of Ethernet shield near RJ45 socket:

These small boxes are probably SMD capacitors which may mean, that internal board is glavanically disconnected from the UTP line.

Is this true?

If this is true, then what will happen, if I pass 5V DC current just into my UTP? Won't I be able to wire appropriate conductors just into Arduino power input? Won't I be able to power Arduino this way?

The question is about not using premade PoE splitter. I have an injector, which injects 5V into line.

UPDATE

I found my injector put power to lines 4,5 and GND to 7,8. Can I take this power on Arduino side?

Not exactly. That RJ45 connector labeled HR911105A is internally connected like this:

It's possible with PoE version (but I suppose not with 5V but more like 12V or so)

Or there are variants without PoE module connected but with support, that should be possible to use 5V if you wire it correctly)

Or you can use external PoE injector and extractor:

For 100Mb networks are two unused communication pairs used as power lines:


Arduino Robot. a function-definition is not allowed here before '{' token The code is very messy. We have an L293D circuit which has two enable pins always on. We also have an LDR light sensor with two light resistors, one on the left and one on the right.

We are trying to make a line following robot

We are ambitious high school students.

// Use this code to test your motor with the Arduino board:

// if you need PWM, just use the PWM outputs on the Arduino
// and instead of digitalWrite, you should use the digitalWrite command

// --------------------------------------------------------------------------- Setup
void setup() {
{Serial.begin(9600);

// --------------------------------------------------------------------------- Motors
int motor_left[] = {2, 7};
int motor_right[] = {10, 15};
int LDR = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDRValue = 0;      //that’s a variable to store LDR values
int light_sensitivity = 500;    //This is the approx value of light surrounding your LDR
int LDR2 = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDR2Value = 0;      //that’s a variable to store LDR values
int light_sensitivity2 = 500;    //This is the approx value of light surrounding your LDR
int i;
for(i = 0; i < 2; i++){
pinMode(motor_left[i], OUTPUT);
pinMode(motor_right[i], OUTPUT);
LDRValue = analogRead(LDR);
    Serial.println(LDRValue);

    if (LDRValue < light_sensitivity);
    Serial.println("wat");

}
// --------------------------------------------------------------------------- Loop

// --------------------------------------------------------------------------- Drive

void motor_stop(){
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], LOW);

digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], LOW);
delay(25);
}

void drive_forward(){
digitalWrite(motor_left[0], HIGH);
digitalWrite(motor_left[1], LOW);

digitalWrite(motor_right[0], HIGH);
digitalWrite(motor_right[1], LOW);
}

void drive_backward(){
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], HIGH);

digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], HIGH);
}

void turn_left(){
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], HIGH);

digitalWrite(motor_right[0], HIGH);
digitalWrite(motor_right[1], LOW);
}

void turn_right(){
digitalWrite(motor_left[0], HIGH);
digitalWrite(motor_left[1], LOW);

digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], HIGH);
}
void loop() {
drive_forward();
delay(1000);
motor_stop();
Serial.println("1");

drive_backward();
delay(1000);
motor_stop();
Serial.println("2");

turn_left();
delay(1000);
motor_stop();
Serial.println("3");

turn_right();
delay(1000);
motor_stop();
Serial.println("4");

motor_stop();
delay(1000);
motor_stop();
Serial.println("5");
}

You need to look more closely at your braces. Use the auto-format tool (Ctrl+T) to help you. For example:

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

// --------------------------------------------------------------------------- Motors
int motor_left[] = {2, 7};
int motor_right[] = {10, 15};
int LDR = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDRValue = 0;      //that’s a variable to store LDR values
int light_sensitivity = 500;    //This is the approx value of light surrounding your LDR
int LDR2 = 0;     //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDR2Value = 0;      //that’s a variable to store LDR values
int light_sensitivity2 = 500;    //This is the approx value of light surrounding your LDR
int i;
for(i = 0; i < 2; i++){
pinMode(motor_left[i], OUTPUT);
pinMode(motor_right[i], OUTPUT);
LDRValue = analogRead(LDR);
    Serial.println(LDRValue);

    if (LDRValue < light_sensitivity);
    Serial.println("wat");

}   // <------------------------------------ HERE

// --------------------------------------------------------------------------- Loop

// --------------------------------------------------------------------------- Drive

void motor_stop(){

Where I marked "HERE" you are closing the for loop but you should also be closing setup.

You also have two opening braces here:

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

Proper indentation is very helpful for sorting out these sorts of issues.


How to you initialize a reset on a sht30 digital thermometer? I have a sht30 that will output correct temperature readings for about 5 min and then will drift off.
So I'm trying to hit the reset every few seconds to keep the readings accurate.
I am on a nano connecting d4 to the sht30 reset pin, but I don't appear to be resetting. My temp still drifts.
How do you correctly hit the reset on a sht30?
code:
#include <Wire.h>

// SHT31 I2C address is 0x44(68)
#define Addr 0x45

int reset_pin = 3; // reset pin is set to d4 on board.
int counter = 0; //reset counter

void setup()
{
  // Initialise I2C communication as MASTER
  Wire.begin();
  // Initialise serial communication, set baud rate = 9600
  Serial.begin(115200);
  delay(300);
}

void loop()
{
  unsigned int data[6];

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Send 16-bit command byte
  Wire.write(0x2C);
  Wire.write(0x06);
  // Stop I2C transmission
  Wire.endTransmission();
  delay(300);

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Stop I2C Transmission
  Wire.endTransmission();

  // Request 6 bytes of data
  Wire.requestFrom(Addr, 6);

  // Read 6 bytes of data
  // temp msb, temp lsb, temp crc, hum msb, hum lsb, hum crc
  if (Wire.available() == 6)
  {
    data[0] = Wire.read();
    data[1] = Wire.read();
    data[2] = Wire.read();
    data[3] = Wire.read();
    data[4] = Wire.read();
    data[5] = Wire.read();
  }
  // Convert the data
  int temp = (data[0] * 256) + data[1];
  float cTemp = -45.0 + (175.0 * temp / 65535.0);
  float fTemp = (cTemp * 1.8) + 32.0;
  float humidity = (100.0 * ((data[3] * 256.0) + data[4])) / 65535.0;

  // Output data to serial monitor
  Serial.print("Temperature in Celsius :");
  Serial.print(cTemp);
  Serial.println(" C");
  Serial.print("Temperature in Fahrenheit :");
  Serial.print(fTemp);
  Serial.println(" F");
  Serial.print("Relative Humidity :");
  Serial.print(humidity);
  Serial.println(" %RH");
  delay(500);
  if(counter == 25){
    digitalWrite(reset_pin, HIGH); // sets the digital pin 13 on
    delay(1000);            // waits for a second
    digitalWrite(reset_pin, LOW);  // sets the digital pin 13 off
    delay(1000);
    counter  = 0;

  }
  counter++;
  Serial.println(counter);
}

You need to give a brief LOW pulse, not a long HIGH pulse:
In setup:
pinMode(reset_pin, OUTPUT);
digitalWrite(reset_pin, HIGH);

When you want to reset:
digitalWrite(pin_reset, LOW);
delay(1);
digitalWrite(pin_reset, HIGH);


Failed to read DHT22 sensor using Arduino Uno why do I end up with the display "Failed to read from DHT sensor!" in the serial monitor in most cases when I run the code given below?? In case I reduce the delay to 1000ms the reading shows 0.00 for both temperature and humidity which, as well, is pretty much false......Any help would be highly appreciated...

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
// might need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// Example to initialize DHT sensor for Arduino Due:
//DHT dht(DHTPIN, DHTTYPE, 30);

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

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(f, h);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hi);
  Serial.println(" *F");
}

I suggest you to modify the following lines of code to check which reading has issue.

if (isnan(h) || isnan(t) || isnan(f)) {
   Serial.println("Failed to read from DHT sensor!");
   return;
}


Why my LCD does not work with this if statement? #include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);
int greenLedPin = 12;
int blueLedPin = 11;
int redLedPin = 8;
int yellowLEdPin = 9;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  // put your setup code here, to run once:
  lcd.begin(16, 2);
  pinMode(greenLedPin, OUTPUT);
  pinMode(blueLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);
  pinMode(yellowLEdPin, OUTPUT);
  Serial.begin(9600);
  while (! Serial);

}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(analogRead(lightSensorPin));
  analogValue = analogRead(lightSensorPin);
  if (analogValue < 50) {

digitalWrite(redLedPin, HIGH);

  }
  else if (analogValue >= 50 && analogValue <= 99) {
    digitalWrite(yellowLEdPin, HIGH);
  }
  else if (analogValue >= 100 && analogValue <= 300) {

    digitalWrite(blueLedPin, HIGH);
    lcd.print("its bright");
 }
  else {
      digitalWrite(greenLedPin, HIGH);
      lcd.print("its bright");
      }

  delay(3000);
  digitalWrite(greenLedPin, LOW);
  digitalWrite(blueLedPin, LOW);
  digitalWrite(redLedPin, LOW);
  digitalWrite(yellowLEdPin, LOW);
  lcd.clear();

}

I'm very new to this so sorry if its a dumb mistake and I know my LCD is working right, since I have tested it so all the pins are good.

On the Uno, pin 0 and 1 are used for Serial. You can't use pin 1 for Serial in addition to the LCD. In general, it's best to avoid using pins 0 and 1.

You need to change the LCD wiring to use a different pin and update the code accordingly. For example, if you moved the LCD's RS pin connection from pin 1 on your Arduino to pin 13, you would update this line from:

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

to:

LiquidCrystal lcd(13, 2, 4, 5, 6, 7);

After that, your LCD should work correctly.


Is the SIM900 3G? Or is the SIM900A able to connect to 3G? I would like to state that I am not familiar with the whole cellular connection thing. But I was wondering if the SIM900/or/SIM900A is 3G and will work with PTel Mobile.

I need this Arduino to be able to travel and needs to connect to every PTel's tower. Will I be able to connect to 3G or only the 2G and the 1G networks?

First of all if you are in USA you cannot use SIM 900A since it supports only Dual frequency bands.(900,1800 MHz)it supports only Asian region countries.

According to Wikipedia, PTel Mobile supports only GSM 850/1900 frequencies.
so SIM 900 supports( 850,900,1800,1900 MHz ) you must use SIM900

Considering about the speed you cannot obtain 3g, 4g speed since GSM Shield(SIM900) provides maximum of GPRS class 10: max. 85.6 kbps (downlink) so,

It will able to connect but cannot get such speed in 3g and 4g.


Grounding for arduino, measuring phase controllled 240V I would like to measure a phase controlled 240Vac waveform as a digital PWM input for an arduino. The signal would look something like this:

My intent was to use a zener clipping circuit to limit the positive portion of the waveform to 5V, and measure that signal. However, I want to make sure I'm properly grounding these items. This is what my proposed circuit looks like, with all components inside a metal chassis.

I feel like ideally I would isolate this waveform from the system controller/light with a 1:1 transformer, but I'm unsure if that is feasible given its irregularity. Can I safely connect the arduino ground to the system's neutral, or am I barking up the wrong tree?

Thanks!

your circuit will work, and can be simplified a little bit further. But it will work.

it is safer to use isolation, however. there are multiple ways to go about doing it.

the key here is to detect zero crossing, and start counting from there.


ESP - Nodemcu amica - attachInterrupt crash program I get new boards from the shop but they are little different from the previous version. I got software what works ok on Nodemcu lolin v3 now I get Nodemcu Amica what is almost same board but if I got attachInterrupt function in the program it crashes immediately.

    attachInterrupt(6, bowlingCall, RISING);
//attachInterrupt(digitalPinToInterrupt(D1), statekCall, RISING);

I try different pins but not change. I debug all program(comment all out and left just attachInterrupt and it crashes again).

    ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld

The board cycle in the reboot sequence, even serial output do not work ok. Why did esp crash at attachInterupt on this board?

thanks @Juraj.

Ok, so all you need is rewrite all your interrupt function.
For example:

void getStatusFromMaster()

to

void ICACHE_RAM_ATTR getStatusFromMaster()


How do I get the size of my program at runtime? (This question is specific for the Arduino Due, but maybe there's a general answer to the question)
I'm using DueFlashStorage to store application data in the flash memory of my Arduino Due. That works quite nicely. The Due has two flash blocks with 256k each. By default, the library writes data to the second flash block. The first flash block is used for the program. My program currently uses around 160k of flash (as the compiler tells me). That leaves about 96k of flash unused, which I could really use to store more application data. I managed to adjust DueFlashStorage to allow writing to the full memory range, but how do I detect where it is safe to write to? (Obviously, I must not overwrite any part of the program)
I have tried something like:
  // this returns the logical address of the first byte in flash (0x80000)
  byte* startAddr = dueFlashStorage.readAddress(0);
  Serial.println((unsigned int)startAddr, HEX);
  int bytes = 0;
  while (bytes < 512 * 1024) // That's the size of the flash
  {
    int* data = (int*)(startAddr + bytes);
    if (*data == 0xFFFFFFFF) // empty flash is initialized with FF's
     {
       Serial.print("Free block at 0x");
       Serial.println((unsigned int)data, HEX);
     }
     else
     {
       Serial.print("Used block at 0x");
       Serial.println((unsigned int)data, HEX);
     }
    bytes+=512;
  }

This seems to work, as the first block detected as "free" is just above the size of the program. However, this approach has some major drawbacks:

It's slow. Running over the whole address space to find the end of the program uses time (and maybe I shouldn't just test the first word of each block)
It's not reproducible. After I have written data to the detected first free block, it's no longer free, so I need another approach (like some magic number) to detect the first data block after the CPU is reset.

Is there a better way for this (like, in the ideal world, a constant I could use)? I don't want to hardcode the data start, because as the program grows (and it's still in development) I would forget to adjust that constant and booooommmm....

Just to warn you, I minimally tested this, but it seems to work.
In the Due's linker script there are these relevant lines, containing the named rom section.
MEMORY
{
    rom (rx)    : ORIGIN = 0x00080000, LENGTH = 0x00080000 /* Flash, 512K */

Below you'll see:
SECTIONS
{
    .text :
    {
        . = ALIGN(4);
        _sfixed = .;

_sfixed is a symbol they've created to mark the current location, which happens to be the start of the rom section in this case, 0x00080000.  At the bettom of the brace matching the one following .text, you'll see:
} > rom

showing that section goes into ROM, which is why . at the beginning of the .text section refers to the rom section start address.
If you look near the last thing placed in rom, you'll see:
    . = ALIGN(4);
    _etext = .;

So, they've set another symbol there, the one of interest, _etext, the address of which should be the byte of ROM not used, or so I thought the first time through this; turns out it isn't.  I gather you have no use for start of ROM symbol, since it's a static value and at the beginning, so I'll ignore that, but if you cared to make use of it it could be done the same way as follows for _etext.
These symbols don't have any type, but you can make them whatever you want.  If you want to perform arithmetic on a pointer that results, it makes sense to use a char type, so:
extern "C" unsigned char _etext;

I thought this was the end of the story, could just take the address of this symbol, but there is more to it.  Following the regular code is this section:
    .relocate : AT (_etext)
    {
        . = ALIGN(4);
        _srelocate = .;
        *(.ramfunc .ramfunc.*);
        *(.data .data.*);
        . = ALIGN(4);
        _erelocate = .;
    } > ram

They're placing code for the banzai (reset) function (and perhaps other things), which goes into ram ultimately, at this location in ROM.  So, presumably in the start code this is copied from the end of the normal program code into some place in ram.
So, there are two more symbols of interest here, _srelocate and _erelocate.  Declarations for them:
extern "C" unsigned char _srelocate;
extern "C" unsigned char _erelocate;

These symbols resolve to addresses in RAM, so they can't be used directly, but can have their addresses subtracted to get the size of the image in ROM that gets relocated to RAM, leading to:
const unsigned char *rom_end = &_etext + (&_erelocate - &_srelocate);
Serial.print("The end of used ROM is : 0x");
Serial.println((uintptr_t)rom_end, HEX);

When I compile and run a simple test like this and check the serial monitor connection, I see output like:
The end of used ROM is : 0x82FF8

If look at the .bin file produced by the compiler:
$ wc --bytes  build/arduino.sam.arduino_due_x_dbg/efixed.ino.bin
12280 build/arduino.sam.arduino_due_x_dbg/efixed.ino.bin

And 0x82FF8 - 0x80000 == 12280.
When I hex dump flash around this address I can see what looks like it padding out the flash sector with 0x00 bytes before the next unprogrammed flash sector shows as 0xFF.  So you would need to round this up yourself, and if you want be somewhat safer, maybe add some margin.
I don't know how common that configuration in the linker script is.  It's likely that most linker scripts place a symbol there, if they've had some forethought.  But I wouldn't necessarily expect it have the same name.  It's possible they modify it to add more stuff after that symbol.  But for now, for the Due, that would seem to work fine.  It is a bit messy though.


Is it common that Uno clones misbehave when connected to 12v on VIN? Edit: this was completely my mistake. See end.

My official Uno worked fine when powered by 12v on VIN, but my Uno clone acted really funny--it read random noise from an input when a simple wire was attached, but not with no wire. It was solved with a pulldown resistor. The worse problem was that the PWM didn't turn off when I called analogWrite(pin, 0). More worrying, it seemed to be outputting by power rather than duty cycle, since my small LED strip seemed to be doing higher duty than my big LED strip (both powered by transistors), though both were being set with analogWrite(pin, 0). I measured the 5v pin at 5.9v. The input voltage may have actually been up to 12.5 v, but clean. I disconnected VIN and hooked back up to USB, and everything worked fine.

I assume the solution is to either use a linear regulator wired to VIN, or a battery?

I did get the linear regulator, which didn't help. I finally checked all my voltages, and found there was a 0.8 volt difference between different grounds!  It turned out my breadboard was wired to the Arduino pin next to ground, instead of ground itself. I feel very lucky not to have ruined the board, and my only complaint is that the pins aren't labeled clearly as they are on my official Arduino. On the other hand, I wouldn't have been able to debug this as easily on the official Arduino, since the clone has lovely solder holes at each pin which are a great spot to stick a voltmeter probe.

Is it common that Uno clones misbehave when connected to 12v on VIN

Whether it is "common" is probably unanswerable unless you do some sort of survey.

However bear in mind that clones or "knock off" boards (some of which pretend to be official ones) are built to a price. The original Arduino was already designed to be cheap. To make them even cheaper the manufacturers may well make a number of compromises. For example, some use a cheaper USB interface chip. It wouldn't surprise me if the components like the voltage regulator, capacitors, etc. are under-specified.

I see from eBay that clones are already quite cheap, possibly around $US 4.50. To compete with that, some manufacturers may be cutting back even further on the quality of components.

  I assume the solution is to either use a linear regulator wired to VIN, or a battery?

You are probably better off bypassing the on-board regulator entirely. Get a wall-wart that outputs 5V regulated. The sort of thing that might power a USB-based device. Then plug that into the 5V pin of the Uno (not VIN). In fact, virtually any mobile phone charger wall-wart will output exactly what you want. Just run a USB cable from that to the USB port on the Arduino, and there you have it! Regulated 5V power.

The other thing that could work would be to give the voltage regulator a break. Don't put 12V into it, put in 9V. Then it doesn't have to work so hard (that is, dissipate the extra voltage as heat).


Why Arduino Severino (S3V3) sometimes needs reseting when uploading a sketch? I have an original Arduino UNO R3 that I bought and an Arduino Severino (S3V3) that I've built.

I have no problems uploading sketches to the UNO, but sometimes, when uploading to the Severino board, I have to hard reset it at a specific time during the upload process, when the IDE says something like this below:

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : \\.\COM1
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]

If I don't reset it when one of the Send messages are being displayed, I get the not in sync message, as below:

avrdude: Recv:
avrdude: stk500_getsync(): not in sync: resp=0x00

Other times, if I'm lucky, I can upload to the Severino board without having to reset it.

So, my questions are:

Why does that happen? Why Severino needs a hard reset during upload?
Why is the problem intermitent? Why does it happen sometimes and others it doesn't?
How can I fix that problem? Is there a simple change to the Severino design that would fix that?

Why does that happen?

When the serial port is opened by either monitor, avrdude or other it toggles the DTR pin of the serial port. Which in turn is AC coupled through C4 100nF. This toggling is converted to a up and down pulse on the ATmega(CPU)'s RESET pin. The subsequent reset starts initially with the boot loader, which typically in turn waits for a avrdude's semiphore (e.i. Send: 0 [30]   [20] ) and if seen then responds in turn and if not seen after a timeout period (typically 5s) it continues on with the application in flash space.

You behavior is describing either; not hearing the response. Or the reset is not getting triggered. Since it does work some times I suspect its prior, but the later.

Why Severino needs a hard reset during upload?

This statement further supports the later.

Why is the problem intermitent?

the pulse is almost long and strong enough, where the DTR toggle is in code and likely has some significant inconsistency.

How can I fix that problem?

Yes, change the value of C4 100nF and or R11 10K, to better pass the toggle. I could derive some EE explanation of what value to pick. But I would suggest some trial and error.

It should also have 5V clamping, as the RS232 levels can reach +/-12V (typically +/-9V) where the AC coupling prevents the DC and burn out. but the AC will stress it.


Converting of 32 bit signed hex value to dec Using Seed studio CAN shield to read and convert CAN data to dec value.

Example of expected result:

Full CAN message is 70 3B F1 FF 00 00 00 00 , using little endian first 4 bytes gives: FFF13B70 , which should be equal to converted dec value of -0.967824 (using factor of 0.000001).

Here is code to extract the text value I am using.

CAN.readMsgBuf(&len, buf);
unsigned char len = 0;
unsigned char buf[8];
    {
           String reg0 = String (buf[0], HEX);
           String reg1 = String (buf[1], HEX);
           String reg2 = String (buf[2], HEX);
           String reg3 = String (buf[3], HEX);
           Serial.print(reg3);
           Serial.print("\t");
           Serial.print(reg2);
           Serial.print("\t");
           Serial.print(reg1);
           Serial.print("\t");
           Serial.print(reg0);
           Serial.print("\t");
           String regsumm = (reg3 + reg2 + reg1 + reg0);

           Serial.println(regsumm);
        }

As result I got only text string which couldn't be converted into dec. Any other ways how do it?

Since the bytes you received in the buffer are in little endian order,
and your Uno is itself little endian, you don't even need to move bytes
around: you can just reinterpret the bytes you already have as an
int32_t:

union {
    uint8_t bytes[8];
    int32_t numbers[2];
} buffer;
unsigned char len = 0;

CAN.readMsgBuf(&len, buffer.bytes);
Serial.println(buffer.numbers[0] * 1e-6, 6);

This prints -0.967824 to the serial port.

Note that this code will not work as expected on a big endian platform.
If you want something portable, the usual solution is to build the
result using bit shifts, as in Majenko's answer.


Why can't I include a library in another one? I am trying to create a new library that uses another existing library.

The original library declares a way to create an object called Multiserial that can be created in the main file and the program is correctly compiled.

However, when I include this library in a second one and I try to build the program, then the IDE returns an error that says:

  In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Print.h:27:0,
                   from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Stream.h:26,
                   from MultiSerial.h:17,
                   from maqMODBUSmst.h:5,
                   from maqMODBUSmst.c:1:
  C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Printable.h:25:1: error: unknown type name 'class'
   class Print;

Even if the library only contains the include of the first one.

Nested includes lead to these convoluted error messages and are in general, a PITA for the next reader to follow & understand. It is better practice for the dependent library to test, at compile time, for the existence of its required libraries and for each one found missing, issue:

#error DepLibe.h: Missing required include file ReqLibe.h

Most .h files guard against multiple-inclusion by

#ifndef _REQLIBE_H_
#define _REQLIBE_H_
// library definitions here

or some variant of it. DepLibe.h can test for these guard symbols. DepLibe.h should document the dependencies in prominent comments.


Arduino-Bluetooth HC-05 Android app blueterm connection for chatting I want to communicate between an arduino and an Android phone that has an Android app blue term. I connected HC-05 with Arduino using software serial and I connected the hc05 as a device with the android app. I am able to send data ( data as in message) from Android to Arduino but I am unable to send message from arduino to Android though I have given .write() command to Bluetooth connected.

Is it such that the Android app does not show the received message? Or there is some master-slave configuration issue? Do I need to configure HC-05 in master mode? It was configured in slave mode by default when I had connected it to Android app.

Its totally Normal. You must be doing something wrong. It has happen to my Arduino Code a lot of times. try following:

Try interchanging you Tx and Rx Pin Positions. (This happens all the time).
Try connecting using default Serial and using Pin 1 and Pin 0 as Tx/Rx. (In this case remember to unplug the Tx/Rx Pins while running code.)
Try using just basic Serial.Write() function in beginning.


Reading input from digital pins 36, 37, 38 in Arduino Mega 2560 is giving a problem I wrote a program to read digital input from pins 36, 37, 38 and print on LCD when they go HIGH.
I've connected those pins to a switch to test.

The program looks like this:

#include "LiquidCrystal.h"

// initialize the library by providing the nuber of pins to it
LiquidCrystal lcd(8,9,4,5,6,7);
int vswr,th,od,a;

void setup() {
  pinMode(36,INPUT);//SENSING VSWR
  pinMode(37,INPUT);//SENSING THERMAL
  pinMode(38,INPUT);//SENSING OVER DRIVE
  pinMode(35,OUTPUT);//BYTE_CTRL SIGNAL TO SHUTDOWN
  digitalWrite(35,LOW);
}

void loop() {
  vswr = digitalRead(36);
  th= digitalRead(37);
  od = digitalRead(38);
  lcd.begin(16,2);
  // set cursor position to start of first line on the LCD
  lcd.setCursor(0,0);
  if (vswr==1) {
    lcd.write("vswr");
    digitalWrite(35,HIGH);
    delay(2000);
  }
  if (th==1) {
    lcd.write("thermal");
    digitalWrite(35,HIGH);
    delay(2000);
  }
  if (od==1) {
    lcd.write("over drive");
    digitalWrite(35,HIGH);
    delay(2000);
  }
}

When I run this, the LCD continuously  displays:**

  vswrthermaloverdrive

Even though none of the pins are high.

When I use Pins 11, 12, 13 instead of 36, 37, 38 it works fine. I already used pins 11,12,13 for some other purpose. Why is this happening? And how do I solve this problem?

I expect the problem is in the circuit. To be sure, put a serial print statement directly after reading the inputs, to be sure the input values are read correctly.

See the remark of using INPUT or INPUT_PULLUP from Jot below.

The following is just a more compact way of writing your loop (and does not fix your problem):

void process(int pin, char* text)
{
    if (digitalRead(pin) == HIGH) // Use HIGH instead of 1
    {
       lcd.write(text);
       digitalWrite(35, HIGH);
       delay(2000);
    }
}

void loop()
{
    lcd.begin(16,2);
    // set cursor position to start of first line on the LCD
    lcd.setCursor(0,0);

    process(36, "vswr");
    process(37, "thermal");
    process(38, "overdrive");
}

Also, I would add the delay at the end (after the three calls of process).
And instead of hard coded values 36, 37 and 38 use 3 constants/defines.


Is it bad to power a arduino mega with 6V via USB? I'm working on a project where there is no external 5V voltage regulator available but only 6V. I can not power it through the power jack because via this way I do not have enough current and get thermal shutdown.
Can I power it via 6V over USB? at the moment I'm trying this out and it works but what are the long term risks I'm prone to?

The Absolute Maximum Operating Voltage of the ATMega2560 is 6.0V. The same applies to the ATMega8u2 that does the USB to Serial on the Arduino Mega board.
Recommended maximum voltage is 5.5V
So yes, you can run it at 6 Volts, but you are right on the edge, so I wouldn't recommend it.
Possible risks are a decreased lifespan of the Arduino, and there might be some stability issues.
If the application isn't safety critical, and you don't mind having to replace the board after it failed in, say, two year of operation, it could be an acceptable risk (if there are no easily available alternatives)
PS you might want to measure you power supply. It may say it's 6V but could give out 6.2V. The output voltage of some supplies also vary with the load that's across it.


PWM and Analog Signal Quality I'm converting a 0-5v PWM signal to an analog signal using an LM358D. I've connected the output to an oscilloscope to look at the signal but I'm not really sure what I'm looking at. The PWM looks ok but I'm unsure of the analog signal.
Here's some images, please let me know what you think.
Both pics are at 50% signal strength. The oscilloscope is set to defaults, simply connected the probe.
Thanks

EDIT:
Here's the schematic for the PWM to analog converter. The cap is a tantalum. The dip switch changes the analog from 5v to 10v, the signal looks the same on both and is correct voltage so seems to be ok?

The PWM looks ok but I'm unsure of the analog signal.

The “analog signal” looks like the PWM smoothed by a first-order
low-pass filter. It still has some oscillations, 584 mV
peak-to-peak. If you can tolerate that, then it's perfectly fine. If
not, then increase the time constant of your filter.
A first-order low-pass filter behaves, in its stop band, like an
integrator. Thus, a square signal is turned into a triangle. You are
seeing exactly the expected behavior.

The oscilloscope is set to defaults

There are no “default” settings in the oscilloscope. You probably used
the “autoset” button instead. This button tries to find some settings
that let you see something on the screen. I mean, some kind of signal,
not just straight line. If the signal is almost flat, the autoset will
increase the gain until you can see it is not flat. In this case, it
increased the gain by a factor 10 (200 mV / division instead of
2 V used previously). It also added a negative offset in order to
avoid the trace going out of the screen. See the small pentagon on the
far left with a “1” inside? On the first picture this tells you where
the zero (the reference potential) is relative to your signal. On the
second picture, the polygon pointing at the bottom of the chart tells
you the zero is off-scale.
If you want to really appreciate the smoothing action of the filter, you
have to look at its input (the PWM signal) and its output (the “analog”
signal) using the exact same settings. Connect the input, hit “autoset”,
and look. Then connect the output, do not change the settings (do not
hit “autoset”) and look at the output.
Better yet: forget the autoset button, adjust the settings manually and
mind their values.
Better yet: as you have a two channel scope, display both signals
simultaneously, using the exact same settings on both channels.


What's wrong with my IR sensor I bought some 'lucky dip' IR sensors from China, no idea what they are, but they appeared to get lost in the post so instead I bought some of these from a reputable place in the UK that come with a datasheet.

The next day, both items arrived together!

I'm trying to build a very simple proximity sensor for a robot, I built the following circuit:

simulate this circuit – Schematic created using CircuitLab

and stole this code to test it out:

#define IRledPin 8
#define D13ledPin 13
#define IRsensorPin 9

void IR38Write() {
  for(int i = 0; i <= 384; i++) {
    digitalWrite(IRledPin, HIGH);
    delayMicroseconds(13);
    digitalWrite(IRledPin, LOW);
    delayMicroseconds(13);
  }
}

void setup(){
  pinMode(IRledPin, OUTPUT);
  digitalWrite(IRledPin, LOW);
  pinMode(D13ledPin, OUTPUT);
  digitalWrite(D13ledPin, LOW);
}

void loop(){
  IR38Write();
  if (digitalRead(IRsensorPin)==LOW){
    digitalWrite(D13ledPin, HIGH);
  } else {
    digitalWrite(D13ledPin, LOW);
  }
}

If I hold my hand in front of it, nothing happens (LED on-board arduino should light up), however if I point a TV remote at it and press a button, the LED lights up. I tested 2 of the 'fancy' sensors that I got and both behaved the same.

Then I tried one of the 'lucky dip' sensors, swapped it straight in and the whole thing works perfectly - point a TV remote and the LED lights, hold my hand ~10cm in front of it and the LED lights!

So, where have I gone wrong?

See page 5 of your datasheet - that 'fancy' sensor suppresses "• Continuous signals at any frequency".

So you'll need to pulse your 38.4kHz signal for the sensor to produce an output.


Using a channel relay im using 4 channel relay to switch the motor pump.  but when the arduino output is high and i check first with led. the led behavior were high too but when i attached to the relay input IN1,  the relay were low.  its like reversed action(the arduino is high, but relay was low then when arduino output is low,  suddenly the relay was high.  i try to edit the code hoping if i set arduino output is low then relay will be high but its still the same,  its reversed.  arduino output is low but the relay become high.  is there any way to make the relay to become high when the digital output is high?

however.. i didnt have the the actual circuit act but im using the digital pin as the output and some switches.  the project im work on is the automatic aquarium pump and water change which is the pump will automatically refill the water actuated by the float switch and will automatically drain the water and refill the new water in certain time.

im using pin 13 as the output.. and the pin 1 as the input which is a switch
as in picture im using a led as a output. but as soon i change to the relay, it become what i just said at the above

First of all, you'll soon blow up that LED. (Or the Arduino if you're really unlucky.) You need a current limiting resistor.

Secondly, most relays have two switch contacts: normally closed (N.C.) and normally open (N.O.). If you want your device to be off, unless the Arduino turns on the relay, use the N.O. connection. If you want your device to be on, unless the Arduino turns on the relay, use the N.C. connection.
It looks like you need N.O.

N.b: 'closed' means on (i.e. the switch is closed and current is allowed to flow).

Finally, you seem to be using an external pull-up resistor for you switch, which is completely unnecessary: the Arduino has an internal pull-up resistor on every digital pin that you can enable using pinMode(pin, INPUT_PULLUP).

Edit: you didn't connect the relay to the button pin instead of the LED pin, did you?


Rotating Servo Motor using Arduino Using arduino, I'm trying to rotate a 360 servo that will move clockwise 5 seconds,pause and counterclockwise for 5 seconds and then completely stop. However, my servo just continuously keeps on rotating in one direction. Any suggestions will be helpful

you have not put your code here so i can not understand it properly.From what i understand you must have put your code for rotating the servo motor 5 times in void loop. Don't do that put loop for rotating servo 5 time in setup.
void loop run continuously so it must be rotating 5 time then again 5 time and so on.


Can Arduino Mega2560 Use this 24VDC Relay? Can a Arduino MEGA 2560 R3 provide enough current out of its pin to activate the Songle srd-24vdc-sl-c relay? Will powering the Arduino with an external power supply help?

This relay cannot be directly commanded by any Arduino because its coil require 24V voltage to be able to switch the contact; Arduino Mega pins output voltage is 5V.

Regarding current, the relay coil needs 15mA ("high sensitivity" model) or 18.7mA (standard model), that would be OK for an Arduino Mega pin (max current = 40mA).

Anyway, you would have to add some circuit to adapt voltage between the Arduino pin and the relay. For this, first of all you will need to get a second power supply (in addition to the Arduino 5V supply used for Arduino) that can supply 24V.

Then you could use a MOSFET transistor between the Arduino pin and the relay. A MOSFET is often used in so-called Solid State Relay (SSR) because it can almost do the same as a coil relay but is 100% electronic-based (no moving parts); however, contrarily to a coil relay, it does not provide galvanic isolation between the input and the output circuits.

You can check out this question to find out further information on MOSFET.

Personnally, I would rather replace that relay with a 5V relay model, as that would make the circuit simpler, and would remove the need for a second power supply.


What would be the best way to sense the tank level of a 1000L water tank? I want to read in the values to an arduino analog input.

The approaches I have been looking at are:

1.) A ultrasonic distance sensor; my concerns are that tehse are not usually waterproof.

2.) A pressure transducer; these tend to be very pricy.

3.) Some kind of level switch which provides digital input (Is water level here: yes/no?)

Would anyone happen to have some advice on what sort of sensor would be good for the application of reading in the tank level and using the information in a sketch?

There are some ultrasonic sensors that are specifically designed for this very application. I have used something simlar as a water level sensor, and they seem to be reliable. The sensor that I used was from MaxBotix, and had a range of up to 5m, resolution of 1mm, and both analog and serial data output. Interfacing it with an Arduino was very easy.

Have a look at This article for details


Vibrating motors with different intervals For my project, I have 3 ultrasonic sensors and 3 vibrating motors; the motors need to buzz for a small amount of time, then wait for a specific time that corresponds whith the range of the ultrasonic sensor, then muzz again.

The problem I'm having is that I used delays at first but that would cause the third motor only to buzz after the first two already waited.

I basically need something like "digitalWrite(motorPin_1, HIGH) for X amount of time;"
and at the same moment it has to start "digitalWrite(motorPin_2, HIGH) for X amount of time;".

Sadly I can't get the motors to vibrate any softer or harder, so I use these intervals.

Like Edgar commented, you need to check out Blink Without Delay (http://arduino.cc/en/Tutorial/BlinkWithoutDelay). Learn what they are doing and you will get this just fine.

Also, I recommend you learn to use libraries. This library can do exactly what you are asking for: http://playground.arduino.cc/Main/LibraryList#Timing --> click on the "Timer" library by Simon Monk & J Christensen. Follow the examples there. This library works great!

Here is a complete set of code to answer your question. It should work perfectly for you.

/*
buzz3Motors.ino
By Gabriel Staples
http://electricrcaircraftguy.blogspot.com/
7 March 2015

To help this person here: http://arduino.stackexchange.com/questions/9089/vibriting-motors-with-different-intervals
*/

#include "Timer.h"

Timer t;

boolean buzzMotor1Now = false, buzzMotor2Now = false, buzzMotor3Now = false;
unsigned int buzzTime = 1000; //ms
byte buzzPin1 = 11;
byte buzzPin2 = 12;
byte buzzPin3 = 13;

void setup()
{
  //set pins to outputs
  pinMode(buzzPin1, OUTPUT);
  pinMode(buzzPin2, OUTPUT);
  pinMode(buzzPin3, OUTPUT);
}

void loop()
{
  //UPDATE YOUR BUZZMOTOR BOOLEANS HERE, and set to true if necessary

  /**
   * This method will generate a pulse of pulseValue, starting immediately and of
   * length period. The pin will be left in the !pulseValue state
   */
  //Function format: int8_t pulseImmediate(uint8_t pin, unsigned long period, uint8_t pulseValue);
  //see here: https://github.com/JChristensen/Timer/blob/master/Timer.h

  if (buzzMotor1Now==true)
  {
    buzzMotor1Now = false; //reset
    t.pulseImmediate(buzzPin1,buzzTime,HIGH);
  }
  if (buzzMotor2Now==true)
  {
    buzzMotor2Now = false; //reset
    t.pulseImmediate(buzzPin2,buzzTime,HIGH);
  }
  if (buzzMotor3Now==true)
  {
    buzzMotor3Now = false; //reset
    t.pulseImmediate(buzzPin3,buzzTime,HIGH);
  }

  t.update(); //update all timer events
}

Note that only 10 timer events can be ongoing at any given time. If you want to have more you must increase the MAX_NUMBER_OF_EVENTS value in the Timer.h (https://github.com/JChristensen/Timer/blob/master/Timer.h) file.

PS. Also look into the "oscillate", "after", "every", and "pulse" functions, that the library also supports.

If this answer meets your needs please mark the green check beside it to indicate accepted answer. Thanks.