everything works independitly but not together. Piezo not generating a tone My goal with the code is simple. Let the Piezo buzz when temperature reaches 25 degrees. My piezo is hooked up correctly, because It makes a buzz when the arduino boots or when I put this line of code anywhere else in my code.

I also checked if the If statement was called. And yes it is! So the if statements is happening yet I don't hear a buzz.

I am aware that I am breaking my seven segmented screen by using the delay. But I don't mind the screen working when the buzzer is.

void loop()
{
  //local vars
  if (millis() % 5000 <= 10) {
      float lm35TempC = lm35.getTempC();
      sevseg.setNumber(lm35TempC, 2);
      if (lm35TempC > 25.00) {
        tone(1,500,1000);
        delay(3000);  <------- WHERE IT PROBABLY GOES WRONG
      }
      if (lm35TempC < 25.00) {
        noTone(1);
      }
  }
  sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
}

To conclude: The If-statement is working yet I don't hear a buzz. How does this happen?

Thanks in Advance!

You connected the piezo to pin 1? Chose other pin. Pin 1 is Serial TX. You 'pump' PWM to USB.

tone() function will make sound no matter if you have a delay there. You set 1 sec with 1000 as third parameter. It will sound 1 sec and the turn of. You do not need the delay() and noTone().

500 is low frequency. If it sounds only one second, can you catch it?

try tone(TONE_PIN, 4500, 500). with speaker it is a nice beeeep


Pointer to Hardware Differences Documentation For Arduino Boards? I hope this question isn't overly broad although it is more of a search for consolidated information.

BACKGROUND:

I am new to the Arduino universe and am drawn in by the open hardware concept. After years of doing electronics projects with PICs, I have tired of iterative hardware prototyping and DIY printed circuit construction for small one-off projects. The lure of buying off-the-shelf hardware and doing minimal wiring on protoboards / shields is a powerful concept that I welcome.

The availability of the hardware from multiple sources (and it seems multiple designers) does present a small problem I have discovered. There appear to be small but important differences between Arduino boards from multiple sources.

As an example, I have found that the hardware PWM isn't always the same from one Arduino Board design to another. I find that the arduino.cc pages (including the Forums) appear to indicate that hardware PWM runs at about 487 Hz. However, my testing shows that on the Arduino 101, two of the four hardware PWM outputs run at 487 Hz while the other two run at 975 Hz. I did not find such details when researching board choices and comparisons. I am assuming that this difference may also exist on other board designs although I have only Uno, 101, and Mega2560 boards to play with at the moment.

A second example is that for at least the Arduino Uno and Arduino 101 board I have, the DC power input jack is 5.5mm/2.1mm, a very common size. However, the Arduino Mega2560 I have (third party) uses a 5.5mm/2.5mm DC input jack -- a standard albeit less common size.

Another difference is the well known differences in (TTL) RS232 port interface chips used. At least these are generally made known and documented so that you can plan in advance for differences that may or may not affect you.

Finally, I have found that on the Arduino 101, plugging in or unplugging (or turning on or off) DC power at the DC input jack (or Vin pin) forces a reboot of the Curie module on the board. I think this is caused by the use of the power management chip and power switching circuitry on the board. The Mega2560 does not show this reboot behavior whenever DC power is changed. (This reboot happens even if the USB source remains connected at all times.)

These sorts of minor differences can affect the choice of board one makes for a given project -- especially, if you develop an application on one board and plan to deploy it on another. (Example: develop on a Mega2560 yet intend on deploying on a Uno later to save cost.)

QUESTIONS:

1) Has anyone come across a Website / page that details many of the minor design differences between Arduino boards?
[Edit] I should have used the word designs rather than boards in this question. I realize each vendor may have tweaks to a board but was more interested in detailed differences in the "official" design. Things like above would be interesting to know -- does the board reboot on application of DC input power? Are all PWMs running at the same default frequency, etc?

2) Are there any Web resources that might at least list other "oddities" with the different board choices? (i.e. PWMs at frequencies other than 487 Hz)?

Any pointers would be much appreciated.

You may find this helpful: PTD0001 Arduino Comparison Rev 0 - PDF - 245 KB.

Screenshot of above:

Credit: Payne Technologies Limited

That compares some models in a way you might find useful.

  I have found that the hardware PWM isn't always the same from one Arduino Board design to another

The PWM frequencies can be changed over quite a wide range. I have a page about timers which describes a lot of their features.

According to the Arduino reference page about analogWrite:

  The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.

By changing the hardware register you can change those frequencies. The frequency of 980 Hz is because of the compromise needed to get an approximate 1 ms interrupt for use by the millis() function:

16e6 / 64 / 256 = 976.5625 Hz

In other words the clock speed of 16 MHz is prescaled by 64 and then counted to 256, giving that frequency.

Note that this is almost 1 ms. The code behind millis() and micros() functions compensates for that so that you get a reasonably accurate result.

By changing the prescaler, and "count to" point you can get lots of other frequencies. However if you do that to Timer 0 on the Uno (and similar boards) then you will throw out the calculations for the millis() and micros() functions (you can compensate for that, of course).

This only partly answers your question, but hopefully will provide a nudge in a useful direction.


Arduino Nano -- cannot download, no /dev/tty*** device It appears to me that each Arduino has (should have?) a unique /dev/tty...USB... number assigned. Why this isn't explained anywhere (that I can find) is a mystery. When I plug my problem Nano into a USB port on my iMac no /dev/tty... for it appears. It used to work. Have I fried it? Can this be fixed?

This is probably a duplicate question and duplicate answer, but ...

Flip the board over, look at the bottom. If it says "FTDI" then this answer doesn't apply. But many cheap clones have moved to the CH340G chip for USB serial communication, it's a tenth of the cost with a tenth of the (unused) features.

You can find CH340/341 drivers from the manufacturer at WCH.CN or linked at the bottom of this post.

Or, skip the USB altogether and search for "ISP" on Tindie and grab a USBASP or TinyISP programmer.


What do I do about a compiler error " variable 'font' must be const" I am trying to run the test program from Adafruit, with their libraries, for an Arduino controlling a Nokia5110 display and get this error message:

Arduino: 1.5.8 (Linux), Board: "Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz)"

    /home/Harry/Arduino/libraries/Adafruit_GFX/glcdfont.c:9:23: error: variable 'font' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
     static unsigned char  font[] PROGMEM = {
                           ^
    Error compiling.

Please can anyone explain this? I can happily give more details, but I am not yet sure how much is needed and the files are rather too long to include them all at this stage.

The problem is you're using an old version of the Adafruit GFX Library, which was written for a previous version of the Arduino IDE. You just need to install the latest version of the library and your problem will be solved:

Download https://github.com/adafruit/Adafruit-GFX-Library/archive/master.zip
Unzip the downloaded file.
Rename the unzipped folder Adafruit_GFX
Replace /home/Harry/Arduino/libraries/Adafruit_GFX with the folder.

If you run into any other problems after doing that I recommend trying the latest version of the Arduino IDE. The version you're using is very outdated.


Cannot control servos through 32-servo-controller on Aurduino Duamilanove I have servo (TowerPro sg90) connected to 32 servo controller (this one) through UART interface (RX-TX, GND-GND).
Seller provide documentation how to connect and control my servos, but it isn't work.

Servo work if I connect it indirectly to Arduino. Controller indicate that it is working too (photo below - red led).

I already try different servos. Also try use provided software to control servos from pc through Mac/PC. But it's interface is unreadable for me. I tried different options but servos not responding.

Sketch code below (from sellers examples):

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

void loop() {
  Serial.print("#3P500T2000\r\n");
  delay(2000);
  Serial.print("#3P1500T2000\r\n");
  delay(3000);
  Serial.print("#3P2500T2000\r\n");
  delay(2000);
  Serial.print("#3P1500T2000\r\n");
  delay(2000);
}

Photo of my connections:

Sorry if it post duplicate some, but I cannot google this problem.

There is one connection missing - the one that powers the servo and board.

At the moment your servo board is getting a small amount of power through the RX pin - disconnect it immediately, you are damaging it.

You need to provide +5V to the +5V terminal block, and also a suitable voltage (+5V should do) to the VCC on the terminal block.


Arduino Uno + 2 Monster Motor Shields I've got an Arduino Uno and two Sparkun's Monster Motor Shields.
The aim is to control 4 motors.

There is no problem to control 2 DC motors with single motor shield. There's a manual on how to do it .

But how can I control all of motors (address commands to each of them) when I stack motor shields one on one?

Thanks in advance.

Not really the answer to your question, but an alternative solution, which has proven to work in my case.
We were working on a line-following robot with an ATMega 328P (Same as arduino, but withouth shields) and thus we wired an shield directly. For the shield we used, we only needed 4 inputs (pwm left, pwm right, direction left, direction right). Try to find out what your shield is using, on which pin, and you can drive the shield directly withouth stacking them (as they then would use the same pin).

My alternative solution would be to use 1 driver. And wire the motors parrallel.
If you choose to use 1 shield, you can stack it. But for other shields you have to check which pins to use. There is no drawback on using one shield, the only thing is that the motor driver will draw more current, but they're basically designed for this.


Arduino Mega 2560: Busted Atmega 16U2 I just bought an Arduino Mega2560 R3 and it doesn't connect to my Laptop. The connection is somewhat random, sometimes it connects and sometimes it doesn't.

Can someone help me identify whats the problem?

When it gets connected I can upload sketches.

I would like to remove the Atmega 16U2 and replace it with ftdi USB to Serial, would it be possible?

You can use your USB/Serial adapter to program the 2560 as the Arduino uses the 16u2 as the same thing to program the mega. You shouldn't remove the 16u2, just wait till you get the programmers and reflash the 16u2 with its firmaware and it will work, I actually had the same problem where the DFU didn't work and the 16u2 stopped responding, after reflashing the firmware it worked. The firmaware can be found under(as of 1.6.0):

...\Arduino\hardware\arduino\avr\firmwares\atmegaxxu2\MEGA-dfu_and_usbserial_combined.hex

You need to connect the Serial pins on the FTDI and Mega in the below fashion:

 FTDI           MEGA
 GND<----------->GND
 CTS<----------->GND
 VCC<----------->VCC
 TXD<----------->RX0
 RXD<----------->TX0
 RTS/DTR<---||-->RST

The Capacitor between the DTR pin and RST pin are needed this should be 100nF.

  I have bought an I |SP programmer but it will take 3 weeks to reach and no I dont have another arduino, TBH I'm scared to buy another one... –  echo_salik

If you are buying clones, those will more than likely give issues as they will be cutting back on costs in places, i.e. QC checks.


How do I use 2 ultrasonic sensors to control a 5v motor? I've hooked up two ultrasonic sensors to my breadboard and I also got a 5v motor installed. I also got the diode installed and the usual set up. I can easily control the motor with one sensor.

But what I'm trying to do is I want the motor to run at let's say 100 once I start it up:

The first sensor should be used to slowly slow down the motor when an object is placed in front of it
The second sensor should be used to slowly speed up the motor when an object is placed in front of it

I do not want the speed to return to 100 once the object is removed. It should remain at the same speed according to which sensor was used. (Tell me if I have to clarify anything in the comments)

Code

int motorPin = 9;
int trigPin = 13;
int echoPin = 12;
int trigPin2 = 5;
int echoPin2 = 4;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(motorPin, OUTPUT);
}

