How can I adjust my code so that the value that I print with my BLE device does not get chopped up when I receive it on an app? I am using a BLE device (https://www.adafruit.com/product/1697) that I use to print data to an app. I can successfully connect the BLE to the app and receive the data but the result however gets chopped up.

What I am sending is a lat, lng value (that I gather with a library called TinyGPS++ http://arduiniana.org/libraries/tinygpsplus/) and the code looks like this:

BTLEserial.Print::print(gps.location.lat(), 8);
BTLEserial.print (", ");
BTLEserial.Print::print(gps.location.lng(), 8);

So for example if the latitude is: 32.12345678, it comes like this to the app: 3, new row, 2, new row etc.

So my question is, how can I adjust my code to make sure it does not send the result chopped up but instead sends it's complete value?

how can I adjust my code to make sure it does not send the result chopped up but instead sends it's complete value?

The BLE device uses a package approach and the print member functions only support strings (char vectors and Arduino String). Construct the message as a String:

double lat = gps.location.lat();
double lng = gps.location.lng();
String msg = String(lat, 8) + String(", ") + String(lng, 8);
BTLEserial.print(msg);

Cheers!


bridge messes up serial.print EDIT
I am using an Genuino Uno & Yun Shield

I am a complete arduino noob

I am creating something where I need a process to execute a command on my yun shield but when I use Bridge.begin(); It scrambles all text to something like this

  .ÿš2%š%šr%š%š%šr%š2%š2%º%š%š%š2%º2%º2%ºr%š2%º2%šr%šr%š%š2%šþøøþøøþúøøýýøþþþýþþøøøøúýøþÿøøþþøúýþúøøøþøýøþýúøþþøüþþøýþþøýøúø

and it just keeps adding characters. if I don't use Bridge.begin(); then it correctly prints.

I wrote this short program to replicate the bug:

#include <Process.h>

void setup() {
// put your setup code here, to run once:
// Start the bridge and serial port.
Bridge.begin();
Serial.begin(9600);

 while(!Serial){

 }
}

void loop() {
// put your main code here, to run repeatedly:
Serial.println("test");
}

So this will give the scrambled text and when you remove the Bridge.begin(); it will show the text but I really need to use a Process in my other program so as I understand I need Bridge.

Bridge and Serial both use the same pins. You cannot use them both.

Bridge runs at a much higher baud rate (230400 IIRC) than Serial, which is why it all messes up.


How to control one Mosfet with another mosfet I've got 4x 12V 6a peltiers and some 3d printer mosfet controllers to drive them using PWM with my arduino. But I've found the mosfets need ~7V to switch on, so I'm now wanting to control them with some logic level ones I had around. I could just use the logic ones directly to the peltiers, but am finding it difficult to make my stripboard capable of handling 24A (this page seems to say I need tracks/wire of 2.3+mm diameter which I don't have). Hence I'm trying to make a circuit for the arduino to use the logic mosfets to control the 3d printer mosfets but can't quite get my head around how to do it. I think I'm missing a power source for the first mosfet - do I need to have a whole separate DC power supply for this to the peltiers? Very grateful for a bit of help please!

There's one thing you missed with your arrangement, and that is getting the 12V to turn the MOSFET on.  In your current arrangement it's possible to turn it off, but never on.  Adding a pullup resistor can help:

simulate this circuit – Schematic created using CircuitLab

R1 pulls the gate of M1 up above the switching threshold to turn it on. M2, when on, pulls the gate down below the switching threshold, turning it off.

However: you may have noticed that the switching is now backwards: send a HIGH from the Arduino to turn it off. Which of course has the effect that the output is normally on and you have to actively turn it off.

Again a pullup resistor can help:

simulate this circuit

Now R2 keeps the gate of M2 pulled up (switched on) which keeps M1 turned of. That is, until you actively pull the gate down to ground by sending a LOW from the Arduino.

To ensure that the peltier never turns on when you don't want it to you should also take steps to ensure that the 12V power is never provided without the 5V also being provided - so you could maybe power the Arduino through the barrel jack from the 12V supply.  It doesn't matter if the 5V is provided but not the 12V, but the other way around could mean the peltier comes on with no active control over it.


How to setup an I2C bus which stays valid if a slave is powered down or fails? I have setup an I2C bus between 3 Arduinos (Master, Slave1 and Slave2) by connecting all 3 A4 pins together, all 3 A5 pins together and one GND pin of each Arduino to a common ground line. The 3 Arduinos are currently being powered by independent USB power supplies, but I intend to power all of them from one single power supply using their Vin pins.

The slaves use the Wire library: Slave1 is at address 0x07 and Slave2 at 0x08. The Master uses the I2C library by Wayne Truchsess, because this library has timeout functionality. Master polls Slave1 and 100 ms later, polls Slave2. If either Slave is unavailable, Master should still read the other Slave (this is why Master doesn't work with the Wire library).

However, even though Master doesn't get locked-up, it can't read one Slave if the other gets powered down but left connected. If I cut the power of Slave1, Master becomes unable to read data from Slave2 until I physically disconnect Slave1. If I disconnect Slave1, Master is immediately able to read from Slave2 again. I2C scanning suggests the whole bus becomes invalid when a Slave is powered down (SCL and/or SDA turned low?).

From what I have been reading, this is not a software issue but an electronics circuitry problem: leaking current related to Slave1 and Slave2 having some diodes, something that perhaps could be solved with some transistors or N-FETs which would act like check-valves? Please advise.

P.S.: I have very little background in electronics and English is not my first language.

The 3 Arduinos are currently being powered by independent USB power supplies, but I intend to power all of them from one single power supply using their Vin pins.

I think your problem here is that if you power down one Arduino, it isn't really powered down, because it will get "parasitic power" from the I2C line, particularly from the pull-up resistors which should be there. The protection diodes (internal to the processor) will allow power to flow from the A4 and A5 pins to the Vcc pin of the chip, which will then power up, probably in some sort of indeterminate state.

Since you are planning to power them from the same supply anyway, your problem should simply go away when you do that. Connecting a device with active inputs to a circuit (ie. a voltage present) when the device itself is not powered up, is not recommended. Exceptions would be devices that are specifically designed to handle that, for example, commercially produced printers via their USB input.


How to convert String to Double? I found the .toFloat() but that's not accurate enough.

String StrEx = "57.10598";
float FloatEx = StrEx.toFloat();

Serial.println(String(FloatEx)); //outputs 57.11
Serial.println(StrEx);           //outputs 57.10598

It is a common misconception that, because when you print a float you only get 2 decimal places, that the float only has 2 decimal places.

That is not true. A float doesn't have a number of decimal places - that is how it gets its name - floating point: the decimal point floats around as needed.

The problem is actually that, by default, all the Arduino print and string conversion functions are set to 2 decimal places. Unless you specify the number of decimal places you want to print (or convert to) you get 2 decimal places.

By specifying 5 decimal places when you print or convert to a string you get 5 decimal places.  It still won't always give you exactly the same number, but that is because a 32-bit float cannot store all possible numbers, so some are only an approximation. It's still a whole lot more accurate than 57.10598 -> 57.11 though.


Is the Sparkfun RedBoard pre-loaded with a blink sketch? As soon as I plugged my brand new RedBoard (Sparkfun's Uno) into my computer, I saw the onboard LED (for pin 13) blink on and off every 1 second. This was before I even sent the first demo sketch to blink the LED. After I uploaded a sketch to change the blink time, the LED's blink cycle changed as I expected.

But why was the LED blinking before I sent my very first sketch? Is the RedBoard pre-loaded with a sketch?

Yes, the RedBoard is preloaded with the blink sketch (or at least the two that I've purchased have been).


Analog reading via bluetooth I am making a project in which I am trying to communicate the LDR values collected by one arduino(slave) to another arduino(master) via bluetooth. The readings of the LDR is displayed on the serial monitor.
The slave part of the arduino code :

 #include <SoftwareSerial.h>
  SoftwareSerial BTSerial(10, 11); // RX | TX
  #define ldrPin A0
  int ldrValue = 0;
  void setup() {
     pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
     digitalWrite(9, HIGH);
     pinMode(ldrPin, INPUT);
     BTSerial.begin(9600);
     Serial.begin(9600);

   }
   void loop()
    {
     ldrValue = analogRead(ldrPin);
     BTSerial.println(ldrValue);
     Serial.println(ldrValue);
     delay(10);
    }

I tried getting the readings of LDR in serial monitor to check whether the readings are correct. The readings shown in Serial monitor were correct.

The code of master part of the project which receives the readings from slave :

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
const byte numChars = 1024;
char receivedChars[numChars];   // an array to store the received data

boolean newData = false;

void setup() {
pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH  to switch module to AT mode
digitalWrite(9, HIGH);
BTSerial.begin(9600);
Serial.begin(9600);
Serial.println("<Arduino is ready>");
}

void loop() {
   recvWithEndMarker();
   showNewData();
 }

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

   while (BTSerial.available() > 0 && newData == false) {
     rc = BTSerial.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("This just in ... ");
       Serial.println(receivedChars);
       delay(1000);
       newData = false;
    }
   }

But The serial monitor did not show the correct readings of LDR . Instead it showed something like this

<Arduino is ready>
 This just in ... 8
 This just in ... 3
 This just in ... 4
 This just in ... 3
 This just in ... 3
 This just in ... 3
 This just in ... 3
 This just in ... 4
 This just in ... 3
 This just in ... 4
 This just in ... 3
 This just in ... 3

I have referred this link for the Arduino serial communication:
Serial Input

Kindly help me out since it has been days since I have stuck up in this issue.

Thank you!

A byte is 8 bits, it can hold a maximum value of 255.  You can not store the number 1024 in a byte.  You might want to rethink the type on ndx.
If (ndx >= numChars) then why not set newData to true and print it out.  Something has gone wrong if it gets this far and you want to recover if you can.

Apart from those minor issues your code should work as you expect it to.  Do you have a printout of what the slave's serial output was?  (What you were expecting).  Could it be something to do with the differences between SoftwareSerial and Serial?

Edit:

I have just run a stubbed version of you code on a PC and it ran fine, so I'm going to point my finger at the SoftwareSerial link.  It could well be a misinterpretation of the interface it provides.


Having trouble with sprintf function and string class in my code, I was using string class to make an array to store my menu items
String menu[2] = {{"Menu 1"}, {"Menu2"}};

How do I convert this into char arrays and how do I call them?
Example:
Serial.println(menu[0]);

Create them as char arrays like this:
const char* menu[2] = {"Menu 1", "Menu 2"};

and use them like this:
Serial.println(menu[0]);


Multiple HC-SR04 with one 5v 7805 regulator I am working on a autonomous track vehicle. I have mounted

3 HC-SR04 sensors
1 Sharp infrared distance sensor
3 infrared led distance sensors

1 Arduino Mega 2560
1 H-bridge Board HG7881

I am trying to use 7.5 v 1700 mAh Nicd battery (also tried 11.1 Lipo 2200 mAh)
For all sensors power (5v) I developed 5v regulator using 7805 which is connected directly from battery as input. The output 5v is going to power distribution board (used from quadcopter extra board) which provides 5v to every sensor.

The real problem starts here when I am not getting correct or nothing in reading from Ultrasonic sensors and my vehicle starts behaving abnormal. I checked that sensor reading is either 0 or wrong. I used both simple and with NewPing library.

I checked when using 7.2v battery the output from 5v regulator is 3.72v.

Now my question is if the power is below 5v, does sensors starts behaving like this? How can we supply voltage so every sensor will receive full 5v to work properly?

My vehicle will not work until sensors provide correct distance reading. I worked successfully with one sensor but with number of these, tired working since many days.

You really could benefit from a DC/DC switching power supply.  For instance you are wasting about 20% of the power of the 7.2V battery and something like 50% of the power of the 11.1V battery.

That said, could it be that you are triggering the 3 ultrasonic HC-SR04 too closely together?  If you don't wait for the sound to die out from the 1st sensor the 2nd sensor could give unexpected results.  Same goes for the 3rd sensor.


I2C hookup - sketch just crashes I am encountering problems with I2C when trying to attach a 9DoF Sensor to my Arduino Uno. Following these instructions (the hardware setup I have is like in the schematic) I noticed the basic example not working. I've since debugged different aspects and when I use the "I2C Scanner" example from this page it seems something basic with I2C must be wrong. The code from there I am using is:

// I2C Scanner
// Written by Nick Gammon
// Date: 20th April 2011

#include <Wire.h>

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

  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }

  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;

  Wire.begin();
  for (byte i = 8; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");
}  // end of setup

void loop() {}

Instead of this suggested sample output:

I2C scanner. Scanning ...
Found address: 42 (0x2A)
Done.
Found 1 device(s).

The output I am getting is in Serial monitor on the correct baud rate is:

ù
I2C s

With other examples I have tried I have similar results. As soon as something calls Wire.endTransmission() things start to crash and burn.

Any ideas what this could be or how to debug it?

Wire.endTransmission() is where the action is. Nothing is actually sent until that point. Wire.beginTransmission just gets ready for sending and Wire.write (if used) adds stuff to an internal buffer.

If it hangs at that point you probably have dodgy hardware. Check the connections are correct (ie. SDA/SCL the right way around, and that it is powered, and that you have a common ground).

Then try a pull-up resistor between SDA and +5V, and SCL and +5V. A typical value resistor (for both resistors) would be 4.7k.

I see from the linked page that the board already has 10k resistors. Hopefully you did not cut the jumper links. Whether or not you did you might want to augment them with 4.7k resistors. Also keep the cable runs short.


What maximum length of wire can I use to connect a push button to an Arduino? I am trying to get 8 stop buttons to cause an Arduino UNO to activate a single relay!

The stop buttons have been placed 30' to 250' away from the Arduino uno board.

Q: How far can you go with 5v and still get signal back?

Q: Is there a way to boost the signal?

Majenko's answer is probably the safest option. There is, however,
something simpler that you can try:

Use a strong pull-up (or pull-down). Something around 1 kΩ will
make it quite difficult for the noise to pull your signal low, at the
cost of increased current consumption.
Connect each push button to the Arduino using a twisted pair of copper
wires. This will minimize the inductive pickup effect.


How to connect a a three state switch (ON-OFF-ON) to arduino? I have created a car that can detect obstacle and change its direction, but now I want to add a bluetooth module to control it and I want to switch between the two circuits using a three state switch (ON-OFF-ON), so how can I do that and how can I upload two different codes on the arduino.
Here is a fritzing diagram, (the pins for the bluetooth will be changed).

Sensor:

Bluetooth:

And here is the code for the sensor:

   #define echopin  8 // echo pin
   #define trigpin 9 // Trigger pin

   int maximumRange = 30;
   long duration, distance;

    void setup() {
        Serial.begin (9600);
        pinMode (trigpin, OUTPUT);
        pinMode (echopin, INPUT );
        pinMode (4, OUTPUT);
        pinMode (5, OUTPUT);
        pinMode (13, OUTPUT);
        pinMode (6, OUTPUT);
        pinMode (7, OUTPUT);
    }

    void loop ()
    {
        digitalWrite(trigpin,LOW);
        delayMicroseconds(2);

        digitalWrite(trigpin,HIGH);
        delayMicroseconds(10);

        duration=pulseIn (echopin,HIGH);

        distance= duration/58.2;
        delay (50);
        Serial.println(distance);
    }

        if (distance >= 30 ){
            digitalWrite(4,HIGH);
            digitalWrite(5,HIGH);
            digitalWrite(6,LOW);
            digitalWrite(7,LOW);
            delay (200);
        }
        else if (distance >=15 && distance <= 25) {
            digitalWrite (4,HIGH);
            digitalWrite (5,LOW);
            digitalWrite (6,LOW);
            digitalWrite (7,LOW);
            delay (1000);
        }
        else if (distance < 15){
            digitalWrite (4, LOW);
            digitalWrite (5, LOW);
            digitalWrite (6,HIGH);
            digitalWrite (7,HIGH);
            delay (1000);
            digitalWrite (4,LOW);
            digitalWrite (5,HIGH);
            digitalWrite (6,LOW);
            digitalWrite (7, LOW);
            delay (1000);
        }
    }

Please write in the most details and write any code as I am still a beginner.

As stated by st2000, it's not common practice to have two separate programs running on one microcontroller.

The solution is simple, use the switch to "switch between" behavior.

if(switch is on){
  //Automatic
}else{
  //Bluetooth
}

You should also use functions, to make your code more readable.

This might work:

#define echopin  8 // echo pin
#define trigpin 9 // Trigger pin
#define switchPin 10

int maximumRange = 30;
long duration, distance;

void setup() {
  Serial.begin (9600);
  pinMode (trigpin, OUTPUT);
  pinMode (echopin, INPUT );
  pinMode (4, OUTPUT);
  pinMode (5, OUTPUT);
  pinMode (13, OUTPUT);
  pinMode (6, OUTPUT);
  pinMode (7, OUTPUT);

  pinMode(switchPin, INPUT_PULLUP);
}

void loop ()
{
  if (digitalRead(switchPin)) { //If the switch is pressed.
    automaticLoop();          //Do the automatic control.
  } else {                   //If not pressed.
    bluetoothLoop();          //Do the bluetooth control.
  }
}

void measureDistance() {
  digitalWrite(trigpin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigpin, HIGH);
  delayMicroseconds(10);

  duration = pulseIn (echopin, HIGH);

  distance = duration / 58.2;
  delay (50);
  Serial.print("Distance is: ");
  Serial.println(distance);
}

void automaticLoop() {
  measureDistance();

  if (distance >= 30 ) {
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    delay (200);
  }

  else if (distance >= 15 && distance <= 25) {
    digitalWrite (4, HIGH);
    digitalWrite (5, LOW);
    digitalWrite (6, LOW);
    digitalWrite (7, LOW);
    delay (1000);
  }
  else if (distance < 15) {
    digitalWrite (4, LOW);
    digitalWrite (5, LOW);
    digitalWrite (6, HIGH);
    digitalWrite (7, HIGH);
    delay (1000);
    digitalWrite (4, LOW);
    digitalWrite (5, HIGH);
    digitalWrite (6, LOW);
    digitalWrite (7, LOW);
    delay (1000);
  }
}

void bluetoothLoop() {
  //Code for bluetooth.
}


Interrupt is activated as soon as I insert a jumper wire into the port I have written a very simple code to test the interrupt functionality of my Arduino Uno expansion board:

const byte buttonPin3 = 3;

void setup() {
  pinMode(buttonPin3, INPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin3), trigger, CHANGE);

  Serial.begin(9600);
}