void loop() {
  int duration, distance;
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (1000);
  digitalWrite (trigPin, LOW);
  duration = pulseIn (echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance < 20) {  // Distance from sensor
    analogWrite (motorPin, 50);
  } else {
    int duration, distance;
    digitalWrite (trigPin2, HIGH);
    delayMicroseconds (1000);
    digitalWrite (trigPin2, LOW);
    duration = pulseIn (echoPin2, HIGH);
    distance = (duration/2) / 29.1;
    if (distance > 20) {  // Distance from sensor
      analogWrite (motorPin, 150);
    }
    if  (distance > 20) {  // Distance from sensor
      Serial.println("Out of range");
    } else {
      Serial.print(distance);
     Serial.println(" cm");
    }
    delay(500);
  }
}

This is very simple using the map() instruction. Here's the code you would use (feel free to modify values:

int speed = 112 + map(distance, 0, 20, 0, 112) - map(distance2, 0, 20, 0, 112);

So if both sensors gave equal values, they would offset each other. To make it still work if an object is removed, you could just use the last distance/distance_2 value and update the other.

One issue with this approach is, if the line of transformation of the object is not perpendicular to the line of the pings, the value will go:

  10 → 11 → 12 → 13 → 14 → 15 → 16 → 17 → 18 → 19 → 20 → [Out of range]

I've added some pretty animations to show you what I mean:

Perpendicular:

Collinear:

As I understand, this is what you want:

int motorPin = 9;
int trigPin = 13;
int echoPin = 12;
int trigPin2 = 5;
int echoPin2 = 4;
int postdist = 112;
int postdist2 = 112;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(motorPin, OUTPUT);
}

void loop() {
  //First Read
  int duration, distance;
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (1000);
  digitalWrite (trigPin, LOW);
  duration = pulseIn (echoPin, HIGH);
  distance = (duration/2) / 29.1;
  int ltol = postdist - 5;
  int htol = postdist + 5;
  if (distance > 20 || !(distance > ltol && distance < htol)) {  // Distance from sensor
    Serial.println("Out of range");
    distance = postdist;
  }
  //Second Read
  int duration2, distance2;
  digitalWrite (trigPin2, HIGH);
  delayMicroseconds (1000);
  digitalWrite (trigPin2, LOW);
  duration2 = pulseIn (echoPin2, HIGH);
  distance2 = (duration2/2) / 29.1;
  int ltol2 = postdist2 - 5;
  int htol2 = postdist2 + 5;
  if (distance2 > 20 || !(distance2 > ltol2 && distance2 < htol2)) {  // Distance from sensor
    Serial.println("Out of range");
    distance2 = postdist2;
  }
  //Math:
  Serial.print("Distances-1: ");
  Serial.print(distance);
  Serial.print(" cm 2: ");
  Serial.print("Distances-1: ");
  Serial.print(distance2);
  Serial.println(" cm");
  postdist = distance;
  postdist2 = distance2;
  int speed = 112 + map(distance, 0, 20, 0, 112) - map(distance2, 0, 20, 0, 112);
  if(speed < 60) {speed = 60;} //Modify 60 to meet your needs for minimum threshold
  analogWrite (motorPin, speed);
  Serial.print("Motor Speed: ");
  Serial.println(speed);
  delay(500);
}

Changelog: forgot to edit postdist/postdist2 at end of cycle, added minimum threshold, prevent very small changes in voltage to keep voltage stable and prevent noise.


multiple relays not triggering correctly quick description of the sketch: its a clap on/off relay that turns on only when it's dark.

Cannot seem to get the relays to stay off. What happens is they are off by default then when I do the double clap to turn them on that works, after this I double clap to turn them off and then go off then immediately go on again. I can get a single relay to work perfectly but when I uncomment the rest there seems to be a problem.

I am assuming it has something to do with the delay for the clap sensor, but I am not entirely sure-- I have tried quite a few things to try to resolve it but am really lost as to why this might be happening. ideas?

int soundSensor = A2;
int relay = A0;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
int claps = 0;
long detectionSpanInitial = 0;
long detectionSpan = 0;
boolean clapState = false;
int doubleClap = 0;

//Light sensor
int photocellPin = A1;
int photocellReading;
int LEDbrightness;

//int delayValue = 100;
int photoSensor = 0;

void setup() {
  pinMode(soundSensor, INPUT);
  pinMode(relay, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  /////////////
  // photo sensor
  ////////////////////
  photocellReading = analogRead(photocellPin);
  photocellReading = 1023 - photocellReading;
  LEDbrightness = map(photocellReading, 0, 1023, 0, 255);

  if(photocellReading > 500){
      photoSensor = 0;
  }
  if(photocellReading < 500){
    photoSensor = 1;
  }

  /////////////
  // clap sensor
  /////////////////////
  int sensorState = digitalRead(soundSensor);
  //erial.println(sensorState);
  if (sensorState == 1)
  {
    if (claps == 0)
    {
      detectionSpanInitial = detectionSpan = millis();
      claps++;
    }
    else if (claps > 0 && millis()-detectionSpan >= 50)
    {
      detectionSpan = millis();
      claps++;
    }
  }

  if (millis()-detectionSpanInitial >= 500)
  {
    if (claps == 2)
    {
      if (doubleClap == 0)
        {
          doubleClap = 1;
        }
        else if (doubleClap == 1)
        {
          doubleClap = 0;
        }
    }
    claps = 0;
  }

  if(doubleClap == 1 && photoSensor == 0){
    digitalWrite(relay, LOW);
    digitalWrite(relay2, LOW);
    digitalWrite(relay3, LOW);
    digitalWrite(relay4, LOW);
    Serial.println("off");

  }
  else{
    digitalWrite(relay, HIGH);
    digitalWrite(relay2, HIGH);
    digitalWrite(relay3, HIGH);
    digitalWrite(relay4, HIGH);
    Serial.println("on");
  };

}

As it happens, you are debugging in the dark.  You have half a dozen devices attached to (presumably) some Arduino, driven by some hard-to-read code that might not work properly even if all the devices work ok, and definitely won't work properly if any of them fail or are incorrectly attached.

For example, you can't tell from that code whether your photoSensor works, whether your clap sensor works, or whether your relays work.  Before messing around further trying to test all at once, run some definitive tests on each device individually.  For example, run the following sketch and see if your system is able to turn on all of the relays at the same time.

// Test if relays work ok: First individually for a second each,
// then all together for 2.5 seconds
enum {relay=A0, relay2=A3, relay3=A4, relay4=A5, nRelays=4};
byte rePins[] = { relay, relay2, relay3, relay4};

void setup() {
  for (int r=0; r<nRelays; ++r) {
    pinMode(rePins[r], OUTPUT);    // Set pin to outputs
    digitalWrite(rePins[r], LOW);  // Turn off relay
  }
  Serial.begin(115200);
}

void loop() {
  byte r;
  // Turn relays on individually for a second each, with half-second gaps
  for (r=0; r<nRelays; ++r) {
    delay(500);         // Wait half a second
    Serial.print("Turning on relay #");
    Serial.print(r+1);
    Serial.print(" at ");
    Serial.println(millis());
    digitalWrite(rePins[r], HIGH); // Turn on relay
    delay(1000);           // One on for a second
    digitalWrite(rePins[r], LOW);  // Turn off relay
  }

  // Turn all the relays on
  Serial.print("Turning all relays on at ");
  Serial.println(millis());
  for (r=0; r<nRelays; ++r)
    digitalWrite(rePins[r], HIGH); // Turn on relay

  delay(2500);          // Wait 2.5 seconds

  // Turn all the relays off
  Serial.print("Turning all relays off at ");
  Serial.println(millis());
  for (r=0; r<nRelays; ++r)
    digitalWrite(rePins[r], LOW); // Turn off relay
}

Next, write a sketch to report results from photosensor and clap sensor readings.  Once you know if your hardware is working, try to get your double-clap logic to work without involving the photosensor, or vice versa.  Also, try to make the double-clap logic work just using a button in place of the clap sensor.

Note, to shorten your code and to get rid of some of the features that make it hard to read, do some of the following changes.  With the code slightly shorter, it may be easier to comprehend and debug.

(a) Instead of introducing program constants as integer variables, introduce them as program constants.  For example, instead of the verbose

int relay = A0;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;

say something like

enum {relay=A0, relay2=A3, relay3=A4, relay4=A5};

which tells the compiler that relay is a constant with the value A0, etc.

(b) Since you don't use variable LEDbrightness for anything, take it out.  With that gone, change the verbose

photocellReading = analogRead(photocellPin);
photocellReading = 1023 - photocellReading;
LEDbrightness = map(photocellReading, 0, 1023, 0, 255);

if(photocellReading > 500){
    photoSensor = 0;
}
if(photocellReading < 500){
  photoSensor = 1;
}

to

photoSensor = analogRead(photocellPin) > 523;

which will set photoSensor to 0 or 1 much as before.  (It is slightly different: It handles a photocellReading==500 case that your code ignores.)

(c) Change the verbose and badly formatted

  if (doubleClap == 0)
    {
      doubleClap = 1;
    }
    else if (doubleClap == 1)
    {
      doubleClap = 0;
    }

to

 doubleClap = 1 - doubleClap;

(d) Refactor to cut about half the code involving detectionSpan.


Passing arguments to LCD.print through another function I'd like to write a function like this:

void lcdPositionPrint(int row, int col,  content) {
    lcdPosition(row, col);
    LCD.print(content);
}

but I'm not certain how to declare "content", because it might be a string, or an int, or who knows what, just as it is for the "Serial.print" function or the LCD.print() function. Is there an easy way to do this?

One way to do this is to use generics. And we also need to use an unnamed namespace to get around the IDE's "helpfulness":

namespace {
    template<typename T>
    void lcdPositionPrint(int row, int col, T content) {
        lcdPosition(row, col);
        LCD.print(content);
    }
}

This will cause the compiler to create one function for each type passed in content that the function is actually called with.


PCINT0, PCINT1, PCINT2, etc. on ATtiny45/85 According to the datasheet:

we could think that, if we want to have a pin change interrupt for 3 pins, we have to create multiple instances:

ISR(PCINT0_vect){
   ...
}

ISR(PCINT1_vect){
   ...
}

ISR(PCINT2_vect){
   ...
}

void setup(){
  GIMSK = 0b00100000;
  PCMSK = 0b00000111;
}

However, this does not work, and I read here and here that we have to define just one interrupt function:

ISR(PCINT0_vect){
   if (digitalRead(0) == LOW)
     ...
   if (digitalRead(1) == LOW)
     ...
   if (digitalRead(2) == LOW)
     ...
}

Why is that so? What is PCINT1, 2, 3, ... made for then in this pinout schematics, if we don't have to use it?

That is simply the difference between an external interrupt INTx and a pin change interrupt PCINT. The first is an interrupt for a single pin. The second is an interrupt for a complete group of pins. Normally this group is a complete port. As the Attiny85 only has one port, this is the case here. So the whole group is only 1 single interrupt source. Thus it only has one interrupt vector named PCINT0_vect.

A pin change interrupt triggers, when any of the pins under it's supervision changes. You can remove pins from it's supervision by masking them with the PCMSK register.

So the interrupt vector PCINT_vect will be triggered by every change on any of the pins, that are not masked out. It is up to you to check, which one changed it's level.

On bigger microcontrollers, there are more pins and mostly also most of them are connected to a pin change interrupt. Here mostly every complete port is connected to a single pin change interrupt. Thus the corresponding registers are additionally marked with a number (PCINT0_vect as the interrupt vector for the first port, ...)


Arduino ATmega328P works but board (Uno R3) seems broken This is the first time I'm using my Arduino. It's an Arduino UNO R3. I have two boards. One works, but the other doesn't. I changed the ATmega328P from the broken one to the good one and it works, so I can confirm that the controller works. The issue seems to be in the board.

When I plug the board it doesn't come up either in Mac or in Windows. The LED blinks and the output pins have voltage, but it seems that it's only getting electricity from the computer, it's like the data channels don't respond. The other board works perfectly both on Windows and Mac.

I checked the logs on the Mac and nothing changes when I plug the board. It's like I'm not plugging anything.

Is there a way to reset the board only? Maybe a component was badly soldered in the factory. I can't use the warranty because I got the board last year and never used it until now.

The R3 uses an ATmega16u2 in place of the FTDI. It is possible that it is not loaded, busted crystal, or it has no local power to it. It is a small SMT.

You could use your good Arduino setup as ICSP programmer to talk to the ICSP of the 16u2 to see it is alive. And if so then program it.


how to use the decoded raw value to send IR signal in arduino I am IR library from Ken Shirrif at https://github.com/z3t0/Arduino-IRremote/releases/download/MAJOR/IRremote.zip

It is good and I have used the examples to receive and send and to playback IR signals from the library. And they are working good.

To send Unknown signals we should use sendRaw() method with a list of integers got from the receiver.

My question is when I use the receive program, I get the decoded hexadecimal value for even the Unknown signals. And can I use this small decoded signal to send signals apart from the long list of integers.

I am trying to send these codes from android. It would be quite easy to send and store the small hexadecimal decoded value.

Is there a way to use the decoded value to send for raw signals with some encodings at arduino?

If the signal is reported as "unknown" the library couldn't identify the protocol (RC5, RC6, NEC, SONY, etc).  If the library doesn't know the protocol,  the decoded number is meaningless. Simply put, an IR remote transmission has a frequency; a header; some data (the actual remote command); and a footer.  Without knowing the protocol the library doesn't know the length and shape of each section, so the purpose of the decoded number is only to show quickly if the decoding is receiving the same code at each keypress. You can verify this yourself.  Every time something makes an already known remote code be reported as "unknown", the code received is different from a real code, so simply guessing (or knowing beforehand) the protocol is not going to help anyway.


Question about RGB LEDs I think many people know about the staircase lights, which will get triggered by 2 PIR-sensors (1x upstairs and 1x downstairs).

Here is my code - which works well.  It's not cleaned up - as i don't know how i can simplify it. I think there'll be a much nicer way of getting the same output. :)

#include "FastLED.h"
#define NUM_LEDS 300
CRGB leds[NUM_LEDS];
#define PIN 3
int sensorUP = 5;
int sensorDOWN = 7;
int state = LOW;
int valUP = 0;
int valDOWN = 0;

void setup()
{
  FastLED.addLeds<WS2811, PIN, GRB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness(20);
  pinMode(2, INPUT_PULLUP); // internal pull-up resistor
  pinMode(sensorUP, INPUT);
  pinMode(sensorDOWN, INPUT);
  Serial.begin(9600);
}

void loop() {
  valUP = digitalRead(sensorUP);
  valDOWN = digitalRead(sensorDOWN);

  if (valUP == HIGH) {
    colorWipeUP(0x55, 0xFF, 0x00, 2);
    delay(600);
    colorWipeUP(0x00, 0x00, 0x00, 2);
    delay(100);
  }
  if (valDOWN == HIGH) {
    colorWipeDOWN(0x55, 0xFF, 0x00, 2);
    delay(6000);
    colorWipeDOWN(0x00, 0x00, 0x00, 2);
    delay(100);
  }
}

void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    setPixel(i, red, green, blue);
   FastLED.show();
    delay(SpeedDelay);
  }
}
void colorWipeDOWN(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 299; i < NUM_LEDS; i--) {
    setPixel(i, red, green, blue);
    FastLED.show();
    delay(SpeedDelay);
  }
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
  leds[Pixel].r = red;
  leds[Pixel].g = green;
  leds[Pixel].b = blue;
}