void loop() {
}

void trigger(){
  Serial.println("trigger");
}

However, the Serial.println("trigger"); is activated as soon as I insert a jumper wire into pins 2 or 3. It seems like I have broken the microcontroller. I would appreciate if you could help me know if there is something wrong with my code or I need to change the microcontroller? if I have to replace the MCU can I just use any identical AVR and just place it on the DIP IC socket adaptor?

P.S. Filip Franik asked me to draw the schematics:

simulate this circuit – Schematic created using CircuitLab

P.S. I used the official Button's tutorial and now everything works just fine. I can't reproduce the issue anymore for no obvious reason!.

Connect both Pin2 and Pin3 with two 1K resistors to ground.

When a pin that's set as INPUT is "floating" (it's not connected to anything) the value on it is "undetermined" and interrupt can trigger when a neighboring pin status changes, or even just magically by itself. The 1K resistors (called pulldown resistors) will make sure that pin is set to LOW when it's not connected using the jumper.

This circuit should put a stable 0V on Pin3 when switch is unpressed and 5V when it's pressed. You should be able to verify that using any voltage meter.

If the issue persists then swapping the microcontroller on the Arduino is just one of the steps you need to perform. You would also need to burn a bootloader on the chip. It's not a hard procedure but it requires a second Arduino.


Fan regulator control from Arduino I'm trying to control my ~230 V fan from the Arduino.

Can anyone say the best possible ways to design a fan regulator that can be controlled by the Arduino using a low cost design.

To control AC power for inductive load (motor) a Triac is used. The concept is called phase cutting. It works for a resistive load (heater) too.

This module is designed for phase cutting. It contains a zero crossing detector and a Triac. The control is done in MCU. The zero crossing detector is wired to an interrupt pin. The control signal for the Triac is wired to an output pin. In external interrupt function you set a timer interrupt to send a pulse to the Triac after some microseconds. Longer off time results in less power for the motor.

At 50 Hz AC, one pulse is 10 milliseconds. To cut a part of AC wave out, activate the Triac gate for 20 microseconds after 0 to 10 milliseconds. Triac turns self off the AC line at next zero crossing.

Robotdyn has a library for the module.

EDIT:

I bought the Robotdyn AC dimmer module to use it in my AC heater regulation project and I tested it with a incandescent light bulb and a fan. (video on youtube)

The library by Robotdyn works, but it is designed to control many dimmers and uses a timer interrupt every 12 microseconds (yes, micros). The library sets the interrupts over MCU registers.

I wrote an adrduino fade-in/out sketch using TimerOne library to demonstrate phase cutting with this module.

#include <TimerOne.h>

const byte INTERRUPT_PIN = 2;
const byte TRIAC_PIN = 4;
const byte TRIAC_PULSE_MICROS = 30;

const int FADE_MAX = 9800;
const int FADE_MIN = 2000;

volatile bool triacOn;
volatile int period = FADE_MIN; // microseconds cut out from AC pulse

int fadeAmount = 10;

void zeroCrossing() {
  triacOn = false; // triac tuns off self at zero crossing
  Timer1.setPeriod(period); // to call triacPulse() after off period
}