void setAll(byte red, byte green, byte blue) {
  for (int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  FastLED.show();
}

At the moment the LEDs just go on and after a delay off again (one-by-one).

QUESTION: I wish for a little smoother effect by fading them on and off.
So i reached the actual output by using different snippets and trying to understand. What i don't understand atm is how to add fading.

Your code is currently written as blocking, so we can leave it that way and add another blocking nested loop. Let's take the colorWipeUP() function as example:

void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    setPixel(i, red, green, blue);
   FastLED.show();
    delay(SpeedDelay);
  }
}

You go through all leds, lighting them up one after another with the provided color, delaying between the LEDs. The brightness of an LED is controlled by the overall RGB value. If you just multiply the RGB components red, green and blue with a number between 0 and 1, you (mostly) keep the color and only control the brightness. For example like this:

void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    for(uint8_t brightness = 0; brightness <= 100; brightness++){
      setPixel(i, red*brightness/100, green*brightness/100, blue*brightness/100);
      FastLED.show();
      delay(fadeDelay);
    }
    delay(SpeedDelay);
  }
}

For every LED we are now going from zero brightness to 100% brightness in a loop, showing each individual step on the LED strip.  fadeDelay determines, how fast this fade in should be. You will have to tune both delays to fit your expectations. You can use the same principle for the wipe down.

You may be asking yourself, why I count from 0 to 100 and then dividing by 100 instead of directly counting from 0 to 1 in steps of 0.01. I've done this, because on AVR based microcontrollers you don't have native floating point calculations. This means, that every floating point calculation needs many instructions to execute (because the floating point math is implemented in software instead of hardware). Here I'm counting with integers and when calculating the brightness also only integer math is involved (dividing by 100 is an integer division, which will automatically cut all digits after the decimal point. We don't need them).

Note: With 300 LEDs, the call to FastLED.show() will take some time. I haven't tested the code, but depending on your needs the fading might be too slow, even when you remove the delay call. Then you can simply increase the increment of the for loop, for example to use 10 steps instead of 100:

for(uint8_t brightness=0; brightness<100; brightness+=10)

  something like a fade over 10 LEDs

For this I would use a totally different approach. If you view it mathematically, the brightness of each LED is a function of position and time. So we can implement a function much like a mathematical function, that returns the brightness for a given position and a given time. As I understood, you want the a function, that is first constantly zero, then it grows linearly with time and position and then it is constantly full brighntess. We can count the time from the moment, that the sensor is triggered, where we then start with zero brightness and let it rise linearly. Something like this:

int fadeBrightness(int position, unsigned long time){
    int brightness = m_p*position+m_t*time;
    if(brightness > 100) return 100;
    if(brightness < 0) return 0;
    return brightness;
}

m_p and m_t are constants, that you would need to define and fine tune. For fading over 10 LEDs, m_p has to be -10. time is provided as milliseconds. I'm currently not sure about the value of m_t, but you can simply try some values and use one that's fitting.

Then in your colorWipeUP() function you can loop through all LEDs and set their pixel just like in the code above, but this time you use the newly created function.

void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  unsigned long timestamp = millis();
  while(millis()-timestamp < duration){
    for (uint16_t i = 0; i < NUM_LEDS; i++) {
      setPixel(i, red*fadeBrightness(i, millis()-timestamp)/100, green*fadeBrightness(i, millis()-timestamp)/100, blue*fadeBrightness(i, millis()-timestamp)/100);
    }
    FastLED.show();
  }
}

You need to define the duration according to how long the fading will take with your m_t. If you set it longer, the loop will just loop longer, holding the brightness at 100%.

In the function we first create a timestamp from the millis() function. Then we loop, while the duration of the effect hasn't passed. In each while loop iteration, we set the color components of each LED pixel with the brightness according to our fadeBrightness() function. Then we show this on the LED strip. The function is constantly updating the strip at max speed. The actual speed of the animation is determined by the fadeBrightness() function.

This version is also blocking code, but it can easily be transformed to non-blocking code, that you would call repeatedly until the animation is done.


Rotate Robot head according to Sound level I'm currently working on a robot using an Arduino and I'd like to control robot's head like this:

Imagine that it is on your desk and it can turn it's head through a range of 150 degrees like a human can do. So if I tap the desk in the the middle position, relative to his head rotation (in front of the robot), it should rotate his head by 75 degrees if he was looking at the left or right.

Likewise, I want to locate the desk tap or another sound source and make his head turn to that direction.

So in order to do that I have a solution, but I'm not confident enough to use it because I don't know whether is will give accurate results. This is what I thought:

I'll place two sound modules on the left and right sides of the robot. When a sound comes, I'll measure which microphone detects the higher sound level, and calculate an approximate angle to rotate the robot's head accordingly.

However, since I'm a newbie to Arduino, I've no real sense of whether that will work as I intend. Do people think this is a good method? If not, how can I improve it?

Also if you can, please suggest some good, Arduino compatible sound modules for this project. Thank you.