void triacPulse() {
  if (triacOn) { // stop pulse
    digitalWrite(TRIAC_PIN, LOW);
    Timer1.stop();
  } else { // start pulse
    digitalWrite(TRIAC_PIN, HIGH);
    triacOn = true;
    Timer1.setPeriod(TRIAC_PULSE_MICROS);
  }
}

void setup() {
  pinMode(TRIAC_PIN, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), zeroCrossing, RISING);
  Timer1.initialize();
  Timer1.attachInterrupt(triacPulse);
}

void loop() {
  period = period + fadeAmount;
  if (period <= FADE_MIN || period >= FADE_MAX) {
    fadeAmount = -fadeAmount;
  }
  delay(25);
}

EDIT 2 version with triac activated by 'pwm' pin

const byte TRIAC_PIN = 9;
const byte ZC_EI_PIN = 2;

unsigned long topMicroseconds = 9700; // 10000 micros is between zero crossings
int prescaler = 8;
byte prescalerBits = _BV(CS11); // /8

void zeroCrossing() {
  TCNT1 = 0; // reset the timer counter
}

void setup() {
  Serial.begin(115200);
  Serial.println("START");

  attachInterrupt(digitalPinToInterrupt(ZC_EI_PIN), zeroCrossing, RISING);

  pinMode(TRIAC_PIN, OUTPUT);
  uint32_t topPeriod = ((F_CPU / 1000000)* topMicroseconds) / prescaler ;
  ICR1 = topPeriod;
  OCR1A = topPeriod + 1;
  TCCR1A = _BV(WGM11) | _BV(COM1A0) | _BV(COM1A1);
  TCCR1B = _BV(WGM13) | _BV(WGM12) | prescalerBits;
}

void loop() {
  if (Serial.available()) {
    unsigned long microseconds = Serial.parseInt();
    Serial.find("\n");
    uint32_t period = ((F_CPU / 1000000)* microseconds) / prescaler ;
    OCR1A = period;
  }
}

on SAMD it is possible to setup this to start the timer on external interrupt over event, without an interrupt function. then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals

EDIT 3:

The TriacDimmer library version 1.1.0 for AVR Arduinos available in Library Manager works good with this dimmer. Fun fact: It uses timer1's input capture on pin 8 instead of external interrupt on pin 2 or 3.


ATTiny85 Digispark clones failing USB handshake - how to program them? I've recently bought a batch of ATTiny85 modules (Digispark clones) from China, and tried to write a first test program into them now. I noticed that they do seem to have some bootloader already installed since the P1 LED is flashing, but they do not seem to make any reasonable USB handshake.
(I have ordered other seemingly identical modules from a different seller on Ali before and was able to use them just fine.. so I generally know how to work with these.)

Linux dmesg shows me that a device was plugged in, but does not get any vendor or model ID. Windows tells me that 'the device last plugged in has failed enumeration'. This looks to me like the bootloader is incomplete or somehow broken.

So, as a next step, I tried to rewrite the AVR with an USBASP adapter over ISP, only to find out that the /reset pin apparently has been disabled via fuse bit.

I'm in some kind of a loop now... If the bootloader doesn't speak USB correctly, I can't use the Arduino IDE or avrdude or anything to write to it, and if the /reset is remapped I can't replace the bootloader via ISP to get USB working.

Can anyone provide a hint on how I can get these modules to work? Or should I just assume I bought a bad batch, throw them away and order fresh ones?

I had problems too - SHORT: all about USB-hub or PC's root-hub and extension cables +Luck.

My ebay items were going under the name "Digispark Kickstarter ATTINY85 Arduino Micro USB Development Board" and naturally it came with no Digispark-(c)-right infringing markings from China. I kept my fingers crossed that my items would at least be AVRisp-programable..

So in high hopes I plugged in my China import into my trusty USB HUB2.0(which I always use at least as a current limiter) – after testing it first on a powerbank (>5secs blinky-blink)  .. checked for enumeration (which it did-but no driver yet) .. installed the DPinst[64].exe drivers.. and then kept getting messages like >>device failed to enumerate<<, etc. - the list of my failures:

determined directly plugged into a PC's USB root-hub rigged/minimalistic usb devices do not enumerate at all (all 0s)
with a certain USBAmale-to-USBAfemale extension cable with plastic-encasing(female side) the USBA device’s was not allowed to go "in" probably just for some millimeters to short.. the Data-lamella do not connect correct – just power's okay (blinky-blink) .. but no Windows device-recognition .. No-No!
AND reminding the FTDI black-listing dilemma I used PCs without out the drivers still – using the good old “USBview.exe” program to check on the enumeration (on all my available device the same .. previously plugged into my driver-enable PC or just into an “out of the fab”-one

idVendor:           0x16D0
idProduct:          0x0753
bcdDevice:          0x010B

so no mis-configuration of the bootloader through a >possibly mallign< Digispark clone dis-configurator (as I was thinking the FTDI schemes .. of course FTDI only did it to protect their name X-) – to stop getting accused for faulty devices coming from cheap chinese fake or clone-producers)
* EVEN tried to deinstall the Drivers with DPinst[64].exe /D .. which gave me .. Yes .. yet again “Drivers all installed properly!”..

.. and IN THE END .. I just went back to my old, initial “USB HUB-behind root-hub” configuration .. and Abra-ca-Zang .. the device just enumerated and registered as “Digispark Bootloader” (windows device manager under libusb-win32 Usb Devices)

and all went okay - reprogramming with the Arduino IDE - NO FUZZ!
.. The !very same! config I was using on my “first testings” (minus some fair time and headaches of debugging)

So my advice .. always do a Basic-Test on a USB Powerbank, USE an USB-Hub, check your cables - use ones you trusted before! – try as many options as you (may) have .. and use the tools at your hand .. down to PC-progs or an logic-analyzer or an Beagle USB / protocol analyer to check where the problem may be.. trace back your tracks and even retry..

There may be a suprise for you at the end of the rainbow!


Can I get the current connection speed with ESP8266? Using an ESP8266 I can get the RSSI of the Wifi network using Wifi.getNetworkInfo() or Wifi.RSSI(). But is there a way to know the actual connection speed in Mbps, after joining successfully a WiFi network?

Wifi modules decide on link speed based on signal strength. So you can estimate the link speed with signal strength, which you can get with WiFi.RSSI(network).

The datasheet of ESP8266 contains a table mapping RSSI to link speed under "Sensitivity":

-98 dBm: 1 Mbps
-93 dBm: 6 Mbps
-91 dBm: 11 Mbps
-75 dBm: 54Mbps
-71 dBm: 65Mbps, 72.2Mbps

Whenever these values are "minimum", "maximum" or "typical" remains unclear. These dBm limits are also quite low, which means the link speed will probably be capped by the other communication peer (your router). Here's the same table for a random D-link router, DI-624.


Executing machine code at runtime Uno I want to create a small single threaded os for my arduino.The first thing I want to do is to allow my arduino to read a section from flash/eeprom and execute it. I have some question regarding the memory. The microcontroller is executing one command at a time from..where? Does it directly acces the flash containing the code and take every command at a time?(that would be slow) Or does it first load the entire program into sram?(also wouldn't make sense because sram is 2k while flash is 32k). Either way,if I can find in sram /flash my code( or the header to some void) then i could jump there.Am i wrong?Is it possible(to do such os)?

Something like this:

uint16_t addr=0x1234;
void (*function)(void)=addr;
function();

(or maybe with some avr like assembly code?)

The microcontroller is executing one command at a time from..where?

Flash memory directly. The AVR core can only execute instructions from Flash memory. It uses a two-bus system known as Harvard Architecture, where the Instruction Bus is connected to Flash and is used to execute instructions, and the Data Bus is connected to SRAM, EEPROM, all the peripherals, GPIO pins, etc.

It is possible to jump to any location in memory in a similar way as you have depicted, but in order to know where you first need to know the functions you want to call.  You can get the address of any function and assign it to a pointer, and then call that pointer as a function, but what would that achieve? You may as well just call the function directly and save time. Unless you want to store the addresses of those functions in an array or something to maybe associate them with a command to trigger the execution of that function. In which case you don't need anything "fancy", just pointers to the functions you want to use.


It gives some glitching on 7 segment display It gives the right value on the monitor but it doesnt display the value on my display.

int pinNumb[7] = {2, 3, 4, 5, 6, 7, 8};
int num_array[11][7] = {
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }, // 9
  { 0, 0, 0, 0, 0, 0, 0 }  //nothing
};

int pin = 2;
int button = 12;
int buttonVal;
int randVal;
bool pressVal;
void setup() {
  Serial.begin(9600);

  for (int i = 0; i < 7 ; i++)
  {
    pinMode(pinNumb[i], OUTPUT);
  }
  pressVal = false;
  pinMode(button, INPUT);
}

void loop() {
  buttonVal = digitalRead(button);
  if (buttonVal == 0)
  {
    //zero();
    turnOff();
    pressVal = false;
  }
  else
  {
    //zero();
    if (pressVal == false)
    {
      randVal = rand() % 10;
      pressVal = true;
      delay(100);
    }
    Serial.println(randVal);
    if (randVal == 0)
    {
      zero();

    }
    else if (randVal == 1)
    {
      one();

    }
    else if (randVal == 2)
    {
      two();

    }
    else if (randVal == 3)
    {
      three();

    }
    else if (randVal == 4)
    {
      four();

    }
    else if (randVal == 5)
    {
      five();

    }
    else if (randVal == 6)
    {
      six();

    }
    else if (randVal == 7)
    {
      seven();

    }
    else if (randVal == 8)
    {
      eight();

    }
    else
    {
      nine();

    }
  }
}

void zero()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[0][j]);
    pin++;
  }
}

void one()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[1][j]);
    pin++;
  }
}

void two()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[2][j]);
    pin++;
  }
}
void three()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[3][j]);
    pin++;
  }
}
void four()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[4][j]);
    pin++;
  }
}
void five()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[5][j]);
    pin++;
  }
}
void six()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[6][j]);
    pin++;
  }
}
void seven()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[7][j]);
    pin++;
  }
}
void eight()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[8][j]);
    pin++;
  }
}
void nine()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[9][j]);
    pin++;
  }
}
void turnOff()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }

}

These can all be byte instead of int to save on memory:

int pinNumb[7] = {2, 3, 4, 5, 6, 7, 8};
int num_array[11][7] = {
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }, // 9
  { 0, 0, 0, 0, 0, 0, 0 }  //nothing
};

int pin = 2;
int button = 12;
int buttonVal;
int randVal;

In addition, the array can be reduced to 11 bytes:

0bFD, // 0
0bC0, // 1
0bDE, // 2
etc.

Then your functions can do direct port manipulation to send bits 0-5 to the Port for D2 to D7, and bit to D8.

As written, these functions probably need some hold time so they don't just flash the LED and disappear:

void one()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[1][j]);
    pin++;
  }
}


Arduino Uno - Multiple modules for HDMI switch device I have an Arduino Uno device that uses the following modules:

16 PIN LED w/ Backlight
RFID - RC522 (RFID Reader)
HR911105A (LAN Module - HanRun)

These three modules use every digital pin available in the Uno (2-13) and
it works correctly. The problem is that I want to add a relay to this board. I am new to Arduino so I use tutorials and right now I do not fully understand how this works. So I have connected the IN pin of the relay to Uno pin 8 and the NO pin of the relay to Uno pin 13.

The problem is that when I don't use other modules the relay works correctly (using this code).

int relay_pin = 8;
int led_pin = 13;

void setup() {
  pinMode(relay_pin,OUTPUT);
  pinMode(led_pin,OUTPUT);
  digitalWrite(led_pin,HIGH);
}

void loop() {
  digitalWrite(relay_pin,HIGH);
  delay(5000);
  digitalWrite(relay_pin,LOW);
  delay(5000);
}

The remaining ports are 1 and 0, which I assume are TX/RX, and can't be used for relay (am I wrong?).

So obviously I should not be using those pins but I wonder which pins I am allowed to use simultaneously when using two or three modules at the same time.

Does it depend on the modules or are there some instructions?

The relay wiring diagram you are following is just plain bizarre and the strangest one I have ever seen.

Ignore it. It is completely incorrect.

You only need one pin to control a relay, so disconnect it from pin 13.

The switched side can connect to anywhere where you would normally use a switch - such as to switch power to an LED connected between +5V and GND with a suitable current limiting resistor.

You can use any available pin to control the relay, and that includes pins 0 or 1 if you aren't using serial communication.  Note that with the relay connected to one of those pins it will most likely activate and buzz while you upload a sketch - best to disconnect it at that point and reconnect it afterwards.

Devices like relays and LEDs need their own dedicated pin. They can't be shared with other functions or each other.

The only devices that can share pins are devices which connect to a bus, such as SPI or I2C.


The BOOTRST fuse was disabled, but bootloader code is still running after chip reset I am experimenting with an ATmega328P bootloader, and I created an Intel HEX (.hex) file with a program with an infinite loop in the beginning and with Optiboot code at the end of the hex file. (Code loaded into the chip is here: http://relliks.php5.cz/stackexchange/DUMP.bin.)

Then I disabled the BOOTRST fuse and pressed the restart button on Arduino Uno R3, but the bootloader still blinks with the LED on digital port 13.

How is it possible, that the bootloader is executed after chip restart and BOOTRST is disabled? My fuse settings are: Only SPIEN and BODLEVEL0 are set.

I found that when I disable the BODLEVEL0 fuse, the bootloader turns off.
BODLEVEL0 is used to set the brown-out voltage and shouldn't affect bootloader start. Where is the issue?

You don't seem to have filled in all the interrupt vectors. I get this from your .bin file:

00000000 <.sec1>:
       0:       00 c0           rjmp    .+0             ;  0x2
       2:       00 00           nop
       4:       00 00           nop
       6:       00 00           nop
       8:       fc cf           rjmp    .-8             ;  0x2
       a:       fb cf           rjmp    .-10            ;  0x2
       c:       fa cf           rjmp    .-12            ;  0x2
       e:       f9 cf           rjmp    .-14            ;  0x2
      10:       f8 cf           rjmp    .-16            ;  0x2
      12:       f7 cf           rjmp    .-18            ;  0x2
      14:       f6 cf           rjmp    .-20            ;  0x2
      16:       f5 cf           rjmp    .-22            ;  0x2
      18:       ff ff           .word   0xffff  ; ????
      1a:       ff ff           .word   0xffff  ; ????
      1c:       ff ff           .word   0xffff  ; ????
      1e:       ff ff           .word   0xffff  ; ????
      20:       ff ff           .word   0xffff  ; ????
      22:       ff ff           .word   0xffff  ; ????
      24:       ff ff           .word   0xffff  ; ????
...
    7dfc:       ff ff           .word   0xffff  ; ????
    7dfe:       ff ff           .word   0xffff  ; ????
    7e00:       11 24           eor     r1, r1           <--- bootloader
    7e02:       94 b7           in      r25, 0x34       ; 52
    7e04:       14 be           out     0x34, r1        ; 52
    7e06:       89 2f           mov     r24, r25
    7e08:       8d 70           andi    r24, 0x0D       ; 13
    7e0a:       11 f0           breq    .+4             ;  0x7e10
    7e0c:       89 2f           mov     r24, r25
    7e0e:       de d0           rcall   .+444           ;  0x7fcc
    7e10:       85 e0           ldi     r24, 0x05       ; 5

Now I can't quite see the relationship between the brown-out and those higher interrupts, but if one of them happened to fire I think it would waddle its way past all those 0xFF instructions and hit the bootloader.

The Atmega328P has 26 interrupt vectors (including Reset).


Arduino based fully controlled aquaculture I am doing a project on aquaculture,so I am using temperature sensor, water level sensor, dissolved oxygen sensor, pH sensor and also 4 motor's and water heater is it possible for a single Arduino to run all these at the same time??

I would suggest finding sensors that work on an I2C bus. This way all the sensors are only using two pins for data. That will free up other outputs for motors, heaters that will probably be on relays or other drivers that need a single or multiple pins for each devices.  As you start to plan it out, if you do run out of pins on a arduino uno, look at the Mega, as it has many more GPIO pins as well as multiple dedicated UART ports.

Bottom line, find your sensors, drivers, see what type of communication they require, and start to make a list of how many separate io pins you need. Then that will tell you which board is suitable for your project.


Digital Band pass filter arduino 1100-1300 Hz For a project I need to design an digital band pass filter. I started of with this in Matlab:

wch=1100*2*pi;
wcl=1300*2*pi;

sys=tf([1/wch 0],[1/(wch*wcl) 1/wch+1/wcl 1])
sysd=c2d(sys,9615,'tustin')

so I got this values:

3.01e-08 z^2 - 3.01e-08/(z^2 + 2 z + 1)

Then I rewrote it to:

y[k] = 3.01*10^-8*u[k]-3.01*10^-8*u[k-2] -y[k-2]-2y[k-1]

and so I put hoped that this arduino script should do the Job:

#include <TimerOne.h>

float out;

float second_filt(float x0) {
  static float y1=0;  // y[n-1]
  static float y2=0;  // y[n-2]
  static float x1=0;  // x[n-1]
  static float x2=0;  // x[n-2]
  float y0 = 3.01*10^(-8)*x0-3.01*10^(-8)*x2-2*y1-1*y2 ;

  // Shift values
  y2 = y1;  // Shift y[n-1] to y[n-2]
  y1 = y0;  // Shift y[n] to y[n-1]
  x2 = x1;  // Shift x[n-1] to x[n-2]
  x1 = x0;  // Shift x[n] to x[n-1]
  return y0;
}

void setup() {
  Timer1.initialize(32); //Initialize timer with a period of 32 us
  Timer1.pwm(9,0); // Use pin 9 for PWM
}

void loop() {
  if (isTime()) {
    out=second_filt(analogRead(0));
    Timer1.setPwmDuty(9,out); //Sets the duty cycle to the analog value on pin 0
  }
}

bool isTime(){ //Checks if 300 us elapsed since the last call
  static unsigned long t0=0;
  static unsigned long t1=0;

  t1 = micros();

  bool res = (t1-t0)>300;

  if (res) {
    t0 = t1;
  }
  return res;
}

Now I don't know what the error: 'invalid operands of types 'double' and 'double' to binary 'operator^' means and I am not sure if this is actually gonna work. Pleas help me out I have been busy with this for days.

You cannot use ^ as mathematical power symbol in C. Ini C it means the exclusive-or bit operation (hence the error showing it is a bit operation).

For the mathematical power function, you should use the math C library. See library explanation. To include it, use:

#include <math.h>

The power function has the following prototype:

double pow(double x, double y)
Returns x raised to the power of y.

However if you only need to write a float/double in exponential format, you can use

3.01e-8


How to 'label' module using electric techniques I am in a project where it makes set of 'modules(set of separate circuits that will work as a sensor when connected to the board' that would be connected to Arduino Mega.

Currently, I'm planning to connect 'modules' with the Mega board using RJ-45(also known as LAN cable) cables.

At first, using voltage divider circuit, I tried to identify these 'modules' by attaching a resistor to it, so that if the board sends 5V to the 'module', it gets the resistance of the resistor inside the module.

But, as soon as I tested, this way seemed a bit unstable, because the measured resistance of the resistor kept changing.

Now, is there any other way to 'label' the module? I'm a beginner in this thing, so I'll appreciate any help that is provided.

Thanks in advance.

Ps. the voltage divider circuit that I used can be found in here:

Ps2. the resistor in the module does not mean the total resistance of the circuit in the module. It's separate.

If you are unable / unwilling to change your interface into a purely digital system whereby a small microcontroller in the sensor module interfaces the sensor with a communication bus, the best method is probably to include a small 1-wire EEPROM with each module.

An ideal one would be the DS2431 which provides 1024 bits (128 bytes) of EEPROM storage using just 1 wire to both communicate and provide power.

Programming in a unique identifier for the module would be a simple enough task, and that unique ID can then be used to work out what the module is.

The DS2431 is pretty cheap too, available at prices around  $1.50 and below (much less for bulk and surface mount).

You can also get bigger versions for storing more data should you want to.


2 SPI Slaves with 2 different SPI modes on one Arduino Mega I am working on a project where I read 8 MAX31856 thermocouple sensors using the Adafruit Library. This works just fine and prints the read outs to serial.
I want to also save the readings to a microSD card. And this is where I hit a snag.
I am trying to use the SdFat.h library. I can loop through my MAX31856 thermocouples, and write once to my SD card, but after that it hangs the SPI bus.
the MAX31856 works on SPI_MODE1 (as per Adafruit Library) and the microSD card works on SPI_MODE0, I believe. I am trying to switch SPI bus modes before and after writing to the SD card but I think there is something wrong after first successful write to the SD card. After the first loop iteration, it seems like all data is basically noise on the SPI bus.
I am using the Adafruit ADA254 microSD breakout Board, which has a card detect pin, so I first check to see if an SD card is inserted, and then write to the file.
Question: Is there another or better way to switch SPI_MODES on each loop? is there anything more I need to consider so I end up back to SPI_MODE1 appropriately for the MAX31856 thermocouples?
Below is the pertinent code for what I have going on...
void setup(){
   int sdCard = 36;
   char filename[10] = "test.txt";
}

void loop(){
....code to read thermocouples ...

///THEN THIS

  //lets confirm SD card is still in socket before writing
  CardDetect = digitalRead(37);
  if(CardDetect == HIGH){

     SPI.setDataMode(SPI_MODE0);
     SPI.setClockDivider(SPI_CLOCK_DIV4);
     SPI.setBitOrder(LSBFIRST);
     digitalWrite(sdCard, LOW);
     sd.begin(sdCard, SD_SCK_MHZ(1));
    //LETS START SAVING DATA
          myFile.open(filename, O_WRONLY | O_CREAT | O_EXCL);
          myFile.write(now.unixtime());
          myFile.write(",");
            for(int i = 0; i<8; i++){
              myFile.print(TEMP[i]);
              myFile.write(",");
            }
          myFile.println();
          myFile.close();
          digitalWrite(sdCard, HIGH);
          SPI.setDataMode(SPI_MODE1);
          SPI.setClockDivider(SPI_CLOCK_DIV16);
          SPI.setBitOrder(MSBFIRST);
          delay(200);
    }

}

For anyone who has a similar issue with the SPI Bus, SdFat library has a Software SPI option built in (example here).
You need to modify your SdFat/SdFatConfig.h file, but that is minimal. Once you have the microSD card module on a separate bus, it will not corrupt the main SPI Bus.
Switching the SD Card module to it's own bus rectified the issue. Keep in mind that Software SPI comes with a speed penalty.


Is there a working combination of Arduino IDE + Ardublock? I'm trying to set up Ardublock, but the last release they have is from 2014 and in a recent Arduino IDE it fails when I try to upload the program to the Arduino board:
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: processing.app.Editor.setText(Ljava/lang/String;)V
    at com.ardublock.ArduBlockTool.didGenerate(ArduBlockTool.java:72)
   ....

I assume there is a different API in the recent Arduio IDE for copying the generated code into the editor. This is the block diagram I'm trying to upload. As you can see there are no libraries involved:

Is there a known combination of Arduino IDE and Ardublock which works? Or perhaps an addon similar to Ardublock which is maintained?

I found that Ardublock project was forked on Github, and the latest release indeed works with up-to-date Arduino IDE.


Code uploads successfully on esp8266-01 but doesn't run I am using esp8266-01 board. It was working fine few days ago, the codes uploaded and ran successfully. But now that I upload code to it, it gets uploaded successfully but it doesn't work.

I am using arduino nano to program it. It is connected as:
esp-01       arduino nano
tx-------------tx
rx-------------rx
vcc------------3v3
ch_pd----------3v3
gpio0----------gnd
gnd------------gnd

the code is basic blink code:

void setup(){
   pinMode(2, OUTPUT);
   }
void loop(){
   digitalWrite(2, HIGH);
   delay(500);
   digitalWrite(2, LOW);
   delay(500);
   }

This code gets uploaded successfully (According to IDE atleast) but it doesn't run. LED connected to gpio2 is always on. I also tried gpio0 and gpio1 but no luck.

I have already spend days trying to fix this. Please Help.

if you are using a nodemcu, the pin numbers do not correspond to the digital pins, they correspond to the gpio pins. The digital pin 2 is the gpio 4 and the digital pin 4 is the gpio 2.
Here you have a list of digital and gpio pins:

D0 = GPIO16;
D1 = GPIO5;
D2 = GPIO4;
D3 = GPIO0;
D4 = GPIO2;
D5 = GPIO14;
D6 = GPIO12;
D7 = GPIO13;
D8 = GPIO15;
D9 = GPIO3;
D10 = GPIO1;


Stop Led's from blinking My code:

// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == LOW)
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
   }
 if (buttonState == HIGH){
   digitalWrite(led, LOW);}
  }