A couple of years ago, I completed a MOOC on FUN called Binaural Hearing for Robots (it doesn't seem to have run since, but it may be worth keeping an eye on it to see if they open registration again. At least some of the resources seem to be archived here). Interestingly, localising sound turns out to be easier with three microphones than with two.

You scan the three inputs in sequence, and when the sound is directed to record the time-difference between the three sensors. The technique you're looking at to localise the source is called trilateration.

Once you have a direction relative to the robot head, you can use a simple servo to turn the robot head to that direction.

I did play around with this a little bit, using three KY-038 microphone modules like this that I picked up cheap on eBay:

Connect them to your Arduino something like this:

I can't find my code (it was pretty untidy anyway since I was just playing around while I was working on the course), but a lot of Arduino sound-localisation projects have been published online with examples easy to find on Instructables, Hackaday, and many other sites.


How to digital read and send the data through serial to PC with speed around 2 MHz? I would like to read analog data with frequency sampling around 2 MHz and send it to PC to be processed with python for digital oscilloscope. I use Arduino Nano. I have found ADC (AD9057, PDF) that can handle up to 40 MSPS, but i still face some problems

How could I read digital pin quickly around 2-4 MHz? I read that it is possible using direct port manipulation
How could I send the data to PC with that sampling rate? I know that the maximum baud rate of arduino is around 2.000.000 or let say 2 MegaBytes/s, so for 2 MHz sampling, i could only send one character per micro second, could it be more faster?

Thank you

In short? You can't.

To have a 2MHz transmission you need 2*Nbit MHz of serial clock to send it to the PC, where Nbit is the number of bits per sample. Since the minimum is 8, englecting the synchronization or additional bits the serial clock has to be at least 16MHz. Which is the system clock of the nano. So no way.

Now, with the alternatives. First question: what is your ADC's interface? I found the LTC2204. It is a parallel ADC, so you need something to convert it to anything readable by the PC.

I'm not sure about the feasibility of this, but a nano is not enough. I'd use an STM32 (because I have their Nucleo boards, but you can search for other 32-bit boards) and a high speed serial interface. Since even SPI can be slow, maybe ethernet needs to be used. I was not able to search for boards with native ethernet interface; anyway the STM32F4 microcontrollers should (see this article) have an ethernet interface and you will "only" need the PHY. I think that this is the only applicable way to follow..


Keeping track of the number of rotations of a stepper motor Using the stepper.h library in Arduino IDE, how can we control the number of rotations the motor has to move?

you can keep track of number of rotations by calculating the time


All floats feedback a rounded down integer So I am very confused at the results I am getting.
It seems that floats aren't working properly, and I don't understand why.

I was trying to read a temp sensor and convert the reading to celsius. However, when I tried to divide the value (an int between 145-165) by 1024, and multiply by 5 I would get back a float value of 0.00
Here's the code I was using

    void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(A0, INPUT);

}

void loop() {
  int sensorVal = analogRead(A0);
    Serial.print("Sensor Value: ");
    Serial.println(sensorVal);

  float voltage = ((sensorVal/1024) * 5);
    Serial.print("Voltage Value: ");
    Serial.println(voltage);

}

This would only return values of 0.00 for voltage, even though the sensor itself is working fine, returning varying values between 146 and 165 based on how much heat I apply.
This didn't make any sense, so I tried it with some other values, eg.

Serial.print(float (10 / 6));

and

Serial.print(float (5 / 2));

which should have returned 1.67 and 2.50 respectively, but instead returned 1.00 and 2.00

I think it might be a settings thing, where all floats round down to an int, but that seems really weird.

Any help would be great!

You already got a couple of perfectly good answer. I will nevertheless
suggest a slightly different idiom:

float voltage = sensorVal * (5.0 / 1024);

or, maybe better:

const float V_REF = 5.0;  // at the top of the sketch

float voltage = sensorVal * (V_REF / 1024);

The reason this is slightly better than the other options is because
division – even integer division – is a very expensive
operation on the smaller Arduinos. By writing the conversion as in the
lines above, the ratio V_REF / 1024 becomes a compile-time constant,
which is evaluated by the compiler at build time. Then, only the much
cheaper multiplication needs to be done by the Arduino itself, at run
time. Not a big deal if you are not time constrained, but it's a
low-hanging fruit in terms of optimization.

You may write 1024.0 instead of 1024 if it feels safer. I tend to
keep the .0 for the voltage only, because 1024 is an integer, whereas
the “5” in “5 volts” is conceptually a real number (it's an
analog voltage, and not even exactly 5 V if you bother to measure
it). But this is just a personal preference at the end.


how to get serial data to wait until a certain length is reached I have a code that loops through 2 different serial inputs on the arduino mega, and sends them to serial constantly:

int RFIDResetPin = 13;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  pinMode(RFIDResetPin, OUTPUT);
  digitalWrite(RFIDResetPin, HIGH);
}

void loop() {

  char tagString1[13];
  int index = 0;
  boolean reading1 = false;
  boolean reading2 = false;
  ///////////////////////////////////////
  //this reads from the reader installed
  //on serial1, which is pin 19
  //////////////////////////////////////
  while (Serial1.available() > 0) {

    int readByte1 = Serial1.read(); //read next available byte

    if (readByte1 == 2) reading1 = true;
    if (readByte1 == 3) reading1 = false;

    if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
      tagString1[index] = readByte1;
      index++;
    }
  }
  Serial.println(String("Reader 7: ") + tagString1); //the tag itself

delay(1);
  clearTag(tagString1); //Clear the char of all value
  resetReader(); //reset the RFID reader
  //////////////////////////////////////////////////
  // This bit reads from serial2, located on pin 17
  /////////////////////////////////////////////////
  while (Serial2.available() > 0) {

    int readByte2 = Serial2.read();

    if (readByte2 == 2) reading2 = true;
    if (readByte2 == 3) reading2 = false;

    if (reading2 && readByte2 != 2 && readByte2 != 10 && readByte2 != 13) {
      tagString1[index] = readByte2;
      index++;
    }
  }
  Serial.println(String("Reader 8: ") + tagString1);

  clearTag(tagString1);
  resetReader();
}

void resetReader() {
  ///////////////////////////////////
  //Reset the RFID reader to read again.
  ///////////////////////////////////
  digitalWrite(RFIDResetPin, LOW);
  digitalWrite(RFIDResetPin, HIGH);
  delay(150);
}

void clearTag(char one[]) {
  ///////////////////////////////////
  //clear the char array by filling with null – ASCII 0
  //Will think same tag has been read otherwise
  ///////////////////////////////////
  for (int i = 0; i < strlen(one); i++) {
    one[i] = 0;
  }
}

when not scanning anything, the serial monitor outputs this:

Reader 1:
Reader 2:
Reader 1:
Reader 2:

When I scan a tag, lets say on reader 1, I get this:

Reader 1: 000004f5
Reader 2:
Reader 1: 000004f5
Reader 2:

it is not possible to scan more than a single scanner at a time. Is it possible to get the first line to wait until a certain number of characters have been scanned (indicating a tag has been scanned), and then output to the serial monitor?After that initial run, the code will loop as I showed above. any help is appreciated.

I would use a programming concept called a state machine. For example an integer variable called State could be used to track the current status which could for example be WAITING_FOR_DATA or RECEIVING_DATA or DATA_COMPLETE and only print when DATA_COMPLETE. I'm sure there are plenty of examples you could find with an appropriate search.


What is the library m in C++ linker? Following this guide, it says to include a library in the C++ Linker called m. What is this for?

Specifically, Your second Arduino project.

4) Configure project

5th dot point:

  AVR C++ Linker -> Libraries: Under libraries, add arduino_core and m (in that order). Under path, add the path to the correct core library, e.g. "${workspace_loc:/arduino_core/328P_16MHz}"

The m library is the "math" library. You have to link with it in most flavours of gnu compilers (it is typically not required in other, as it is included in the standard lib) when using functions and stuff from the header file "math.h".


Can I receive data on the Arduino by sending data to /dev/ttyACM0? I'm working on a Raspberry Pi connected to an Arduino.
When I execute

echo 'Hello' > /dev/ttyACM0

, the Arduino receives the data, as indicated by its LED. How can I read the data on the Arduino and process it?

Use Serial.read() there are plenty of examples that come with the Arduino IDE, just make sure the baud rates on the Raspberry Pi and Arduino match.


can't power up arduino from dc jack Yesterday I was working on Arduino based bluetooth car. I was using adafruit motor shield v1. Arduino and shield were on same power supply(11v li-ion cell battery). Every thing was fine. I decided to add some leds to my car. I connected two leds with 5v on shield pins(leds were in series and were multi-colored so 5v was okay). It worked for sometime but later it stopped working. Green led on arduino was on while other were off. I disconnected shield and supplied arduino from dc jack, same result. Then I connected arduino with usb cable then everything was fine. Now it works because I supply arduino from usb and shield is working too either from usb supply or external supply. What could possibly go wrong?

It would appear that the output of the power regulator pin has been vaporized.

From the Arduino R3 schematic we see this part as U1 which is an NCP1117ST50T3G power regulator.  Here is that data sheet for that part. From that data sheet we see the physical image of the part.

It appears that pin 2 has been vaporized.  If we look at the schematic of the Arduino R3 we see where pin 2 supplies the regulated power to the rest of the Arduino board and likely any connected electronics.  Note the red "X" indicating the vaporized pin 2.

The schematic and the data sheet both indicate the regulator's TAB is also an output.  If true it is difficult to explain why pin 2 vaporized.  Perhaps this particular version of the regulator does not use the TAB as an output.  Or perhaps the Arduino R3 PCB and schematic do not agree.

Added later...

There has been a comment that U1 (the NCP1117ST50T3G power regulator) may sometimes be manufactured with out the center pin.  Still, if you can power the Arduino R3 using the USB port and unable to power the Arduino R3 using power through the barrel jack, the likely suspects are U1 and D1.  However, to be sure, you would have to check the voltage before D1 and after U1.


Visual Micro without .ino files I am using the visual micro extension for Visual Studio 2015.  I would like to not use any .ino files since I'm trying to setup cppcheck which doesn't recogonize .cpp files, and its just what I'm used to.  However when I change my project.ino file to project.cpp the compile option is no longer available (I assume its looking for a .ino file).  Is there a project setting I can change to fix this?

Make a new tab in the IDE (top RH corner) with a xxx.cpp file name. Put your code in that. Leave the .ino file blank. Then it will compile. You need to add:

#include <Arduino.h>

... to the start of the .cpp file.

More information: How to avoid the quirks of the IDE sketch file pre-preprocessing

To clarify the question about libraries ...

You do need to put into the .ino file an include for any libraries used in the project. For example:

#include <Wire.h>
#include <SPI.h>
#include <EEPROM.h>

This effectively triggers the Arduino build process to link those libraries into the final executable file.

Related, my reply in this thread: Classes and objects: how many and which file types do I actually need to use them?