The last line of code:

if (buttonState == HIGH){
   digitalWrite(led, LOW);}

Is what I tried using to turn the led off from its continuous blinking state. So the point of this project is to make the led's blink with a button, then turn them off with the same button. This has been bugging me for hours and I've done all the work but can't seem to get this last part done. What is being done wrong here?

EDITED for clarification:

The intention is that with each push of the button the LED is toggled between a blinking and a no-blinking state. The state of the LED is not driven by the level (pushed/unpushed) of the button itself, but by the pushing action itself.

EDITED

The Arduino loop() function makes the use of a while loop redundant in this case. Even worse: the way you've implemented that while loop prevents buttonState from being updated, thus getting stuck in the loop.

What you actually need is to use timers to blink the LED, and a 2-state machine driven by HIGH to LOW button transitions.

Try this instead:

#include "Timer.h"

// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
const int led = 13;
const int buttonPin = 2;

// declare state variables as global
bool buttonState = LOW;
bool buttonState_prev = LOW;
bool toggleBlinking;
bool blinkState;

// declare a Timer object so blinking can be done without loosing button presses
Timer timer_b;
int blink_id;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);

  // initial state: toggle led each 1000 ms
  blink_id = timer_b.oscillate(led, 1000, HIGH);
  blinkState = true;
  toggleBlinking = false;
}

// the loop routine runs over and over again forever:
void loop() {
  // Update the timer (required)
  timer_b.update();

  // check if button has been pressed (HIGH to LOW),
  // then debounce it and raise toggle flag
  buttonState = digitalRead(buttonPin);
  if ((buttonState != buttonState_prev) && (buttonState_prev == HIGH)) {
    // simple button debounce (confirm press after some ms)
    delay (50);
    buttonState = digitalRead(buttonPin);
    if (buttonState != buttonState_prev) toggleBlinking = true;
  }

  // keep current LED state unless the button has been pushed
  switch (blinkState) {
    case true:
      // if button has been pushed, stop blinking and change LED state
      if (toggleBlinking == true) {
        timer_b.stop (blink_id);
        blinkState = false;
      }
      break;
    case false:
      digitalWrite(led, LOW);
      // if button has been pushed, start blinking and change LED state
      if (toggleBlinking == true) {
        blink_id = timer_b.oscillate(led, 1000, HIGH);
        blinkState = true;
      }
      break;
  }

  buttonState_prev = buttonState;
  toggleBlinking = false;
}

NOTE: You'll need to install the Timer.h library. I'VE TESTED MY CODE AND IT WORKS.


Arduino motor rotation I am a beginner in Arduino. Below is my code to propel the fans of my motor. This happens in a clockwise direction but I wish to change the direction of rotation.

How can I modify it?

// Declare the pin for the motor
int motorPin = 9;

void setup() {
  // Define pin #9 as output
  pinMode(motorPin, OUTPUT);
}

void loop() {
  // Turn motor on
  digitalWrite(motorPin, HIGH);
  // Wait 250 ms
  delay(250);
  // Reanimate motor
  digitalWrite(motorPin, HIGH);
  // Wait 250 ms
  delay(250);
  // Turn motor off.
}

I guess you have a DC motor in use. Likely a FET drives it on port 9.

This arrangement is enough to start or stop the motor, however to change direction, you need to swap the two wires on the motor.

I guess you may perfer to do this in software - and for that you need to replace the simple FET driver with a H-Bridge. H-Bridge is an arrangement of electric switches which allows you swapping motor polarity, and it usually comes pre-assembled to a chip.

There are a vast amount of h-bridge motor driver chips to choose from. Google for "pololu motor driver", or "adafruit motor driver".

You can find all the further details in the Arduino examples on the web, e.g.:

https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing/overview