Washable, Wearable Tech with Arduino Question: How does one prepare clothing with embedded electronics for washing?

Background: There are several Arduino boards/clones that are designed for "wearable tech."  (For example, the Lilypad.)  Wearable tech with LED light patterns, microphones, GPS, or other circuitry is an interesting concept, but water and electricity tend not to mix.

To prepare wearable tech for washing, I would assume people make large circuitry removable.  Yet, inevitably, some electronics will be more-or-less permanently affixed to the cloth.  What, if anything, can be done to these electronics (e.g. sewn-in Arduino Lilypad) to make them washing-machine (preferred--hand wash could be done, but it's so much easier to machine wash) safe?

I would use some sort of epoxy and cover up the exposed circuitry. The major concern would be where the wires connect to the board as flex over time can weaken it.

Some options include:

3M™ Scotchcast™ Wet-Niche Potting Kit
Hysol

  US1150™—For electronics, telecommunications, and automotive
  components. Provides environmental hazard protection.

  US1152™—For electronic assemblies. Provides environmental hazard protection.

  Heat might play a factor if you cover up the boards in epoxy but you shouldn't be producing that much heat in a wearable device anyway, right?


Error in defining Ticker in ESP32 library I'm using the exact piece of code in my ESP8266 library (which works OK ), but when used in a ESP32 library- I got an error:

This is the relevant code snip:

void myIOT32::_feedTheDog()
{
  _wdtResetCounter++;
  if (_wdtResetCounter >= _wdtMaxRetries)
  {
    sendReset("Dog goes woof");
  }
}
void myIOT32::_startWDT()
{
  wdt.attach(1, std::bind(&myIOT32::_feedTheDog, this)); // Start WatchDog
}

void myIOT32::sendReset(char *header)
{
  char temp[150];

  sprintf(temp, "[%s] - Reset sent", header);

  if (useSerial)
  {
    Serial.println(temp);
  }
  if (strcmp(header, "null") != 0)
  {
    pub_msg(temp);
  }
  delay(1000);
  ESP.restart();
}

and this is the error:

/home/guy/Documents/git/Arduino/libraries/myIOTesp32/myIOTesp32.cpp: In member function 'void myIOT32::_startWDT()':
/home/guy/Documents/git/Arduino/libraries/myIOTesp32/myIOTesp32.cpp:333:55: error: no matching function for call to 'Ticker::attach(int, std::_Bind_helper<false, void (myIOT32::*)(), myIOT32*>::type)'
   wdt.attach(1, std::bind(&myIOT32::_feedTheDog, this)); // Start WatchDog
                                                       ^

ESP32 ticker attach functions take pure function pointers with at max one argument type -- not a std::function/ std::_Bind_helper that std::bind produces.

See code and types at https://github.com/espressif/arduino-esp32/blob/master/libraries/Ticker/src/Ticker.h#L38.

For the ESP8266 however, they do use a std::function:

https://github.com/esp8266/Arduino/blob/master/libraries/Ticker/src/Ticker.h#L36

And that's why it works on ESP8266 and not on ESP32 -- either adapt the Ticker library or rework your own code to not use member functions of classes.

Edit: You can easily rewrite your code to use a static helper function with one argument (the watchdog object itself) which then just calls the member function of that object. For this to work, the called function must be public. So a rewrite like

static void watchdog_timer_triggered_helper(myIOT32* watchdog) {
   //needs to be public!
   watchdog->_feedTheDog();
}

void myIOT32::_feedTheDog()
{
  _wdtResetCounter++;
  if (_wdtResetCounter >= _wdtMaxRetries)
  {
    sendReset("Dog goes woof");
  }
}
void myIOT32::_startWDT()
{
  wdt.attach(1, &watchdog_timer_triggered_helper, this); // Start WatchDog
}

void myIOT32::sendReset(char *header)
{
  char temp[150];

  sprintf(temp, "[%s] - Reset sent", header);

  if (useSerial)
  {
    Serial.println(temp);
  }
  if (strcmp(header, "null") != 0)
  {
    pub_msg(temp);
  }
  delay(1000);
  ESP.restart();
}

Since both the ESP32 and ESP8266 versions implement the

    template<typename TArg>
    void attach(float seconds, void (*callback)(TArg), TArg arg)

templated function this should work on both platforms now.


Fog Machine - On Command I work with a marching band, and we want to use fog machines for a particular part of the show. I know how to code/program in Arduino, however I am not great in the electrical and technical end. I own two fog machines, and the issue is that we need them to start fogging on command without delay (at least not a long delay, just not early and not late). We cannot exactly stop the show in the middle of a competition to say "wait, the fog is coming soon." We also need them to stop fogging on command.

I have read this article, Motion Triggered Fog Machine and it seems simple enough, however, I do not need or want it to work with a motion sensor. I suppose the easiest way you could help me is to either point me to a tutorial or tell me how to modify that tutorial to my own needs.

Perhaps use a small wireless board like the NRF24L01 (available for around $1 each on eBay). Have one at the fogging machine, similar to the Instructable, but instead of a sensor, you turn the machine on and off when a command arrives. For example, send "0" to turn it off and "1" to turn it on. There are examples with the NRF24L01 library.

Then you have an Arduino in the wings nearby where you press a switch when you need to turn the fogging machine on (this would transmit the signal).


Creating a wireless remote I am trying to create a wireless remote control to control a servo motor via Bluetooth. What all do I need to establish this? I did some research and found the following:

Tinyduino

Bluetooth low energy shield

Would these be enough (in addition to the servo motor) to establish my needs? Any advice on how I would go about coding this? I can research on the specifics but hints on functions to use would be greatly appreciated. Thanks!

I need to be able to control the system wirelessly (may it be Bluetooth or whatever) through a remote control. This remote control could be a push button system or an app on the phone. I do not have this designed yet. I do not know how to make iPhone apps so the best solution for me would be a simple push button on/off switch that can wirelessly tell the servo motor to either turn 90º clockwise or counterclockwise.

The RFDuino suggestion is very helpful, thank you for that. Can anyone recommend a push-button switch (small) that can wirelessly transmit the signal to the servo motor on the device? I hope this clears things up. Thanks!

I would also check out RFDuino.

Basically it's a finger-tip sized, Arduino compatible, wireless enabled microcontroller, low cost enough to leave in all of your projects.

The RFduino runs Arduino code and can do everything an Arduino can.


How to fix this error (expected ',' or ';' before 'int' exit status 1)? int Led1=13;
int Led2=10;
int tone1=6
  int D=300;

void setup(){
  pinMode(Led1,OUTPUT);
  pinMode(Led2,OUTPUT);
  pinMode(tone1,OUTPUT);
}

void loop(){
  int D;
digitalWrite(Led1,1);
digitalWrite(Led2,0);
delay(D);
}

Change your program like this:
int Led1=13;
int Led2=10;
int tone1=6; // <-- Add the missing semicolon here
int D=300;

void setup(){
  pinMode(Led1,OUTPUT);
  pinMode(Led2,OUTPUT);
  pinMode(tone1,OUTPUT);
}

void loop(){
// Remove the declaration of D here, it's already defined in the outer scope
digitalWrite(Led1,1);
digitalWrite(Led2,0);
delay(D);
// Set the leds inverse (otherwise, nothing happens, since setting the state twice doesn't do anything)
digitalWrite(Led1,0);
digitalWrite(Led2,1);
delay(D);
}


Can't figure out how to send Motor Values over Bluetooth, Arduino Bluetooth-controller robot I was trying to make an Arduino Robot that is Bluetooth controlled but I've some problems!

I can't figure out how to parse strings in Arduino like c++/java/python!
I tried this, If the first letter is L, set the next value to left motor, same for R

but for example "L255" is received as L - 2 - 5 - 5 and it sets L to 2 and ignores 5 - 5.

Any ideas on what I should do?

EDIT: Thought of something else, Sending L or R will toggle the motors! but that's just terrible, it'll be my last option

Update: This is how it works now:
L(0-5) means Left motor speed 5 * 51, 6-9 are backwards! its go backwards at (L(6-9) -5 * 51)

A state machine is the right way to go if you are sending multibyte commands.

However do you need to send 4 bytes for every turn? Do you need accuracy to one degree? Are you going to make regular turns of greater than 60 degrees?  If not I would consider encoding the dAta into a single byte.  You will reduce the radio bandwidth by 3/4, it will improve the responsiveness of. Your software and it will remove the need to have a handler for incomplete messages.

Of course there are probably other requirements that I don't know that will stop you doing this, but in case you haven't thought of it.


How to delay outside loop I am using a function outside loop(), which is called after an interrupt. Inside this function, I am setting several relays that need to change after a second or two, depending on my setting. I tried the delay, it doesn't work. millis() isn't working as well; I found out it stops counting when I exit the loop function.

My code looks something like this:

const long on_interval = 2000;
unsigned long currentMillis = millis();
bool hv_bool = false;

void hv_switch() {
    if (digitalRead(hv_pin)==HIGH){
        hv_startup();
    }
}

void hv_startup() {
    unsigned long previousMillis = 0;
    digitalWrite(pre_charge, HIGH);
    digitalWrite(main_charge, LOW);
    //Wait interval
    previousMillis = currentMillis;
    while (currentMillis - previousMillis < on_interval) {
        Serial.println(millis());
        //Wait
    }
    digitalWrite(pre_charge, LOW);
    digitalWrite(main_charge, HIGH);
    hv_bool = true;
    loop();
}

void setup(){
    //Set some ports

    //Initiate interrupt
    attachInterrupt(digitalPinToInterrupt(hv_pin), hv_switch, RISING);
}

void loop() {
    //Low voltage loop after startup, high voltage off
    while (hv_bool == false) {
        Serial.println("Waiting on high voltage");
        digitalWrite(hv_led, LOW);
        digitalWrite(pre_charge, LOW);
        digitalWrite(main_charge, LOW);
    }
}

@EdgarBonet has it - hv_startup() is part of the the interrupt handler. Interrupt handlers should be as short (timewise) as possible, doing only what has to be done with the interrupts off, and leaving longer tasks for the mainline (loop() and its sub-functions) to do.

But a bigger problem is that loop() is called from hv_startup(), also getting used as part of the interrupt handler, and loop() has a while{} loop that depends on hv_bool, which can never get changed, 1) because there is no statement to set it false (besides the initialization); and 2) because loop is now running at interrupt level and no more interrupts (at the same level) can be taken.

So I'd suggest several fixes:

Don't call loop from your interrupt handler. When your handler exits, loop() will resume from wherever it was when it got interrupted.
Don't delay in your interrupt handlers. If the interrupting hardware needs to be reset, do that and any other processing you have to do while the interrupts are off. But if some longer processing needs doing, set a flag in the interrupt handler (remember to declare it to be 'volatile'!), and exit.

In loop(), test the flag. If it is set, clear it and call another function to handle the less urgent processing required by the interrupt.


What is the necessity of "Prototyping Shield" for an arduino UNO R3? I just want to learn Arduino and make some  small projects. But in  the beginner starter kit there's  a part named Prototyping Shield. Is it necessary or will it help me?

A prototyping shield allows you to create your own circuit that can sit neatly on top of an Arduino.  Its main advantage is the pins/holes to connect to the Arduino, as these aren't evenly spaced so they are difficult to replicate with strip-board.
Do you need one? I doubt it very much, stick to the bread board and leave the soldering iron alone until you know what you are doing.


Connecting multiple topics- MQTT I'm configuring an ESP8266 using Arduino Uno.

I have several MQTT topics I wish it to subscribe, and I do not want to repeat code 3 or 4 times ( in Python I would have created a list - and make a for loop to subscribe all )

These are my topics:

//MQTT topic
const char* deviceName = "Sonoff1";
const char* deviceTopic = "HomePi/Switches/Sonoff1";
const char* msgTopic = "HomePi/Messages";
const char* groupTopic = "HomePi/All";

This is the function registering a single topic:

void reconnect() {
        // Loop until we're reconnected
        while (!client.connected()) {
                Serial.print("Attempting MQTT connection...");
                // Attempt to connect
                if (client.connect(deviceName,user, passw)) {
                        Serial.println("connected");
                        pub_msg("Power On");
                        client.subscribe(deviceTopic);
                } else {
                        Serial.print("failed, rc=");
                        Serial.print(client.state());
                        Serial.println(" try again in 5 seconds");
                        // Wait 5 seconds before retrying
                        delay(5000);
                }
        }
}

Appriciate you kind help,

Guy

just for a closure:

added an array (thank to Juraj):const char* topicsArry[]={deviceTopic, msgTopic, groupTopic, "HomePi/Dvir/Clock", "HomePi/Dvir/Alerts"};

a for loop to over this that loop, and using sizeof ( which was not trivial for me ), led to :

void reconnect() {
        // Loop until we're reconnected
        while (!client.connected()) {
                Serial.print("Attempting MQTT connection...");
                // Attempt to connect
                if (client.connect(deviceName,user, passw)) {
                        Serial.println("connected");
                        pub_msg("Power On");
                        for (int i=0; i<=sizeof(topicsArry)/sizeof(char *); i++){
                          client.subscribe(topicsArry[i]);
                          char msg[50];
                          sprintf(msg, "Subscribed to %s",topicsArry[i]);
                          pub_msg(msg);
                        }
                } else {
                        Serial.print("failed, rc=");
                        Serial.print(client.state());
                        Serial.println(" try again in 5 seconds");
                        // Wait 5 seconds before retrying
                        delay(5000);
                }
        }
}


How can I read servo motor readings via serial communication? I'm new to serial communication. I tried to make Arduino talk to MATLAB, but certain values are allowed to be received like 100 and 101. I tried other values but didn't work. The problem is with ASCII code but I tried to subtract what is read by 48 but failed.

This is the Arduino code that I found on Google and edited it for my servo motor problem:

#include <Servo.h>
const int servoPin = 3;
int recValue; // received value from MATLAB
Servo Servo1;

void setup()
{
  Serial.begin(9600);
  Servo1.attach(servoPin);
}

void loop()
{
  if (Serial.available() > 0)
  {
    recValue = Serial.read();
    if  (recValue == 100)
    {
      Servo1.write(0);
      delay(1000);
    }
    if (recValue == 101)
    {
      Servo1.write(90);
      delay(1000);
    }
  }
}

So how can I read the correct angles that I received from the MATLAB via serial communication? Thanks.

I'm assuming, that you are sending the angle value as a 1-byte value, so no ASCII encoded numbers. This is how the code in your question works, so it should be right.

You don't have to convert anything here. The Serial.read() function already returns an integer value and you are saving it to an integer variable. But in your code you only care for 2 different states (100 and 101), instead of the actual angle value. Now you only have to replace your if-statements and write this value directly to the servo:

Servo1.write(recValue);

EDIT:

You doesn't seem as you know how serial communication (to be exactly USART) functions. So I will explain further:

The data, that is send over serial is just a stream of bytes. All content, that get transmitted are converted to a stream of bytes. Every byte has a numerical value. For example a byte with the bit-content 00100000 has a numerical value of 32. But at some point in history it was necessary to send text with a byte stream. So someone invented ASCII, which assigns a character or control command to every numerical value from 0 to 127. So if you send a byte with the numerical value of 32, you could mean the actual numerical value 32, or you could mean the ASCII equivalent to 32, which is the space character. This is just an interpretation of the byte data, that flows through the serial interface.

So you have to investigate, in which kind you are encoding the angle value. If you use fwrite() in your Matlab code, you are most likely sending the byte value, which you can simply use as described above. If you use fprintf(), you are sending the angle value as an ASCII encoded string. The value 32 from above would then occupy 2 bytes with the characters 3 and 2, which correspond to the byte values of 51 and 50. In this case you should add a delimiter character at the end in fprintf() (for example the newline character "\n") and use Serial.parseInt() to get the angle value from the string.

You can read more of this in many tutorials about Serial communication that you can find in the internet. Also refer to the example, that come with the Arduino IDE.


Initialization of function pointer array I have an array of function pointers:

unsigned int dimension = 8;
void (* myFunctions [dimension])();

This array is a member of a class:

class myClass {

    static const unsigned int dimension;

    void (* myFunctions [dimension])();
}

and in a cpp file:

const unsigned int dimension = 8;

It's size is known at compile time, but it's values will be added through a public method in unknown parts of the code. I need to be able to find out at any time whether there is a valid pointer at some index in that array at any time, and my idea was to do that by comparing the pointer against nullptr: if it doesn't equals it then I'll assume that it holds a valid function pointer.

I was wondering if I need to initialize the array before making that kind of speculation. How is this array initialized if I only write the above two lines of code? Can I assume something like myFunctions[x] ==  nullptr is true in that case? Or do I need to do an explicit initialization like the following one?

for(int i = 0; i < dimension; i++)
    myFunctions[i] = nullptr;

You should actively zero-initialize your pointers in the constructor of your class.

The "zero-initialization" of the C++ language only applies in certain cases defined here. In certain configurations, e.g., when the object of the class has an explicit constructor which does not initialize the array, or when the class has no constructor and an object is function-locally created by typing myClass myObject;, the pointers are not initialized to nullptr.

They do get automatically zero-initialized via the C++ standard without you doing anything if an object of this class is declared and defined as a global variable, though. Then you have a "static storage location", and your object is zero-init'ed by zero-init'ing every data member. Your array of function pointers gets then member-wise zero-init'ed to the zero-value of a pointer, i.e., nullptr.

But you should write robust code which is always correct regardless of which kind of method is used to instantiate the object. Thus, the for loop in the constructor as you have it is correct.

See the analogous question I asked here (which I asked because I gave an initially wrong answer and felt responsible).


How to tell Arduino Uno that I pressed or released a key on PC keyboard over serial? I want to implement a simple musical keyboard with Arduino using tone() and noTone() functions, etc.

The desired behavior is:

While PC and Arduino are connected via USB/Serial...
...when I press a key, a corresponding note starts playing...
...and if I release that key that note stops playing...
...or if I press another key, another note replaces the former one.

So, basically, instead of "while key is pressed" logic, I would like to just write a byte to serial when a key is pressed, write nothing while the key is held pressed, and write another byte when that key is released.

I will be using a Python script in the PC, but examples in other languages, or just using a plain serial monitor, are fine.

As mentioned by Spiked3 there are a few ways to hit the ground running with C#.

Firstly, as detailed by Majenko, you will need an application running on your PC and some code on the Arduino to interact with this. For the desktop application, the two easiest ways to get started with C# are with WinForms, or XNA/MonoGame. WinForms is targeted at Desktop application development; think legacy desktop apps. Although it is not the current defacto standard (replaced largely by WPF) it is very simple and akin to Swing in Java to use. MonoGame and XNA are targeted at video game development. The latter would be my preference as it lends itself more towards real time applications, and has a game loop much like the Arduino so it is very easy to start using. The caveat is that there is more setup involved, but you will probably find this the friendliest and best supported.

Firstly, The Code! So for the Winforms Route, We have something like this:

using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            Debug.WriteLine(" Key Up! ({0})", e.KeyCode);

            // TODO: Talk with Arduino
        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            Debug.WriteLine(" Key Press! ({0})", e.KeyChar);

            // TODO: Talk With Arduino
        }
    }
}

To get to this point, fire up a new winforms project, and open up the 'Form1' code (the default window which is added to the project) add the methods as outlined above. You will need to go to the designer afterwards and add events for on KeyPressand on KeyUp to tie these functions to the Window. You can do this by clicking the Window, then opening the Properties Panel, and then clicking the lightening bolt. You will see a list of event names; find the corresponding events (Key Press and Key Up) and associate them with these methods.

From here, you can perform some logic when a button is either pressed or released.

The monogame or XNA approach is a bit simpler to follow as there is no hidden magic; but may be more intimidating if you're not familiar with C# and the project type.

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Diagnostics;

namespace GameName1
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;

        KeyboardState currentState;
        KeyboardState previousState;

        public Game1() : base()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            // Get state management started
            currentState = Keyboard.GetState();

            base.Initialize();
        }

        protected override void Update(GameTime gameTime)
        {
            // Listen for exit command
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            // Update the state of your keyboard object
            previousState = currentState;
            currentState = Keyboard.GetState();

            // Detect Keypress of key 'F'
            if (currentState.IsKeyDown(Keys.F) && previousState.IsKeyUp(Keys.F))
            {
                // F Key has been pressed
                Debug.WriteLine(" Key Pressed! ({0})", 'F');
                //TODO Talk to Arduino
            }

            // Detect Keyrelease of key 'F'
            if (currentState.IsKeyUp(Keys.F) && previousState.IsKeyDown(Keys.F))
            {
                // F Key has been pressed
                Debug.WriteLine(" Key Released! ({0})", 'F');
                //TODO Talk to Arduino
            }

            base.Update(gameTime);
        }
    }
}

In either case, you will need to get yourself set up first. Get a compy of Visual Studio Community from the link below, and install MonoGame if desired. Then do some C# tutorials to get comfortable in your new environment.

Visual Studio Community Edition
Mono Game
C# Tutorial
C# Mono Game Tutorial
C# WinForms Tutorial

Lastly, you will want to talk with your Arduino. This can be done by implementing a compatible Serial interface between your desktop application and your Arduino. See the tutorial below to get started!

Arduino C# Serial Tutorial