Can you fry an arduino with nothing plugged in to it? I only get to work on my arduino every few weeks, so sometimes and get interrupted a lot by small children, so if I completely forget what is on the firmware, then I unplug the pins (because I haven't got anything soldered on there) should I be 100% certain I'm not going to fry my board?

Although the controllers on an Arduino are pretty well protected, they can still be damaged by ESD (Electro Static Discharge). The same effect that makes a crispy sound when you pull off your woolen sweater in the winter, or after walking with rubber shoes on a carpet and you touch someone else or a metal and grounded object and you feel a pick. Static electricity can damage the controller. It may get completely broken, or it may function 'most of the time' or lifetime may be shortened.

An Arduino is also easily killed with an piezo gas lighter, just make the spark near the copper traces that feed directly in the controller. This is largely the same effect as above.

Again, the controllers themselves are pretty well protected, don't worry too much about them. But with kids running around (on their rubber shoes) better make sure they don't accidentally draw a spark from their little finger to your Arduino. The protective metallic bag is best, but putting it away in a cupboard or box should do the trick equally well.

As a general rule of thumb, the faster the electronics, the more sensitive it is for ESD. A Due is probably more sensitive than a UNO or a MEGA. But with normal, avoiding static electricity, use you should be OK.


how to read arduino board info serial no programmatically well I am try to make an project with original arduino. but I want to make this project unique. if my codes are copied and loaded another arduino board, my app should not work. how can make unique app, are there any idea? on Arduino IDE Tools> Get Board İnfo> SN look unique id. but how can read it programmatically.

You can't. The serial number is burned into the ATMega16U2 chip and is only available to the computer over the USB interface.  There is no method for you to get it from the UART interface that connects the two MCUs together.

To stop people copying your code there are two things you need to do:

Don't allow anyone access to the source code or any compiled code files, and
Enable the "code protection" facility of the ATMega328P.

The latter will stop people being able to read the code from the Arduino. It would also be beneficial to remove the bootloader and program the board directly. That way there is no other possible route for getting at your code.

You enable code protection by setting the correct fuse bits.


Can I power an Arduino with a computer's motherboard? I was thinking of using my Arduino to turn on and off a computer remotely. I would like to know if the 5v header pin on a computer's motherboard (which I’m using instead of a USB because the 5v pin provides a constant power supply) can power an Arduino UNO without frying it. If the Arduino can be powered where would the cable from the 5v motherboard pin go into the Arduino?

↑ These are the pins I would like to use

You want to tap off of the +5VSB pin of the ATX or BTX power supply connector and send it to the 5V pin on the Arduino. Where this will directly drive the VCC(5V) of the UNO.

Note that 5V of the USB basically drives the VCC directly, except through a MOSFET that acts as a blocking diode to prevent local VCC from flowing back to the 5V_USB.

Not sure if you are suggesting that the 5V USB is frying Arduino's. If so that is bad. If true; Fix that first.

That said (with good 5V usb) you should be able to find or configure (BIOS) so that a USB connector will remain powered, and allow a wake up from mouse movement. Hence a possible solution would be to use a Leonardo/Micro's Mouse emulation to do just that as to wake the PC, without any hardware mod's.

Freeduino Micro's are pretty cheap.


Power bank turns off spontaneously I currently have a 50,000 mAH USB power bank powering my Arduino Uno and micro servomotor. Unfortunately, my power bank has an automatic shutoff and shuts off after 2 hrs of runtime (I need 16 hrs for my project). I can restart the power bank by hitting the on button and it will run just fine for another 1-2 hrs at which point it will shut off. In one instance, the power bank ran for the desired 16 hrs straight hours. I believe that my arduino/servo are very close to the current threshold of the bank which could explain some of the variability I am seeing in terms of turn-off time. Would hooking up a resistor in the circuit do the trick and if so where?

Not quite sure about the brand of power bank (just one I found off Ebay). I believe the arduino uno and servo consume about 60 mA for power.

You have a couple of options, depending on how much you want to dive into electronics.

Find/buy a new powerbank that does not auto-shutoff
Find the current-sense resistor on the internal circuitry of your existing powerbank and change it out so that the device always thinks there is current flowing, or is more sensitive to your low-draw attachment. I was able to find a few websites describing this for specific powerbanks by searching.
Add a dummy load in parallel with your circuit, which wastes power, but does trick the powerbank into staying on.

It's also worth noting on the side, that you very likely do not have 50,000 mAh capacity in this powerbank, as others have noted. However, you ought to be able to get 16h of runtime with even a lower-rated powerbank if your claim of 60mA current draw is true.


Operating Sharp memory LCD with Arduino I am trying to write to Sharp memory LCD "LS027B7DH01" which isn't going well for me. I didn't find any useful information for beginners. I just want to display any character on the LCD. Here's my code:

#include<SPI.h>

int SCS=10;
int SI=11;
int SCLK=13;
int EXTCOMIN=4;

 void setup()
 {
   pinMode(SCS,OUTPUT);
   pinMode(EXTCOMIN,OUTPUT);
   pinMode(SCLK,OUTPUT);
   pinMode(SI,OUTPUT);
   digitalWrite(SCS,HIGH);
   tone(EXTCOMIN,40);
   SPI.setClockDivider(SPI_CLOCK_DIV16);
   SPI.setBitOrder(MSBFIRST);
   SPI.setDataMode(SPI_MODE0);
   SPI.begin();
   SPI.transfer(0×20);
   delay(3000);
}

void loop()
 {
   SPI.transfer(0×80);
   delay(3000);
   for (byte i=0; i<30;i++)
    {
       SPI.transfer(i+1);
       delay(3000);
      for(int j=0; j<50;j++)
       {
         SPI.transfer(0x0F);
         delay(3000);
       }
       delay(3000);
       SPI.transfer(0×00);
    }
    delay(3000);
    SPI.transfer(0×00);
  }

As the page Sharp Memory LCD Breakout A2 shows, it seems that you need some additional circuitry to drive the display, such as capacitors and resistors. This is why breakout boards are usually employed. Quoting the page:

  This is a simple breakout board for Sharp’s new Memory LCD displays (
  LS013B4DN02 and LS013B4DN04). It brings all pins to a 0.1″ header and
  provides necessary caps and resistors. The new revision A2 also adds
  an optional boost converter for those wanting to run 5V display from
  sub 3.3V supply.The footprints are there, but parts are not populated
  to save cost. I’ve also added silk labels to the header pins on the
  back. This is an open design under CC BY SA license.

Of course, you can always make your own breakout circuit. For example, you could reproduce the breakout board using a breadboard and some resistors and capacitors. The schematics are provided on that page for A1

and A2

So, in short, either purchase a breakout board, or make one. Once you have done that , you can use the CraftyCoders Arduino Library

Hope that helps.


Problem with my arduino board I had attatched a GSM module to my arduino Uno board. The power had been switched on. The GSM 5V pin was connected to my board. I was still midway with my work so for some reason I gave an external power supply to my GSM module. Now smoke started coming out of my Uno board and a burning smell came from it. I immediately switched off the power supply. But now I am unable to burn sketches to my Arduino. It is showing error: Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
On opening the serial monitor it says: Board at COM3 not detected.

Link from wher I bought the GSM module: http://www.ebay.in/itm/GSM-Module-SIM800-Quadband-better-than-SIM-900-or-SIM900A-Modem-with-SMA-Antenna-/252053758680?hash=item3aaf9322d8

Oops.

You let the Magic Smoke™ escape from your Arduino.  Your Arduino is now somewhat dead.  Depending on what died it may be repairable by replacing components, or it may be beyond resurrection and it'll be easier to buy a new one.

Now - why did it happen?  Looking at the board in your link it should have been OK with the 12V power you provided, since it has its own regulator on board that can supposedly take up to 12V.  So one of two things may have happened:

What you thought was 12V was actually higher than 12V and the regulator didn't cope with it.
You connected the power backwards, so -12V was pumped straight through everything.

There seems to be no polarity protection on the board as far as I can see, and many regulators, if connected backwards, will just pass the power straight through with little or no change to it.  So my money is on having connected the power backwards.  Now, that might not be your fault, since on that site I can see no mention of which polarity the power connector uses - whether it is pin-positive or pin-negative.  The normal way (the way the Arduino board uses) is pin-positive, but that is not always the case.

Either way, the Arduino is now dead, and the GSM module may be dead as well. In fact the whole lot may be dead.


Temperature sensor reading is higher than the actual temperature // Tells the Arduino to read A2 and stores the value in “Vin”
Vin = analogRead (tempSensor);

// Converts the voltage value to temperature and stores it into the “TC” variable (in °C)
TC = 500.0 * (Vin / 1024.0);

The temperature shown is about 50.25°C, sometimes it is showing 36-38°C   degrees, but the actual temperature is about 25-26°C.

Why this is happening?

Code:

Vin = analogRead (tempSensor);
TC=(500.0*Vin)/1023.0;
TF = ((9.0*TC)/5.0)+32.0;
lcd.setCursor(0, 1);
lcd.print(TF);
lcd.print((char)223);
lcd.print("F ");
lcd.print (TC);
lcd.print((char)223);
lcd.print("C");
delay(1000);

Any chance you're printing Vin, and not TC?

500*(50.25/1024) = ~24.5

If not, please post as much of your program as possible


Arduino/Genuino not in board list I've downloaded the Arduino IDE and the Genuino isn't in the list of boards. I'm running Rasbian and used the command line to install.

"Genuino" is just a name, not an identifier. Pick the equivalent Arduino board from the list.


Atlas Scientific pH project - serialEvent3 problems I am trying to get this pH project working and I've noticed that the serialEvent3 never sets the boolean value sensor_string_complete to true.  I am not sure if it is actually capturing the values from the probe.  What I want is for every loop through it should grab a pH value and that is not happening right now.  Most times through the loop the serial3 port is not providing any values.  Here is my code:

String sensorstring = "";
boolean sensor_string_complete = false;
float pH;

void setup() {
  Serial.begin(38400);
  Serial3.begin(38400); // pH stamp
}

void serialEvent3() {                                 //if the hardware       serial port_3 receives a char
  sensorstring = Serial3.readStringUntil(13);         //read the string until we see a <CR>
  sensor_string_complete = true;                      //set the flag used to tell if we have received a completed string from the PC
}

void loop() {
  getPh();
  if (sensor_string_complete == true) readph();
}

void getPh() {
  Serial.println("we are here");
  Serial3.print("r");
  Serial3.print(13);
}

void readph(){
  Serial.println("read ph here");
  if (isdigit(sensorstring[0])) {
    pH = sensorstring.toFloat();
    Serial.println(pH);
  }
  else{
    Serial.println(sensorstring);
  }

  sensorstring = "";
  sensor_string_complete = false;
}

This returns values such as
we are here
we are here
we are here
read ph here
7.0
we are here
read ph here
7.0
we are here
we are here
we are here
read ph here
7.0

I want this to return these values every loop.  I expect to see:
We are here
read ph here
7.0
We are here
read ph here
7.0

Any help on this would be great.  Thanks so much!

On a typical Arduino, the delay between loop() ending and loop() running again is a few microseconds.  Serial.println() in getPh() is interrupt-driven so that call too takes only a few microseconds.  Writing two bytes with Serial3.print() at 38400 bps will take about half a millisecond.  In short, there is plenty of time for loop() to run several times before  serialEvent3() sets sensor_string_complete.

To call  getPh() once and readph() once per loop(), instead of

if (sensor_string_complete == true) readph();

say

while (!sensor_string_complete) {}
readph();

This will stall the loop while the pH sensor takes and reports a reading.

Note, in getPh() instead of using two separate Serial3.print() statements, you can just say Serial3.print("r\r").


Setting up I2C with HTU21D, no response after beginTransmission I'm playing with the temperature/humidity sensor HTU21D. Datasheet: https://www.te.com/commerce/DocumentDelivery/DDEController?Action=showdoc&DocId=Data+Sheet%7FHPC199_6%7FA6%7Fpdf%7FEnglish%7FENG_DS_HPC199_6_A6.pdf%7FCAT-HSC0004

The sensor is properly wired and yields reasonable values if I use the library and example here: https://github.com/sparkfun/SparkFun_HTU21D_Breakout_Arduino_Library/blob/master/examples/SparkFun_HTU21D_Demo/SparkFun_HTU21D_Demo.ino

But I'm more interested in how I2C works, so I'm trying to write a small sketch from scratch to communicate with the sensor. Here is what I have right now:

#include <Wire.h>

#define SensorAddress 0x40
#define SoftReset 0xFE
#define TriggerTemperatureNoHold 0xF3
#define TriggerHumidityNoHold 0xF5

void setup(){

    Serial.begin(9600);
    Serial.println("HTU21D library");

    //delay(50);

    //Wire.beginTransmission(SensorAddress);
    //Wire.write(SoftReset);
    //Wire.endTransmission();

    //delay(50);
    Serial.println("init finished");

}

void loop(){

    Serial.println("entering");
    Wire.beginTransmission(0x40);
    Wire.write(0xF3);
    Wire.endTransmission();
    Serial.println("hello");

    //Hang out while measurement is taken. datasheet says 50ms, practice may call for more
    bool validResult;
    byte counter;
    for (counter = 0, validResult = 0 ; counter < 10 && !validResult ; counter++){
        delay(100);

        //Comes back in three bytes, data(MSB) / data(LSB) / Checksum
        validResult = (3 == Wire.requestFrom(0x40, 3));
        Serial.println(validResult);

    }
    Serial.println("here");
}

I'm in the middle of debugging the sketch. When the sketch is uploaded, I'm reading on the serial connection, and all I can see is:

HTU21D library
init finished
entering

It seems the program hangs on the first communication attempt, when I send the TriggerTemperatureNoHold command.

Could you give me a hand please? I don't understand why it's hanging there.

You forgot Wire.begin();.  You should add it in setup().

Wire.begin(); will configure the IO pins for I2C usage. Without that the signals don't get in or out of the MCU, so I2C functions that wait for an ACK signal never see it and don't complete.


Sending data from txt file over serial connection I'm trying to send data saved on a txt file to arduino over serial connection. I wrote this simple sketch

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

void loop(){
  while (Serial.available() > 0) {
    Serial.write(Serial.read());
  }
}

When I try to send serial data from bash by typing cat input.txt >> /dev/cu.wchusbserial1a1340 while the Arduino's serial connection window is open. It gives an error message "resource busy: /dev/cu.wchusbserial1a1340". Then I tried cat input.txt >> /dev/tty.wchusbserial1a1340. Now it hangs. Bash is busy, and it is not possible close Arduino IDE or serial connection window. What is wrong here?

I don't know the details of why the hang is occurring.  However, the problem stems from serial ports being available to one process at a time.  When the Arduino-environment's serial-port-monitor opens a serial port, that port becomes unavailable to bash.  (To close the hung Arduino IDE process and the SPM, say ps aux |grep arduino and kill n, where n is the PID shown by the ps and grep.)

Here is a python program you can run, that sends and receives data:

#!/usr/bin/env python
# Send data to an Arduino and report responses.
from time import time, sleep, asctime, localtime
from serial import Serial
print 'Opening serial port'
ser = Serial('/dev/ttyACM0', 9600, timeout=3)
sleep(1)                      # Let board initialize
while 1:
    txt = 'It is about ' + asctime(localtime()) + ' now'
    print 'Sending  "{}"'.format(txt)
    ser.write(txt)
    s = ser.readline()          # Get result from arduino
    print 'Readback "{}" at {}'.format(s, asctime(localtime()))
    sleep(1)

Here is some sample output from it, with your sketch runing in a Mega2650.  (I'm not sure why the readback is taking so long as it apparently is.)

Opening serial port
Sending  "It is about Fri May  8 16:48:41 2015 now"
Readback "It is about Fri May  8 16:48:41 2015 now" at Fri May  8 16:48:44 2015
Sending  "It is about Fri May  8 16:48:45 2015 now"
Readback "It is about Fri May  8 16:48:45 2015 now" at Fri May  8 16:48:48 2015
Sending  "It is about Fri May  8 16:48:49 2015 now"
Readback "It is about Fri May  8 16:48:49 2015 now" at Fri May  8 16:48:52 2015
Sending  "It is about Fri May  8 16:48:53 2015 now"
Readback "It is about Fri May  8 16:48:53 2015 now" at Fri May  8 16:48:56 2015


Control many devices via Wifi I have one Arduino and I want to control a Servo motor and other devices. The Servo motor is further away from the Arduino so I want to control it wirelessly. The problem is that I want the Servo to communicate to the Arduino, which in turn communicates to me via wifi, text message, website, etc. I'm guessing I would need two esp8266 chips, one connected to the Servo and one connected to the Arduino. I would also like the other devices to communicate to be via wifi, text message, website as well which are connected to the arduino wired.

Yes, I agree with @Paulo Soares to use 2 Arduinos.

It makes little sense to make the 2nd wireless jump between the 2 Arduinos using a complex packet protocol such as TCP/IP.  This project uses 2 Xbee radios.  I suspect it is also possible to accomplish this using COTS model airplane radio.  This may be talked about here but it is not clear if the hardware talks to existing R/C hardware or to proprietary hardware.


What is the point of D0-D3 on LCD? The Arduino LiquidCrystal library has 4 constructors with different arguments:

LiquidCrystal(rs, enable, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d4, d5, d6, d7)
LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)

The following comments are stated for the constructor arguments:

  [...] d0, d1, d2, and d3 are optional; if omitted, the LCD will be controlled using only the four data lines (d4, d5, d6, d7).

What is the point of d0-d3 if they are not needed? Will they decrease the response time?

That type of LCD has two main modes of operation: 4-bit mode which uses 4 data pins (d4-d7), and 8-bit mode which uses all 8 data pins (d0-d7).

4-bit mode has the advantage of requiring fewer output pins on your Arduino. However, it means your sketch needs to send each command/character as two separate batches of 4-bits (one after the other). This is handled for you automatically by the LiquidCrystal library, so you won't need any extra complexity in your code. However, it does mean that your sketch requires roughly double the number of processor cycles to send anything to the LCD.

In contrast, 8-bit mode sends each command/character as a single batch of 8-bits. That simply means it technically runs a little faster.

With that said, a person looking at the display probably won't see a significant speed difference most of the time, as it still goes very quickly. The main impact will be on the microcontroller (the Arduino in this case). If it can use the faster 8-bit mode then it can devote a little more processing time to other things. That can be particularly helpful for timing-critical applications.


How can I remove the delays in this code for sweeping the servo? I know this is probably a very asked question, but I am building a fairly basic radar type thing which sweeps left and right and uses an ultrasonic sensor to determine the distance to an object and a buzzer is set off if something is detected.
The device itself works  but I've noticed that because I have used delay() to allow the servo to complete its full movements, it is holding up the rest of the code, and as a result the buzzer and returning of the distance is extremely unresponsive and sluggish.
So far I have looked at simply returning a value whenever the motor reaches a certain step but it doesn't achieve exactly what I'm looking for, and I have looked into using millis() for timing asynchronously, but I'm struggling to wrap my head around it a bit in terms of how it will work for a servo.
My current working but sluggish code:
//Servo Stuff
#include <Servo.h>
int servoPin = 12; // Pin for interacting with servo defined
int servoStart = 0; //Starting position of servo motor
int servoEnd = 90; //End position of servo means it rotates 90 degrees
int waitTime = 1000; // Allows servo to fully rotate before moving again
int servoPos = 20; // For incrementing the position of the servo
int servoStep = 20; //amount to increment servo position by
Servo myServo; // Creates an instance of a servo object

//Ultrasonic stuff
int trigPin = 9;
int echoPin = 10;
long duration;
int distance;
int maxDistance = 329; // The max range of the ultrasonic sensor

//Buzzer stuff
int buzzerPin = 11;
int buzzerWait = 200;

void setup(){

//Attach the servo object to the pin and begin serial monitor with
// polling rate of 9600
Serial.begin(9600);
  myServo.attach(servoPin);
  pinMode(buzzerPin, OUTPUT);

    pinMode(trigPin, OUTPUT); // Trig pin set as output
    pinMode(echoPin, INPUT); // echo pin set as i
      }

    void loop()
    {

      // Moving servo
      myServo.write(servoStart); //Moves servo to the starting pos
      //delay (waitTime); //allows servo to fully move before next move
      //myServo.write(servoEnd); //Moves to end position
      //delay (waitTime); // waits before reverting back to start pos

    //myServo.write(servoStart);
    //delay(waitTime);
    //myServo.write(20);
    //delay(waitTime);
    //myServo.write(40);
    //delay(waitTime);
    //myServo.write(60);
    //delay(waitTime);

     // Using ultrasonic sensor

      // Clears the trig pin
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);

    // Sets the trigPin on HIGH state for 10 microseconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

    // reads echoPin and returns the travel time of the wave in microseconds
      duration = pulseIn(echoPin, HIGH);

    // Calculating distance
      distance = duration*0.0343/2;

    //Prints the distance to the Serial Monitor
      Serial.print("Distance: ");
      Serial.println(distance);
      Serial.println(distance);

      if (distance < maxDistance) {
      digitalWrite(buzzerPin, HIGH);
      //delay(buzzerWait);
      //digitalWrite(buzzerPin,LOW);
      //delay(buzzerWait);

      }else digitalWrite(buzzerPin, LOW);

    }