I hope this information is useful. There is a very broad range of topics mentioned here, and it may seem overwhelming at first - but C# is a very idiosyncratic language in that it permits rapid development in many different scenarios, and I think that you will find it rewarding to conquer the learning curve.


Urgent need of help splitting a JSON formatted string received by UDP I guess that my problems are because I'm new to C, but after spending three evenings without success I thought I'd give it a try to ask here!

I receive a JSON-formatted string in a UDP message. It contains several values that I would like to catch and convert to variables. The string format is like this:

{
  "U1": 224,
  "U2": 227,
  "U3": 224,
  "I1": 0,
  "I2": 0,
  "I3": 0,
  "P": 0,
  "PF": 0,
  "E pres": 639,
  "E total": 69901578,
  "Serial": "16889379",
  "Sec": 393833
}

Actually I really only need to get values U1, U2, U3 and I1, I2, I3. I'm grateful for all the help I can get solving this!

Best regards
Per

Two possible approaches:

Tokenize the string using strtok(), probably a few levels deep.
This may require you learning quite a bit more about C++, pointers, and character arrays as strings.
An excellent opportunity to use an existing library, such as ArduinoJSON, which abstracts out the difficulties you may encounter if the fields in your JSON string arrive in a different order, etc.

An example of using ArduinoJSON for your case is shown in the documentation (excerpted/adapted from Decoding JSON)

#include <ArduinoJson.h>

// [...] other code

char json[] = "{ \"U1\": 224, \"U2\": 227, \"U3\": 224, \"I1\": 0, \"I2\": 0, \"I3\": 0, \"P\": 0, \"PF\": 0, \"E pres\": 639, \"E total\": 69901578, \"Serial\": "16889379", \"Sec\": 393833 }";

//
// Step 1: Reserve memory space
//
StaticJsonBuffer<200> jsonBuffer;

//
// Step 2: Deserialize the JSON string
//
JsonObject& root = jsonBuffer.parseObject(json);

if (!root.success())
{
  Serial.println("parseObject() failed");
  return;
}

//
// Step 3: Retrieve the values
//
uint16_t    u1 = root["U1"];
uint16_t    u2 = root["U2"];
uint16_t    u3 = root["U3"];
uint16_t    i1 = root["I1"];
uint16_t    i2 = root["I2"];
uint16_t    i3 = root["I3"];


ESP8266 - Sending a software Reset Command I have an ESP8266 running an Arduino code to control a dual relay device ( Up, Down, Off ), both from a physical switch and MQTT commands. After mounting the device in place I have no access in case of a need to reset ( just as a precaution ).

My workaround:

1) condition: function that on 4 detection of 4 repeated UP button presses - it should send a reboot signal.

2) the reboot signal is :

void sendReset() {
  Serial.println("Sending Reset command");
  Serial.println(1/0);
}

sendReset function actually reboots the device and boot occurs as needed, BUT - is doing it this way is a valid solution ? does boot process actually boots all services and freeing/ memory or any other.... AS NEEDED ?

Guy

1/0 is an exception (divide by zero). esp8266 arduino core has soft reset: ESP.reset(). Calling this function you get a valid reset.

Note to software reset. esp8266 has a bug. If software reset (or exception) is executed in program started right after the flashing, the board goes back to flashing mode because the flashing flag is still active. Perhaps you noticed that after flashing the bootloader doesn't reset the board, but executes the flashed code.


Alternative to delay() when using Ticker in ESP8622 When using the Ticker library on the ESP8266 you can't use the delay() function because Ticker functions are using the underlying timer. The original Arduino library says that you can use a Ticker as delay, but in the ESP8266 implementation things work differently. You "attach()" a callback function and specify the period.

How can I generate a delay that doesn't require the underlying timer?

(BTW, where is the documentation for the ESP8266 Ticker library? The repository has no documentation nor comments on the functions.)

use the ticker callback to increment a value. this value can be used as millis() substitute. actually the "millis" is made that way.

write a simple function to give you a delay. this code assumes the callback function is interrupt/event driven like a systick timer in ARMs.

uint32_t ticks;

void callbackFunc()
{
   ticks++;
}

void myDelay(uint32_t del)
{
   uint32_t tempTime = ticks;
   while (ticks < tempTime + del);
}


Choosing the right mosfet to switch on-off a neopixel strip I,m trying to find the right mosfet or transistor to switch on-off a neopixel strip to safe battery power on a Lipo 3.7v using a pro mini 3.3v.

My Animation-Setup and Power Comsumption with 35 Neopixels is :

Sparkel      : 20mA
Knight Rider : 80mA
Pulse        : 600mA

So the maximum  current for the ledstrip is 600mA @ 3.7v
My first thought was to use the 2N 2222 - Transistor NPN TO-18 60V 0,8A 0,5W.

But then i realize the worst case:
What happens if the all 35 Neopixels turn full white caused by a software glitch or a bug in the code. Full white means every neopixles consumes 60mA.

Total power comsumption: 35 X 60mA = 2.1A

Would be destroyed the 2N2222? Because it could handle only 800mA drain current?

How can I avoid this situation. So I read about Mosfet like this one FQP30N06L :

N channel power MOSFET
TO-220 Package
Vds = 30V max
Max current = 62A
Vgs = 2.35V max
Rds_on = as low as 8.7 milliohm - depending on Vgs

What do you think will it work to switch on/off the led if:

the drain current is between 20mA - 600mA - 2.1A
ledstrip Vcc is 3.7v
pro mini out 3.3V at max 40mA

Or is there an other suitable Mosfet for this problem than the FQP30N06L with 62 Ampere for these hardware setup with only 2.1 Ampere Peak @ 3.7v ?

You refer to a 2N2222 handling 800 mA.  However, the 2N2222 datasheet shows 600 mA as its maximum rating for Collector Current – Continuous.  Moreover, from the On Characteristics table, Collector – Emitter Saturation Voltage at 500 mA current could be as high as 1 V.  In typical circuits with high base drive it usually is less, eg about 0.2 V typical with 50 mA base drive, which is more current than a typical AVR output is rated for.  Anyhow, the Neopixels won't operate if your switch drops any significant voltage from the supply.  Using a 2N2222 might work ok, or briefly, or intermittently, or not at all  – depending on the quality of the  2N2222 and the amount of base drive.

You refer to a FQP30N06L handling 62 Amperes.  However, the FQP30N06L datasheet shows 32 A as its rating for Drain Current - Continuous (vs 128 A for Drain Current - Pulsed, which is irrelevant here).

Using a FQP30N06L at its maximum 32 A continuous drain current would require careful heatsinking and perhaps 10 V of VGS drive to achieve low RDS(on), like 27 mΩ. With low VGS of say 3.3 V, RDS(on) might be twice as much.  For example, if it were 45 mΩ, going above 4 or 5 A current would be problematic without careful heatsinking:  4 A → P = 4²·0.045 = 0.72 W, enough to heat up a not-heatsinked unit's junction by about 45℃ or 80℉.

But the FQP30N06L should work ok for your 600 mA typical-case scenario, and also should be ok with the 2 A worst-case as well.


Add

pinMode(TONE,OUTPUT);

to setup() to fix the problem.


Leonardo clone being recognized by Windows as a broken Linino One - wtf? I'm running a Velleman VMA103, which is advertised as a clone of the Leonardo. Both use the 32u4 chip, and the pinout is exactly the same. However, when I plug it in, the drivers do something weird.

For about 5 seconds after pressing reset, the Arduino IDE will recognize the Leonardo on COM9, and the Windows device manager will show "Arduino Leonardo bootloader" then, the COM9 device will disappear and a device will be shown in the Other Devices tab as a LININO ONE, with no drivers installed. How is this possible?

I've reinstalled the IDE, no help there.

USB associates a driver, and thus what it calls a device, with the VID and PID that the device announces. Arduino PIDs are in a horrible mess, and there are many different devices that use the same PID. On top of that you have other makers also using the same VID/PID pairs and providing their own re-named Arduino driver files for their devices.

And then of course you have the problem that it is down to the firmware ("sketch") installed on the Leonardo that determines what VID and PID is shown to the computer.

So you have a set of possible scenarios - the main two being:

You have a driver installed that identifies the VID/PID pair of the Leonardo as something else
You have firmware installed in the Leonardo that gives the wrong VID/PID pair for your drivers

Check 2 first by installing the Blink example into the Leonardo (you can still upload firmware since it goes to bootloader mode at first as you have seen). If it changes the shown driver then you had some broken firmware installed. If it doesn't then you may be running a patched installation of the Arduino AVR core that gives a different default VID/PID pair, or you may just have the wrong board selected in the menu.

If you still have trouble then uninstall whatever driver is associated with the detected device and reinstall the official Arduino drivers that come with the IDE.

You can also delete the IDE and its associated downloaded packages and reinstall the latest version to ensure that you don't have strange patches and settings in there corrupting things.


What is this green board? Hi I'm new to arduino and robotics itself. I have no idea what this giant green board is in the middle of the robot. I really need help!

The green board is probably a custom PCB that controls the vehicle. Unfortunately, the image does not have enough quality to determine much else.


Connection of Seeeduino GPRS with relay module Good day. I'm working on home automation. I'm now at the implementation stage, where I want to assemble all the materials I need to use.

The materials are: Seeeduino GPRS (Arduino Leonardo), relay module, LCD display and electrical appliances. How do I connect them? I need the connection diagram, and some tips about the microcontroller. Thanks.

Have you checked out these two websites:

https://www.pubnub.com/blog/2015-02-17-connect-arduino-gsm-gprs-shield-to-the-internet/
http://www.seeedstudio.com/wiki/Seeeduino_GPRS.

They both go over many examples of how to connect the Seeeduino GPRS and even provides some sample code that you could run to test the connections if you are still unsure. As for the relay module, it depends on which one you are using, the LCD can be easily connected following this tutorial: https://www.youtube.com/watch?v=85LvW1QDLLw. Hope this helps.


How to pass a filename to a function? What type of variable is the filename? In the example below, I have two functions that write numbers to two different files on an SD card. I'm using the SdFat library.

Is there any way I can combine the two functions into one, so that I can call (for example): writeToFile(int t, FileName "filename1.txt");?

In the example below, to write a value to the "temperature.txt" file, I would like to be able to call: writeToFile(7, "temperature.txt"); In my sketch I have about a dozen functions that are writing to a dozen different files, so it would be very handy to be able to combine them into one function.

I think the main part I'm stuck on is I have no idea what the filename variable would be, or how to pass the filename to the function.

#include <SdFat.h>
SdFat sd;

void setup() {
  if (!sd.begin(chipSelect, SPI_HALF_SPEED)) {
    sd.initErrorHalt();
  }

  setTemperature(7);
  setFanSpeed(4);
}

void setTemperature(int t) {
  SdFile rdfile("temperature.txt", O_WRITE);
  rdfile.rewind();
  rdfile.println(t);
  rdfile.close();
}

void setFanSpeed(int t) {
  SdFile rdfile("fanspeed.txt", O_WRITE);
  rdfile.rewind();
  rdfile.println(t);
  rdfile.close();
}

String literals are of type const char *. Ordinary char *s can be passed to it though; the const means that the compiler will make sure that the function doesn't attempt to change the contents.

void setFileParameter(const char *filename, int value)
{
   ...
}


Is it possible my ATMega is burnt due to bad wiring? While working on a project I tried sending data from my Arduino NANO to ATMega64 placed on AREXX Robot arm PCB via TXD/RXD. After plugging in VCC, GND, TXD and RXD to UART socket it didn't work so I figured the socket itself must be backwords or mirror image from my perspective. Then I tried plugging everything in on the other side of the socket and as I plugged VCC to one of the pins a little smoke came out (I can't specify exact place where smoke came from) and from now on there is no connection to the robot. However LEDs seem to work just like before the 'incident'. It can be seen as COM but, desktop app constantly displays 'Connection failed' when trying to access the robot. It seems that I plugged VCC to the MRESET pin and GND to the RXD1 pin of the ATMega64. Can anyone help define if my processor is burnt? And if so, what can I do to fix the robot? Are there any other ways to send data to ATMega considering it is already programmed adn I want to keep it that way? Unfotunately, replacing ATMega isn't possible for me. Thanks in advance for any help.
UART :

ATMega :

Robot PCB :

Smoke is a definite sign something failed. The LED (power indicator)is independent of the microprocessor, it just indicates power is applied in the appropriate direction.  Go to the basics, and load the simple blink sketch and see if it works, if so you are lucky. You then might want to write some code to check all the outputs and inputs. It is possible you destroyed both devices, you need to do some investigating to determine what is still properly operating.


Arduino Coding Issue I'm running a water pump based on ultra sonic readings. Once the Ultra Sonic Sensor reads > 10 cm , I want the water pump to start until sensor reads < 5 cm. Would you please help me adjust the following code to meet my requirements.
void loop(){
 digitalWrite(trigPin,LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin,HIGH);
 delayMicroseconds(10);
 digitalWrite(trigPin,LOW);
 duration=pulseIn(echoPin,HIGH);
 distance=(duration*0.034/2);
 if(distance>5){
   digitalWrite(motor,HIGH);
   delay(30000);
   digitalWrite(motor,LOW);
 } else {
   digitalWrite(motor,LOW);
 }
}

So what you're asking is:

If distance is greater than 10:

Turn on

If distance is less than 5:

Turn off

That's not hard to code, since you already have an "if" there that compares the distance.
 if(distance>5){
   digitalWrite(motor,HIGH);
   delay(30000);
   digitalWrite(motor,LOW);
 } else {
   digitalWrite(motor,LOW);
 }

becomes:
if (distance > 10) {
    digitalWrite(motor, HIGH);
}

if (distance < 5) {
    digitalWrite(motor, LOW);
}

See how there's a direct 1:1 correlation between the English I wrote at the top and the code below it? That's often a good way to understand code: write it out in plain English step by step what you want and what decisions you need to make - then there's usually a simple conversion from English to code.
The hardest part of learning to program is understanding the logic. Do that in English first and the writing of the code itself becomes so much easier.


CH340 3.3v stability I want to use the 3.3v on a cheap Arduino Nano clone as my ADC analog reference voltage. The 3.3v comes from a regulator inside the CH340 USB serial chip.

I've measured the voltages (My DMM is NOT calibrated) on seven different Nanos and the voltages vary (2.96-3.38v).

I'm happy to calibrate each board to this voltage, but are there any figures available on how stable this 3.3v supply is? Long term and temperature wise?

Using the VCC as voltage reference is ok only if

you accept poor performances or
you need to measure a ratiometric output.

Case 2 is because the output depends on VCC (so you compensate). For instance, if you want to get the value of position in a potentiometer, you have that the voltage you see is Vo = Vcc * X (where 0<=X<=1 is the position), then the result you have on your ADC is Y = Vi / Vcc * k = X * k (where k is the maximum value of the ADC reading - e.g. 1023). So you actually compensate the Vcc deviation.

If you want to measure an absolute voltage, however (case 1) you will have a lot of uncertainties. For instance, if your current varies during the time (for instance you turn on the LED), the Vcc voltage can vary quite a lot. This is why for precise measurements you always must use a voltage reference.

In your case, you can

Use the internal reference - for the Atmega328 it is nominally 1.1V, but it can range from 1.0V to 1.2V
Use an external reference

You have to keep in mind that the voltage reference is the maximum value you can read. For instance, if you use the internal reference and then try to measure a 2.3V, you will not be able to do it (you will read the maximum value of 1.1V)

In order to fix this, you can use a trick: use Vcc as reference, and then use a voltage reference to get a precise calibration every time you need to measure something. For instance, if you have to read values from ADC1 and ADC3, you can

Read the value of the internal/external reference
Read ADC1
Read ADC3
Use the reading in point 1 to be able to guess what ADC1 and ADC3 readings were

This way you compensate for variations in the supply.

Just note that, even if the internal reference is not very precise (it has a 10% deviation from the standard value), it is indeed stable, while the VCC varies (a lot) during time. So if you have to calibrate, calibrate against the internal reference and not the Vcc.

If you can afford an external voltage reference, these are usually very stable and have very little deviation from sample to sample, so you may assume their value is "fixed"


Serial communication of strings I used this simple code to understand the basics of serial communication. This achieves simple communication between the computer and arduino:
String receive_buffer;
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()>0)  //check for any data received
  {
      receive_buffer = Serial.readString();  //read received data
      Serial.print("received data is: ");
      Serial.println(receive_buffer);        //display received data
  }

}

This works. Now, my next idea was to try communicating between two arduinos. I used this code for the reciever arduino.
The sender arduino contains a motor fitted with an encoder, and using the ppr value I  calculate the rpm of the motor. The code for rpm works perfectly. I now want to communicate this data to the receiver.
Wiring: (RX,TX) of sender connected to (TX,RX) of receiver, and GND is made common.
Now, on arduino.cc, it says that Serial.write() can have String as an input. So, I tried typecasting the rpm value (which was int), into a String, and then send that string to the receiver through Serial.write().
float ppr=512.0;
int encpin=3;
volatile long pulsecount=0;
float revs;
float rps;
int rpm;

extern volatile unsigned long timer0_millis;

void setup()
{
  pinMode(encpin,INPUT_PULLUP);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(encpin),function,RISING);
                                        //when pulse is detected
                                           //interrupt triggered,
                                           //function callled
}
//increments pulse by one
void function(){
  pulsecount+=1;
}

void loop()
{
 revs= pulsecount/ppr ;
 if(millis()>=1000)
  {
    rps= revs;
    rpm=rps*60;
    pulsecount=0; //resets pulsecount

    String strrpm= (String)rpm;

    //Serial.println(rpm);
    Serial.write(strrpm);

   // Serial.println("string rpm");
    //Serial.println(strrpm);

    noInterrupts ();  //resests millis() to 0
    timer0_millis = 0;
    interrupts ();
  }
}

However, I get an error:
43:24: error: no matching function for call to 'HardwareSerial::write(String&)'

The issue is not with typecasting. I tried to simply print strrpm and it worked fine. When tried Serial.write() with a different and simple string, i.e Serial.write("abcdef"); , it still gave the same error.
How then should I should I send my strrpm (string rpm) value to the receiver?

Serial.write() is meant for sending binary data. So if you want to send a string with it, you need to provide a c-string, not the Arduino implementation of the String class. That's done easily with a member function of that class:
Serial.write(strrpm.c_str());

That compiles successfully for me.
Though you should not do it like this. The String class is generally bad on small microcontrollers, especially on the AVR microcontrollers with little memory (like Uno, Nano, Mega, ...), because it causes memory fragmentation (see Majenkos "The Evils of Arduino Strings").
Instead you should just use the corresponding print() functions of the Serial class. They are made for sending human readable strings. No need to first build up a String object. Just do
Serial.println(rpm);

And it will do the string conversion itself without using the String class.

Besides that I have some notes on your code:

The way you use millis() is a bit weird. There is no need to actually reset the millis() value itself. Normally you would hold a timestamp in a variable and then only calculate the difference between millis() and the timestamp. That is also overflow safe. Like this
  unsigned long timestamp = 0;

  ...
  if(millis()-timestamp >= 1000){
      ...
      timestamp+=1000;
  }

That doesn't use an extern variable, it is not resetting the millis() counter (which might mess with other things too, that rely on it) and is somewhat the standard way to do it.

You are using an atomic section for resetting the millis() counter, but not for accessing pulsecount. That is actually the place, where you absolutely need this. pulsecount is of type long, so it will need many instructions to do the calculation for revs. The your interrupt service routine can easily mess with the data in that moment, resulting in garbled data. Move  the calculation into the if statement and use an atomic section like with the millis() counter to read it into a local variable then you can do the calculations. That will keep the time, where interrupts are turned off very short. You can also - instead of turning all interrupts off - just detach the pin interrupt for that time, so that other things are not affected. Like this code:
  void loop(){
      if(millis()-timestamp > 1000){
           // deactivate our pin interrupt, so it cannot mess with the data
           detachInterrupt(digitalPinToInterrupt(encpin));
           // copy pulsecount to local variable for further calculation
           long local_pulsecount = pulsecount;
           // reactivate our pin interrupt
           attachInterrupt(digitalPinToInterrupt(encpin),function,RISING);
           // Do calculation and print the value
           ...
           timestamp += 1000;
       }
   }


125 kHz RFID reader with Arduino Why is a toroidal inductor being used in the RFID reader described in DIY FSK RFID Reader?

I feel that a toroidal inductor wouldn't be very effective in grasping the changes in electromagnetic field changes.

Yes, Chris Stratton is right. A toroidal inductor keeps flux within the core, reduces the external flux to near zero and have near zero ability to grasp/convert external flux/magnetic field into electrical signal. Apparently, the word 'toroidal' was used in loose sense referring to a circularly shaped coil.

In an real-life commercial product, a 125 kHz coil typically has many turns on a very thin wire on an open-air core (no core).

An example profession factory made a 125 kHz RFID with a GitHub Arduino library and photos of an antenna coil:

125 kHz RFID module - UART
Seeed-Studio/RFID_Library
125Khz RFID module - UART (wiki)

Also, see Building RFID Card Reader using PIC Microcontroller.

Note, for higher frequency RFID, not shown in above examples, coils have fewer turns than for 125 kHz.