Any pointers to some good resources for this would be very appreciated, thanks.

From your code it seems like you are doing all the servo movement before you read the distance and report back. A lot of code is commented out, so it's a bit difficult to follow. What I would do is something along the line of:
[...]
int servoStart=0;
int servoEnd=90;
int servoPos=0;

[...]
void setup() {
    [usual setup stuff like you do it now]
    myServo.write(servoPos);  //start at pos 0
    // Maybe a delay here to make sure we are at pos. 0
}

void loop() {
    //Switch direction if we reach end
    if (servoPos+servoStep < servoStart || servoPos+servoStep > servoEnd)
        servoStep = -servoStep;
    servoPos += servoStep;
    myServo.write(servoPos);
    //Small delay?
    //Read distance
    //Send distance to seraial
    //Buzz buzzer if needed
}


Can I simulate a clock without an RTC connected? I want to program for a timer that works as set timer such as in an oven where user can set their own time. One of the way I know is using an IC(RTC) for the timer. However, I don't have the IC yet only the coding and Arduino.

Is it possible to simulate the Arduino code without having the RTC? Or is there any electrical component that I can use to replace the IC for the time being?
Thank you for your help and comment.I really appreciate that.

TimeLib.h has a virtual clock that can be updated and corrected from multiple sources, including an RTC chip or an NTP server on the internet (assuming an internet connection).

It doesn't need that clock source, though, but it will drift with time. Once you have set the clock correctly it will keep close to the right time (assuming no reset or power loss of the Arduino). Not perfect (because the Arduino's main clock isn't perfect) but close enough for many simple applications.


Not receiving data from NRF24L01 I'm trying to send data from one Arduino board to another using NRF24L01 connect to the two ends of the two Arduino boards. The Tx blinks in the transmitting end(Arduino board 1) but the receiving end(Arduino board 2) is not getting any value from it. Here is my code.

Transmitting end (Arduino board 1)

#include <SPI.h>
#include "RF24.h"

RF24 myRadio(0, 1);
byte addresses[][6] = {"0"};

struct package
{
    int id = 1;
    float longitude = 0.0;
    float latitude = 0.0;
    char text[100] = "Geographic coordinates";
};

typedef struct package Package;
Package data;

void setup()
{
    Serial.begin(115200);
    delay(1000);
    myRadio.begin();
    myRadio.setChannel(115);
    myRadio.setPALevel(RF24_PA_MAX);
    myRadio.setDataRate(RF24_250KBPS);
    myRadio.openWritingPipe(addresses[0]);
    delay(1000);
}

void loop()
{
    myRadio.write(&data, sizeof(data));

    Serial.print("\nPackage:");
    Serial.print(data.id);
    Serial.print("\n");
    Serial.println(data.longitude);
    Serial.println(data.latitude);
    Serial.println(data.text);
    data.id = data.id + 1;
    data.longitude = data.longitude + 0.1;
    data.latitude = data.latitude + 0.1;
    delay(1000);
}

Receiving end (Arduino board 2)

#include <SPI.h>
#include "RF24.h"

RF24 myRadio(7, 8);
struct package
{
    int id = 0;
    float longitude = 0.0;
    float latitude = 0.0;
    char text[100] = "empty";
};

byte addresses[][6] = {"0"};

typedef struct package Package;
Package data;

void setup()
{
    Serial.begin(115200);
    delay(1000);
    myRadio.begin();
    myRadio.setChannel(115);
    myRadio.setPALevel(RF24_PA_MAX);
    myRadio.setDataRate(RF24_250KBPS);
    myRadio.openReadingPipe(1, addresses[0]);
    myRadio.startListening();
    delay(1000);
}

void loop()
{

    if (myRadio.available())
    {
       while (myRadio.available())
       {
           myRadio.read(&data, sizeof(data));
       }
        Serial.print("\nPackage:");
        Serial.print(data.id);
        Serial.print("\n");
        Serial.println(data.longitude);
        Serial.println(data.latitude);
        Serial.println(data.text);
    }

}

This is how i connected the Arduino and NRF24L01

Any reason why im not getting the the data from the transmitting end?

Check the reading and writing pipe addresses.

First, the default is 0xE7E7E7E7E7 for pipe 0 (RX_ADDR_P0) and 0xC2C2C2C2C2 for pipe 1 (RX_ADDR_P1), see the data sheet.  Check that the transmitter (TX) address is the same as the receiver
(RX) pipe address.

Secondly, you should not set the pipe address to 0x0 even if that's common between the TX and RX.  This note comes from the data sheet:

  Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in
  noise and can give a false detection, which may give a raised Packet Error Rate. Addresses
  as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate


How do I use an AtTiny85 (or other AtTiny) with Arduino? Please mind that this is an "example" question.

How to make a "tiny arduino"?

I've ordered a bunch of ATtiny85's off E-bay, they're like tiny Arduino's.

I've set up the latest Arduino IDE and would like to run the blink example.

My process so far:

Wiring

Code

(The blink example)

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

1. The Tiny

The ATtiny differs a little from the Arduino, don't expect it to be "fully compatible". It's a microcontroller which is just a part of an Arduino and not a full Arduino itself.

It's more of a device for "advanced users" and gives some more flexibility (at cost of usability). You can easily add this microcontroller on a breadboard, since putting a full Arduino on a breadboard makes little sense.

1.1 USB?

Since the ATtiny is a microcontroller (like the ATmega on an Arduino) and not a development board (as an Arduino), it does not have an USB connector.
The ATtiny series also does not have hardwareUART (Rx/Tx). The

You'll have to take care for a steady power-supply to your Microcontroller and the programming will be a little more tricky (details further below).
It is however possible to use SoftwareSerial and a customized bootloader. My ATtiny85 runs software serial with 115200 fine, though I have found a post which states that the internal oscillator should be tuned for a reliable connection.

1.2 RAM/program memory

The ATtiny has less RAM and program memory. This essentially means your program can't be as 'big' as on a normal Arduino. It also means that you can't use as much variables. A program for the tiny should be "small" or very efficient.

1.3 "Speed"

My ATtiny came with 1Mhz internal clock set, but if you change the fuse bits you can make it run at 8Mhz. An standard Arduino has a 16Mhz clock on the board. So your code would run 16x slower on default and 2x slower on "max". You could use an external clock for the ATtiny, but that eats up 2 pins.
The cool thing is, when you set it to 1Mhz it can run on about 2.7V (check datasheet first).

Arduino                   16Mhz
ATtiny (standard)         1Mhz
ATtiny (set fuses)        8Mhz
ATtiny (external crystal) up to 20Mhz

Higher Mhz is faster. Keep in mind that 1Mhz is roughly 1000000 instructions per second, which is still blazingly fast and good enough for most occasions, especially on such a tiny device.

2. Programming the Tiny

Most of the ATtiny's don't come with a customized (software serial) Arduino bootloader. This essentially means that you have to burn a custom bootloader by yourself or use another type of programmer. You should really watch the video from Ben Heck. He explains that Arduino boards have an USB converter on board and have custom code that is able to "bootload" your Arduino. But that ICSP/ISP programmers are used to upload programs without a bootloader/uart connection.

2.1 The programmer

You've got a load of options, check the "Programmer" item in the "tools" tab in your Arduino IDE. I'm using an USBasp which can be bought on ebay for as little as 3€. You should get one that has a selectable voltage (3.3V and 5V).

(If your ATtiny85 already has the bootloader, which is unlikely, you can use the software rx/tx pins for uploading)

2.2 Preparation

Check your microcontroller if it really is a ATtiny85 my E-bay reseller actually had one ATtiny45 included, which lead to an "error" when trying to upload.

The Arduino IDE does not know the "ATtiny board" so you can't select it easily. You'll have to let the IDE know that the ATtiny can also be programmed.

I found a very nice tutorial that describes how to do this.

  Open the preferences dialog in the Arduino software. Find the
  “Additional Boards Manager URLs” field near the bottom of the dialog.
  Paste the following URL into the field (use a comma to separate it from any URLs you’ve already added):
  https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json
  Click the OK button to save your updated preferences.
  Open the boards manager in the “Tools > Board” menu.
  Scroll to the bottom of the list; you should see an entry for “ATtiny”.
  Click on the ATtiny entry. An install button should appear.
  Click the install button. The word “installed” should now appear next to the title of the ATtiny entry.
  Close the boards manager. You should now see an entry for ATtiny in the “Tools > Board” menu.

2.3 Changing the internal clock

Some interesting post I found told me that you can change the internal clock/oscillator to 8Mhz by selecting 8Mhz (internal) as the clock and pressing the "Burn bootloader" button. This won't flash a bootloader (since that makes little sense on a Tiny85) but does change the fuse-bits.

2.4 Code

You'll not get away with the standard blink tutorial. It uses digital pin 13 (the tiny only has 8 pins).

Mind that you might have to upload using Ctrl+Shift+U (or sketch->Upload with programmer).

I used the diagram below to check the pins (from highlowtech.org)

3. Hardware

Your "schematic" isn't complete, I don't see a way to program or power the microcontroller. And you might want to take some precautions.

I personally think a well-drawn schematic looks better as a "breadboard view".

The 10Kohm pull-up resistor on the reset pin is not 100% neccesary according to the datasheet. But the Uno has one in it's reference design (which I use as a reference).

There are two capacitors, one "big" capacitor as a reservoir. If one device suddenly pulls a lot of current, this capacitor will handle that. The smaller decoupling capacitor will damp the noise of other IC's or switching supplies. It may work withouth these, but your circuit will be more reliable with them.
Mind that the decoupling capacitor should be (physically) close to the IC.

You can power the board through the programming header, but mind that you'll need a smooth voltage between (most likely) 3.3V and 5V. If you want to power it with a bigger voltage (9V battery) then you'll need a voltage regulator.


Servo motor with 9V battery I'm using servo motor in my Arduino based project, I've tried to provide servo with external power supply, So I've used 9v battery with IC7805 to step down to 5v,  but the motor is not working, so what should I do? FYI: I used the same battery with IC7805 to power IR proximity sensor which works fine.

A 9v "transistor" battery is unsuited to powering servos - at best it might work very briefly.

Use 4 alkaline (or depending on the servo ratings, perhaps 5 rechargeable) AA or AAA cells to power the servo.

Either power your Arduino from something else, or get a 3.3V version that you can operate from a low dropout regulator on the 4 or 5 cell pack.

A 7805 has a high dropout voltage and is out of place in a battery powered system.


How to get number of available pins in code? Different boards have different number of pins.

Is there a way to know this number in code (at least digital and analog pins), or do I have to determine board type (like in this thread) and know the number of pins by myself?

Reasoning for this is that I'm creating prototype using Uno and using 2-3 analog pins for temperature readings, but I want to be able to use the same code for different board in the future with eg. 8 analog pins, so I don't have to remember to change pin numbers in code and maybe solder it convenient way etc. Also being able to use for eg. "last available analog pin" for certain job could help keep code/schematics nice and clean.

It is quite easy actually:

Serial.print("number of digital pins: ");
Serial.println(NUM_DIGITAL_PINS);
Serial.print("number of analog inputs: ");
Serial.println(NUM_ANALOG_INPUTS);

Note that these are compile-time constants defined as macros in a file
named pins_arduino.h. There is one such file for every board supported
by the Arduino environment. Just to take Curt J. Sampson's example, if
someone “made a board with an MCU with 100 digital IO pins available,
yet if only ten of these are brought out to pins on the board”, then the
macros would tell you you have 10 digital pins. Assuming of course that
you installed the proper support package for that particular board.


Please help me read this Schematic Diagram So, i'm trying to build an Obstacle Avoiding Robot by refering this site "Robot Obstacle Avoiding Car
On the website they have provided with very poor Circuit Diagram.
Please help me read the positions of capacitors.
I have completed connection of all other components.

Help would be appreciated

They are not poorly described.

All capacitors need to be put from the VCC to GND directly (this will not cause a shortcut).

The left 3 are related to the motor; as it uses a lot of current, it can take the current from the capacitors instead of flowing all the way to the power supply, causing problems of a voltage reduction that can cause other components to fail (temporarily).

The middle two are for the ultrasonic sensor as it also uses some current.
0.1 uF capacitors (the one for the ultrasonic sensor) is typically used for ICs and are called bypass capacitors. These needs to be placed as close as the VCC of the IC (in this case ultrasonic as possible).

And the right two for the power supply itself to remove noise/ripple.

For all capacitors, place them close to where the power is needed (for the motor/ultrasonic) and for the power supply close to the VCC input.

EDIT

Below I added the capacitors for the motor, sorry for using MS paint, having no better option right now. I assume the two red wires from the L293D other than going to the breadboard are the 9V lines (VDD).

Also don't put the capacitors in the same pin as the L293D IC pins, but I didn't want to obfuscate the picture. This might destroy your breadboard or IC pins as there is too less space for both.


Servo causes disconnection I've only started using Arduino in the last week, and I'm having a problem with the servo supplied with the kit I purchased. It's a SG90 microservo. I'm trying to connect the servo as shown on the Arduino tutorial site:

But when I connect the power and ground pins to the board, the board powers down and disconnects from the USB. I've had the servo working before without a problem.

Yesterday I was trying out another tutorial without any luck, and I noticed the servo getting hot (not too hot to touch though).

Could I have accidentally fried the control board in the servo?

Have a look at the current requirements of the SG90 and compare this to the maximum current available from an Arduino Uno.

Another thing to look at is how much current your computer's USB port can supply. My laptop, for example, can only supply 500mA per USB port.

My advise is to use a separate 5V power supply for the servo.


What is this component? (range finder) I've taken apart an old range finder (see photo here). It uses a circular, seemingly gold-plated, two-wire sensor that I'd like to re-use in an Arduino project.
I'm looking for a datasheet of the sensor and/or a circuit-diagram. Any help is welcome.

The big circular parts likely is ultrasonic transducer as used in instant camera.

http://www.uoxray.uoregon.edu/polamod/

https://www.google.com/?gws_rd=ssl#q=polaroid+ultrasonic+ranging+module&revid=399558007&safe=off

Working principle is same as modern unit, easily available at a few US dollars. The transducer does NOT work by itself, needs the associate PCB to work.


AccelStepper Library: How do I go to a position without decelerating? When I make the motor move at a certain distance with setMaxSpeed(), setAcceleration(), and moveTo(), it always accelerates and decelerates. Is there a way to disable the deceleration?

AccelStepper, as hinted by the name, uses acceleration always. By setting the acceleration high, you reduce the amount of time spent accelerating to the set speed.

setAcceleration() sets the rate in steps per second per second. If your MaxSpeed is 200 steps per second, then setting the acceleration to 200*10 means all acceleration is over in 1/10 second. You can go higher, etc.