Serial.println Issue with Flame Sensor I'm really new to coding and Arduino so I would be eternally grateful for the help.

I'm trying to make a really basic flame sensor that beeps, lights up an LED and displays the distance from the sensor to the flame when activated. I keep getting a "'Serial' does not name a type" error message for the line that reads - Serial.println(analogRead(A0));

I’ve tried to figure it out from the information on this forum of similar questions to try to correct the issue but it seems like every time I fix one thing another 2 errors come up. I’ve been stuck on this one for a little while so I’m hoping I might be able to receive some kind of assistance from the Arduino community.

Below is the entire code - any help is appreciated, thanks :)

int Led = 4;
int Buzz = 7;
int Sensor = 11;
int Fire = HIGH;
void setup()
{ Serial.begin(9600);
pinMode(Buzz,OUTPUT);
pinMode(Sensor,INPUT);
pinMode(Led,OUTPUT);
}
void loop()
{
Fire = digitalRead(Sensor);
if(Fire == HIGH);
Serial.print("analog Read = ");
Serial.print(analogRead);
}
Serial.println("HELP! A FIRE!");
digitalWrite(Buzz,HIGH);
digitalWrite(Led,HIGH);
delay(200);
digitalWrite(Led,LOW);
delay(200);
Serial.println(analogRead(A0));
}
else
{
Serial.println("No fire detected");
digitalWrite(Buzz,LOW);
digitalWrite(Led,LOW);
}
delay(500);
}

First things first; please INDENT YOUR CODE. The code you posted is a mess and I took at least double the time to fix that.

First, you have an extra closing curly bracket at line 17 and the if (Fire == High); should be changed to if (Fire == High){

Fixed code:

int Led = 4;
int Buzz = 7;
int Sensor = 11;
int Fire = HIGH;
void setup()
{
  Serial.begin(9600);
  pinMode(Buzz,OUTPUT);
  pinMode(Sensor,INPUT);
  pinMode(Led,OUTPUT);
}
void loop()
{
  Fire = digitalRead(Sensor);
  if(Fire == HIGH){
//Serial.print("analog Read = ");
//Serial.print(analogRead);
    Serial.println("HELP! A FIRE!");
    digitalWrite(Buzz,HIGH);
    digitalWrite(Led,HIGH);
    delay(200);
    digitalWrite(Led,LOW);
    delay(200);
    Serial.println(analogRead(A0));
 }
 else
 {
    Serial.println("No fire detected");
    digitalWrite(Buzz,LOW);
    digitalWrite(Led,LOW);
  }
  delay(500);
}


Arduino UNO LED half brightness when connected to digital GND but not analog I am using an Arduino UNO. When lighting an LED with the switch button on a joystick module, I have two situations:

If the LED's cathode is connected to GND on the digital pin side of the Uno, the LED only dimly lights up on button press.
If the LED's cathode is connected to GND on the analog pin side of the Uno, the LED fully lights up on button press.

The device is receiving power from my laptop, and I am writing a digital HIGH/LOW to the LED pin (on press/release).

Is this a fault in my board, or is there a (perhaps more enlightening) reason why this is happening?

Despite double checking my cables before asking this question, it seems I had connected the LED's cathode to digital pin 13, and not GND. The issue is now resolved. Takeaway: Triple check your cables :)


How can I make std::cout write to Serial? I'm using an Arduino MKR WiFi 1010, a SAMD ARM Cortex M3 board. I rely on the standard library a lot, using things like std::vector<> and std::string. I also want to use std::cout. I've managed to do this on an UNO R3 using the ArduinoSTL library, but that library neither works nor is necessary on the MKR WiFi 1010, because it has all the standard library stuff built in to the platform.

However, on MKR WiFi 1010, I cannot get std::cout to produce any output. I'm guessing its not really hooked up to anything.

I want std::cout to write to Serial (which is aliased to SerialUSB which is of type Serial_).

Is there a way of making std::cout write to the Serial stream?

The ARM gcc libraries offer a simple way to redirect standard outputs. It is enough to implement function _write(int fd, char *ptr, int len) and it will replace the default implementation used in library to direct the standard outputs to debugger semihosting. The function must be compiled as  C to match.

#include <Arduino.h>
#undef max
#undef min
#include <stdio.h>
#include <iostream>

using namespace std;

extern "C" {
int _write(int fd, char *ptr, int len) {
  (void) fd;
  return Serial.write(ptr, len);
}
}

void setup() {

  Serial.begin(115200);
  while (!Serial);

  Serial.println("START");

  printf("HERE WE ARE\r\n");

  cout << "TEST COUT\r\n";
  cerr << "TEST ERR\r\n";
}

void loop() {

}

the #undefs undefine the Arduino macros, which are in conflict with includes used in <iostream>


Libraries not included correctly I stumbled upon the following unexpected behaviour and am curious about its cause.

header.h:

#include <Time.h>
[...]

main.ino:

#include "header.h"
#include <Time.h>
[...]

My code is working correctly with this setup. However, if I comment out the Time.h library in my main.ino, my code is working not correctly anymore:

#include "header.h"
//#include <Time.h>
[...]

I can still access the functions of Time.h, but they are returning garbage time.

Why do I have to include the library in my *.ino, although I am already including it in my header file?
Is there a best practice, on where to include libraries? Shall I simply always include all libraries in my *.h and *.ino file?

Firstly you should be including TimeLib.h not Time.h - the library header name has been changed to avoid conflicts on case-insensitive systems (Windows) and the internal time.h header in many compilers.

Secondly you should always include all your libraries in your INO file directly.  This is because the IDE parses the INO file before compiling looking for any included libraries. It then adds these found libraries to the list of libraries that need to be compiled. Without this you won't get the source code for your libraries compiled properly.


How to analyse audio and to affect source? I want to use the audio from my PC and have it going to the speakers and Arduino for some lighting effects. This project is a bit of a struggle because I don't know what the best way of analysing audio is. So for the lights I only want bass frequencies to affect the lights.

I have actually just finished a project doing exactly that. I used a frequency analyser chip called an MSGEQ7 (Available from Sparksfun), here's the datasheet.

https://www.sparkfun.com/datasheets/Components/General/MSGEQ7.pdf

These little things are really easy to use. Give me a shout if you would like any help with it such as coding or wiring.


Arduino UNO + CC3000 Wifi Shield, Reading webpage data I'm new so I might be making a stupid mistake, but I'm declaring:

char dollars;

at the begging of file, afterwards I'm reading a data from a web page, printing it to my serial. That part work well. The data returned from the web page is a number, 55 for instance.

The number get's printed correctly to the serial. But when I try to save the complete number it changes. for instance, when I get 0 from the server. The printed result is 10.

here is the important part of my code:

unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    while (www.available()) {
      char c = www.read();
      Serial.print(c);
      dollars = www.read();
      lastRead = millis();
    }
  }

  www.close();
  Serial.println(dollars);

while the www.read is repeating each of the returned characters it works fine Serial.print(c); but when I save it to the dollars char var, it get garbled up into something different. What am I doing wrong?

I'm planning to show that number from the web page onto my 4 digit screen at the end.

Webpages usually return data in text format with new line characters at the end.
In case of 55 you would get "55\r\n" or [53, 53, 13, 10] in bytes.
You need to parse the characters, like Serial.parseInt() does.

You are also only sending every second byte back to the serial monitor and only saving the last byte from the other every second byte.
After you read a byte with Serial.read() you can't read the same byte again, you get the next one.
In case of 55 you would send back "5\r" to the serial monitor and only store "\n" or 10 into dollars.
In case of 0 you would send back "0\n" to the serial monitor and store some unknown value into dollars, because you read more bytes that was sent.


Why is the BLE device not starting on my Arduino Pro Mini? I recently purchased a 5V arduino pro mini that I now wish to connect to a BLE device.

I firstly tried the BLE device with my Uno board and it worked very well! However when I now try to use it on my mini it does not start.

This is my wiring:
First I connect the pro mini to the uno in order to upload the code looking like this:

Arduino Mini Pro to Arduino Uno
RX --> TX
TX --> RX
VCC --> 5v
GND --> GND
RST --> RST

Then I wire the mini to my BLE device (https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/hooking-everything-up):

Arduino Mini Pro to BLE nRF8001
13 --> SCK
12 --> MISO
11 --> MOSI
10 --> REQ
9 --> RST
2 --> RDY
GND --> GND
VCC --> VIN

When I connect this setup to the computer the arduino uno starts and also the pro mini (both has LED lights on). I upload a simple test code that worked when i tried it with the uno but the BLE device does not respond (it seems like it does not turn on) when i use it with the pro mini.

Any idea what might be wrong? I have my board put as: Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz).

Thanks a ton!! :)

This is my wiring: First I connect the pro mini to the uno in order to upload the code looking like this:

Arduino Mini Pro to Arduino Uno

RX --> TX
TX --> RX
VCC --> 5v
GND --> GND
RST --> RST

How would this work? The bootloader in the Uno and Mini Pro will both try to reply. You need a FTDI or a USB-to-UART module instead of the Uno. Alternatively, start by programming the Uno to act as a USB-to-UART converter using Serial and SoftwareSerial.

Cheers!


Value of uninitialized EEPROM in ESP8266? In my limited testing it appears that the EEPROM in the Wemos D1 is not initialized to 255 like the specs say is the case for AtMega based Arduinos. In fact, the values look to be more-or-less random. Presumably this is because the ESP8266 doesn't actually contain EEPROM, but instead emulates it using flash. Is there a way to initialize the EEPROM region when flashing?

(This is pretty much the same question as here, which has not been answered.) Since I need only a few bytes of data, I'd prefer not to have to use the SPIFS.

Update:

Use case: I'm using the WiFiManager library to select the network to connect a Wemos D1 mini to the web to upload data to Thingspeak. I'd like to use WiFiManager to request the api-key and channel id from the user. However, once the user has entered these, I'd prefer not to make them enter the values again. (The api key is 16 random looking chars and difficult to enter correctly.) This means that the device has to store the values persistently between boots - the main use case for EEPROM. But how do you tell that the values in EEPROM (actually flash on an ESP device) are uninitialized crap, not the previous value? As suggested in the comments, setting flag values in a number of vars make it statistically unlikely to the random values from uninitialized memory. On an AtMega device, unless previously used, the values will be 255 in each byte.

Calculate a checksum for the data and store as part of the data. Recalculate the checksum when you read the (questionable) data back again. If the checksum fails, it's invalid. If it passes, the data is valid to some statistical level of confidence.

A 16-bit checksum would make false acceptance highly unlikely, but  make it long enough for your own comfort level. What would be the worst consequence of a false acceptance: inconvenience (user has to re-enter a number)? Loss of money or property? Loss of life? Choose the complexity of your solution accordingly.


Arduino Power Consumption I am pairing an Arduino Uno along with both a HC-05 bluetooth module and a sensor circuit.

Show below is the circuit conditions as well as the circuit.

As far as powering up the system, I am planning to use a 9 Volt battery(550 ampere) to connect to the Arduino which draws in 45 mA and the sensor circuit which takes in a total of 28 mA. I calculated the total life of one of the batteries to be 7.53 hours by (550/(28+45)). Can someone help me with the total power consumed by the system?

UPDATE:
I read on the sensor data sheet that there are two parameters which heater power as well as sensor consumption. Heater Power consumers approximately 140 mW and the sensor consumes approximately 10 mW. I believe the Arduino will consume 405 mW because of (9 volts * 45 mA)  and the bluetooth module will consume 26.5 mW because (3.3 volts * 8). Therefore, the total power consumption is 571.5 mW. Is this correct??? Also will the 9 volt battery be able to support the total power?

Your calculations are not totally right. I did not check the data you provided, so I'm just using the numbers you put.

The arduino draws up 45mA @5V.
The sensor has a power of 150 mW and is powered at 5V, which means a current of 30mA.
The bluetooth module gets 8mA (are you really sure? it seems too low) @3.3V.

Now, the battery gives you 9V. So you need to convert them to the proper (5V and 3.3V) voltages required by the devices.

You have mainly two options:

you use a linear regulator
you use a switching regulator

(Please note that if you use the regulators already present on the UNO board - the 1117 and the LP2985 - you will use the first approach)

In the linear case, the regulator will drop the voltage by dissipating the excess power through heat. In this case, you will need to sum the currents:

Total current = 45mA + 30mA + 8mA = 83mA. Please note that if using a 9V battery, the 5V regulator will need to dissipate (9-5) * 83mA = 332mW of power (or slightly less if the 3.3V regulator directly interfaces to the 9V battery).

Now, according to the first datasheet I stumbled upon on google, this kind of battery have a capacity rated at 10mA, but at 100mA it loses about 40% of it. In fact, batteries tend to last less when the current increases (if you double the current you will get less than half of the time).

Considering so a mere 30% of loss at 83mA, your battery will last slightly above 4 hours and a half (550mAh*70%/83mA)

Now, if you use a switching regulator to get 5V from the 9V (and then a linear one to get the 3.3V), you will have to generate 83mA at 5V. This means that, considering an efficiency of 85%, your battery will have to provide roughly 54mA (83mA*5V/9V/85%).

According to the datasheet of the battery, this lower current reduces the degradation of the capacity to about 25%. The total uptime is consequently 7 hours and a half (550mAh*75%/54mA).

If you put a second switching regulator to get the 3.3V, you will have
- 75mA at 5V, which with a 85% efficiency will become 49mA
- 8mA at 3.3V, and with a lower efficiency due to the very low current (let's say 75%) become 4.4mA

Total current from battery: 53.4mA (which can be considered equal to the case with just one switching converter.

Just one last note: please consider that a heated sensor like the one you have is not engineered for battery-powered devices, since a lot of power becomes heat. When you want to develop a real battery-powered sensor, you will need to go with a lower-power solution for both the microcontroller (and the board) and the sensor


Arduino board is turning off when I connect to +5V I am trying to set up an LCD screen without using a resistor or a potentiometer for an Arduino project. This is the LCD I am using: Basic 20x4 Character LCD.

But when I connect to +5V on the Arduino board, my Arduino board turns off. This is how I have the LCD connected to the Arduino on a breadboard.

Connections:

LCD RS pin to digital pin 12

LCD Enable pin to digital pin 11

Data:

• LCD D4 pin to digital pin 5

• LCD D5 pin to digital pin 4

• LCD D6 pin to digital pin 3

• LCD D7 pin to digital pin 2

LCD R/W pin to ground

LCD VSS pin to ground

LCD Cathode pin to ground

LCD Anode pin to digital pin 9

LCD VCC pin to 5V

Code:

// include the library code:
include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  analogWrite(6,20);
  // set up the LCD's number of columns and rows:
  lcd.begin(20, 4);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

Try out this connection. It will helpful.


Optimizing ext. SPI ADC for speed and verify the speed So I have a project where I will be using an Arduino Leonardo and an external ADC (AD7980) to run a 16-bit (18bit) conversion and transmit it to the Arduino and then out on USB as fast as possible.

The AD7980 can run up to 1 MSPS, and I know I cannot reach that with the ATmega32U4 - but I want to know how to optimize my code for running it as fast as possible and how to measure it.

Right now my code is:

#include <SPI.h>

int CNV= 11; //Convert on pin 11
int Slaveselect=8;
int adcValue;
byte highByte;
byte lowByte;

void setup() {
  Serial.begin(115200);
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV2 ); // 8 MHz rate
  SPI.setBitOrder(MSBFIRST);
  pinMode(Slaveselect, OUTPUT);
  pinMode(CNV, OUTPUT);
}

void loop() {
  digitalWrite(Slaveselect,HIGH);
  // SS always high to use 3 Wire mode without busy indicator
  digitalWrite(CNV,LOW);
  digitalWrite(13,LOW);
  digitalWrite(CNV,HIGH);//starts conversion
  digitalWrite(13, HIGH);
  digitalWrite(CNV,LOW); //starts to transmit MSB on data line
  digitalWrite(13,LOW);
  highByte = SPI.transfer(0x00);
  lowByte = SPI.transfer(0x00);
  adcValue = highByte << 8;
  adcValue = adcValue | lowByte;
  Serial.print("analog value =");
  Serial.println(adcValue);
  Serial.print('\n');
}

The datasheet for the ADC can be found here: Datasheet

Don't use digitalWrite().
Don't use delay().
Don't flood your Serial connection with useless junk ("analog value =")

You may also consider using lower level SPI operations instead of the SPI library, which is completely blocking and slows you down. At least consider the use of SPI.transfer16(...) which is more efficient than two SPI.transfer(...) calls.


Fio Keyboard program out of control, how to reset? My question involves a Sparkfun Fio v3, similar to the Arduino Fio.

I had a student who was testing his understanding of the Keyboard library.  He uploaded a sketch that continuously sends output, emulating a keyboard, saying "Hello!If you're reading this, then you did things right!" (I don't have his code, unfortunately, so I can't post it.)

So, now, whenever I connect it via the USB, I can't upload a new sketch because the Serial channel is clogged with this output.  (Error Message: "avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00" and so on)

I've tried putting the cursor inside the header comment in 'Blink', so that the new characters that are being spammed to my code are all inside a comment, and this makes it possible to compile, but it won't sync and upload.  I've tried burning a new bootloader, and this fails as well (Message: "Error while burning bootloader.").

It seems to me that the only way to get this device back is to reset the memory without connecting to a computer, but I can't find any way to do this.

Is there any way to rescue this device?

Hehe... This is a fun one to try and get out of. The normal way is to reflash the bootloader...

If it's the same as the Leonardo you get about 8 seconds after a reset while just the bootloader runs before it starts to spam everything with text. So you can try:

Open notepad or something similar
Plug in the board
Press and hold the RESET button (or connect the RESET pin to GND with wire)
Open the IDE and load Blink.ino

Now the tricky bit.  If the correct serial port isn't selected, you need to, within the space of 8 seconds:

Release the reset button.
Let the PC enumerate the device
Open the serial ports menu and select the right port
Press and hold the RESET button again.

Now you can program it, in a similar way:

Press UPLOAD in the IDE.
Just before it finishes compiling (turn on verbose output can help you time it better) release the RESET button.

If you timed it right the bootloader should run and accept the new program before the existing sketch runs and starts spamming everything.


Displayng 2 error messages on a 16x02 display I am trying to display on a 16x02 LCD display 2 error codes. The error message is when one or both thermocouple wires get disconnected and the second error message is when the soldering iron temp goes higher than 432 C. I am using MAX6675 module.
The problem is that when I disconnect one thermocouple wire (the + or the -) sometimes the displayed message is "Overheating !!!" instead of "No tc conn !!!".
Is there any way to display the correct error ?
heaterTemp = thermocouple.readCelsius();
  Input = heaterTemp - 100;
   //No TC connection
  if (isnan(Input)) // No TC Connection
  {
    while (true) {
      digitalWrite(relay_pin, LOW);
      digitalWrite(11, LOW);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("NO TC CONN !!!");
      delay(1000);
    }
  }

  //Soldering Iron overtemperature
  if (Input >= 432)
  {
    while (true) {
      digitalWrite(relay_pin, LOW);
      digitalWrite(11, LOW);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("OVERHEATING !!!");
      delay(1000);
    }
  }

Edit: I finally decided to use the same message for both errors - no TC connection and overheating. I used the code below:
heaterTemp = thermocouple.readCelsius();
  Input = 0.779828 * heaterTemp - 10.3427;
  if (isnan(heaterTemp) or Input >= 432) // No TC Connection OR over-temperature
  {
    while (true) {
      digitalWrite(relay_pin, LOW);
      digitalWrite(11, LOW);
      for (int i=0; i<=1; i++){
      lcd.clear();
      lcd.setCursor(0, i);
      lcd.write((byte)0);
      lcd.setCursor(1, i);
      lcd.write((byte)0);
      lcd.setCursor(5, i);
      lcd.print("ERROR!");
      lcd.setCursor(14, i);
      lcd.write((byte)0);
      lcd.setCursor(15, i);
      lcd.write((byte)0);
      delay(1000);
      }
    }
  }

and
byte thermometer[8] = //icon for termometer
{
  B00100,
  B01010,
  B01010,
  B01110,
  B01110,
  B11111,
  B11111,
  B01110
};

The code displays the thermometer symbol at the beginning and at the end of the row and the text (including the symbols) are moving from one to another row.
Now it is sufficiently to display a error message when the thermocouple gets disconnected or when the iron temperature goes above 432 *C.
I have also left the 2 while(true) loops because I need the program to stay in the loop and display the error message until I turn off the power and start again the soldering station.

I think before the disconnection is detected, it goes into overheating (maybe just for some milliseconds).
However, because there is a while (true) loop within the overheating part, it will never show the NO TC CONN error.
If you consider the NO TC CONN error to be higher than the OVERHEATING error, than check within the while loop of the OVERHEATING error also for the NO TC CONN error and display NO TC CONN when it is detected.


Which bluetooth module should I buy? I am doing a wireless rover using arduino mega 2560 that can be controlled by a smartphone and a PC. Which bluetooth module would fit me? Again I want to control it both by my Laptop(Built-in Bluetooth) and my smartphone. Thanks in advance.

A little late but in case someone like me ran into this:

HC-05 seems to be the DIY choice. Can work in slave or master mode and works with Android but not iOS.

HC-06 is the same as HC-05 except that you can only use it in slave mode.

HM-10 seems to be the option for iOS users.


Is it possible to output a variable clock using Fast PWM? I am trying output a clock and change its frequency dynamically with a rotary encoder.

When the code for the rotary encoder is included the clock doesn't reach its max freq(31Khz). But without the rotary encoder code, it does. What is happening that it can't reach its max freq?

const byte CLOCKOUT = 9;
int val;
int encoder0PinA = 3;
int encoder0PinB = 4;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;

void setup() {
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS12);   // CTC, no prescaling
  OCR1A =  0;

  pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  Serial.begin (9600);
}

void loop() {
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    if (digitalRead(encoder0PinB) == LOW) {
      OCR1A-=100;
    } else {
      OCR1A+=100;
    }
    Serial.print (OCR1A);
    Serial.print ("/");
  }
  encoder0PinALast = n;
}

The Code that reaches the Max freq properly is below

void setup ()
  {
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS12);   // CTC, no prescaling
  OCR1A =  0;
  }

void loop (){
  }

I'm not sure whether this is the real issue you have, but I spot an issue which can be the issue you have.

You wrote something like this:

if (pulseFromEncoder)
  if (direction1)
    OCR1A -= 100;
  else
    OCR1A += 100;

Now, the OCR1A is a unsigned 16 bit integer. A value of 100 corresponds to 1.6ms of delay on the timer (see comment from Edgar Bonet below). This is what happens when you rotate in direction 2:

        OCR1A  Time delay
Rotate:   300      4.8ms
Rotate:   200      3.2ms
Rotate:   100      1.6ms
Rotate:     0      0ms
Rotate: 65436   1047ms

See? The value rolls over and the time completely changes.

Now, maybe the issues are other (for instance changing the mode to 15 instead of 4 like EdgarBonet said (no idea on what this means, you should double check the differences on the atmega datasheet), but I strongly suggest you to fix this issue, for instance this way:

const uint16_t OCR1A_Min = 0
const uint16_t OCR1A_Max = 20000
const uint16_t OCR1A_Step = 100

...

if (pulseFromEncoder)
  if (direction1)
  {
    if (OCR1A > OCR1A_Min + OCR1A_Step)
      OCR1A -= OCR1A_Step;
    else
      OCR1A = OCR1A_Min;
  }
  else
  {
    if (OCR1A < OCR1A_Max - OCR1A_Step)
      OCR1A += OCR1A_Step;
    else
      OCR1A = OCR1A_Max;
  }

Sidenote: doesn't your encoder need debounce?


Issue with CD74HC4067 MUX on high values I'm having a small issue with the CD74HC4067 multiplexer/demultiplexer: I am using it to receive data from an array of sensors (at the moment I have only 2, but in a near future they will grow). Specifically I have a light sensor and a sound sensor.
Mux output is connected to A0 since the readings I do are analog. The pins I use to switch the channels are A3 and A2 (when the other sensors will arrive also A1 will be dedicated to that).
My problem is that when switching between one channel and another, my readings highly fluctuate, but only when the reading value is > 500 or so, and I don't understand why. In a simple sketch I've tried adding some delay (40 msec) and the issue goes away. But in my project which is far more complex and uses also other analog channels I need a delay of ~1 second to get a correct reading, which is absolutely unacceptable since I need it to run in real-time(ish). I also tried using the digital pins to control the mux but to no avail. The only thing that seems to stabilize everything is connecting a capacitor between the MUX out and ground, and using a 20msec delay, but it only works for a bit.
I hope I've been clear enough and that someone can point me the right way!
EDIT:
Here is the schematic

(Error in the drawing: "temp" is actually a "light sensor" as in the bottom of the post...)
And my code:
#define MUX A0
#define S0 A2
#define S1 A3

void setup() {
  Serial.begin(9600);
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);

  selectMux(1);
}

void loop() {

  //selectMux(0);
  //Serial.println(analogRead(MUX));
  //selectMux(1);
  Serial.println(analogRead(MUX));

}

void selectMux(byte port) {
//  pinMode(MUX, mode);
  int r0 = bitRead(port, 0);
  int r1 = bitRead(port, 1);

  digitalWrite(S0, r0);
  digitalWrite(S1, r1);
  analogRead(MUX);
}

the analogRead(MUX) in the selectMux function was added because I read in a post that they suggested to do that in order to get a more accurate reading.
With this code only the results already fluctuate:
Output:
76
41
77
76
76
75
36
75
74
76
77
106
76
76
76
76

but it goes crazy when the input is higher, close to 5V:
Output:
948
780
340
948
948
635
437
949
948
499
551
949
950
396
684
950

If you enable the commented code that starts to switch the outputs it is even worse. As I said, adding delays helps, but in my final application I cannot afford to have 1s delays.
I also show that in the circuit there is a timer that uses other Analog pins, but in the code I didn't include that part. If you need I'll add that too.
Sound Sensor,
Light Sensor

I don't think you should leave s2 and s3 floating. A floating pin does not mean nor 0 nor 1.

Connect them both to ground.


voltage output at digital pins vs. load I am trying to convert the signal from digital pin 2 on my Uno to 3.3V.  I set up a voltage divider with 3 x 1000 ohm resistors.  When connected to ground and 5V the divider circuit generates 3.3V correctly, with a calculated input current of 1.7mA.  However I connect it to a digital pin, the digital pin voltage drops from 4.8V to .37V.  I thought the digital pins were to support 40mA, I was assuming 40mA at the 5V supply voltage.  Is my Uno malfunctioning?

Thanks

Just figured out I didn't have the pin mode set, it works fine now, thanks.


Arduino for delivering a WoL signal over ethernet, when receiving a specific command over WiFi I'd like to assemble a device that could accomplish the following:

Connect to my home wifi (WPA2-Personal)
Connect to my home PC with via Ethernet cable
Able to send WoL signal to the PC when getting a signal over wireless connection
The whole set up needs to be less than 45USD, desirably much less, otherwise I'd just buy a wireless bridge.

The goal is both to have a useful device (that will allow me to wake up my pc remotely) but also have fun learning something new (arduino).

I have no background in Arduino or Electronics in general. I program well though and learn fast.

Do you think Adruino is adequate for the above? Is soldering required (I'd rather not, or at least not a lot)?

The Arduino might not be a choice for you. The reason why microcontroller boards(like Arduino) become popular is the simplicity and the easiness of control peripherals through GPIO pins, like output PWM signal to control motors, reading sensors through SPI or I2C, reading analog voltage, and etc. Most microcontrollers on Arduino boards itself, however, is not designed for networking features and does not have even enough performance for it. This means that it would cost you much more money on additional networking devices like WIFI shield, Ethernet shield and microprocessor for networking (Arduino Yun).

So, if you are looking for just a pure networking device like what you have in mind, I would highly recommend you Raspberry Pi(2 Model B for $39 and 1 Model B+ for $30), which has enough capability of networking itself. All you need is a USB WIFI dongle($9) with the Raspberry Pi, I guess. I am pretty sure you won't have a cheaper option using Arduino.

You can use the raspberry Pi as a web server, a NAS, a media server along with the features you mentioned.


Problems with transmission between ATtiny85 and Arduino Uno with 433MHz RF modules and Manchester I am trying to transmit from an ATtiny85 running at 16MHz internal clock to an Arduino Uno with the Manchester Library.

The problem is that the Arduino is not receiving any data.

I have hooked an oscilloscope to the ATAD/DATA pin of the transmitter, and I can see data being transmitted. I have also done the same thing on the DATA pin of the receiver, and it shows data being received. But the Arduino Uno is not detecting anything.

I have tried having an Arduino Uno sending data to itself, which does work, but the data gets dropped very often.

Here is the source code of the transmitter:

#include <Manchester.h>

#define TX_PIN 3  //pin where your transmitter is connected

uint16_t transmit_data = 2761;

void setup() {
  pinMode(1,OUTPUT);
 man.setupTransmit(TX_PIN, MAN_1200);
}

void loop() {
  digitalWrite(1,HIGH);
  man.transmit(transmit_data);
  delay(200);
  digitalWrite(1,LOW);
  delay(200);
}

And this is the code on the receiver:

#include "Manchester.h"

#define RX_PIN 4
#define BUFFER_SIZE 22

uint8_t buffer[BUFFER_SIZE];

void setup() {
  Serial.begin(9600);
  man.setupReceive(RX_PIN, MAN_1200);
  man.beginReceiveArray(BUFFER_SIZE, buffer);
}

void loop() {
  if (man.receiveComplete()) {
    uint8_t receivedSize = 0;
    // do something with the data in 'buffer' here before you start receiving to the same buffer again
    receivedSize = buffer[0];
    for(uint8_t i=1; i<receivedSize; i++)
      Serial.write(buffer[i]);
    Serial.println();
    man.beginReceiveArray(BUFFER_SIZE, buffer);
  }
}

This is the code I used to test with only the Arduino Uno:

#include <Manchester.h>

#define RX_PIN 7
#define TX_PIN 8  //pin where your transmitter is connected

uint16_t transmit_data = 2761;
int lastTransmit = 0;

void setup() {
  Serial.begin(9600);
  man.setupReceive(RX_PIN, MAN_1200);
  man.setupTransmit(TX_PIN, MAN_1200);
  man.beginReceive();
}

void loop() {
  if (millis() - lastTransmit > 200) {
    man.transmit(transmit_data);
    lastTransmit = millis();
  }

  if (man.receiveComplete()) {
    uint16_t m = man.getMessage();
    Serial.println(m);
    man.beginReceive();
    //start listening for next message right after you retrieve the message
  }
}

You set receivedSize to zero at instantiation, then load it with buffer[0], which also appears to be zero.  You should check that value to ensure it's correct and that it's at least 2 as 1 isn't less than. Otherwise when you go into the loop, i is 1 and receivedSize is zero (i is > receivedSize.)  So it fails to enter the loop, so no write.

uint8_t receivedSize = 0;

receivedSize = buffer[0];
for (uint8_t i = 1; i < receivedSize; i++)
     Serial.write(buffer[i]);

There may also be a logic problem. If you receive one byte, the receivedSize will be 1 and it still won't print.  Keep in mind that the array goes from 0 to limit and your 'data' lives starting in buffer[1].  Meaning if 6 characters are in the buffer only 5 (1 thru 5) will print. It may be much more clear to add the index at the position 'buffer[i + 1]' then the i can run it's normal 0 to n.


What speaker can you drive with output pin? I'm wondering how to drive a speaker using an arduino output pin.  I am using a pwm playback method with a sound data file.  If you wire a speaker across an output pin and ground then how do you calculate what speaker power and impedence you can use without damaging the arduino?  Is there a reference making these calculations?

Thanks

The Arduino can supply 5V at max 20mA so 5/0.02 ⇒ 250Ω (if you can find such a beast).

NOTE you should use a capacitor to prevent DC flow if using a conventional speaker.

In general the larger the speaker the better. Tiny speakers are inefficient transducers. Hi-Fi speakers are not a good choice, as they are often inefficient, trading efficiency for linearity.

An alternative, if you are a scrounger, is to scavenge a transformer from an old transistor radio - this should give the best match.


Vin pin vs USB vs Barrel connector: Wemos D1 R2 @Majenko says in the leading (19 Upvote) answer here not to use VIN and USB socket at the same time.

  You must never ever connect VIN to a power source and connect the USB socket. That can destroy the USB port in your computer. There is zero back-powering protection on [LoLin v3 board] board.

I need to do diagnostics on my Wemos (LOLIN) D1 R2 V2.1.0 while it's connected via 9-12V barrel jack and the Vin pin connected to an L9110H H-bridge as an output (bridge input).

Does the Wemos (LOLIN) D1 R2 V2.1.0 (ESP8266) work like this as well? Would I be able to run diagnosics with Serial through my USB socket while running this setup?

The D1 R2 uses the same power supply arrangement as the Arduino Uno (albeit with a better switching regulator for the 5V instead of the Arduino's basic linear regulator).

So it should be safe to use both the USB and the barrel jack at the same time.

The NodeMCU doesn't include a 5V regulator and doesn't have the power switching circuitry of the Uno / D1 R2, and thus is a completely different arrangement.


Recursive list of files on SD card with indexing I'm trying to create a way to make a recursive list of the long name of files from an SD card with an index so that I call the file I'd like. Right now, I'm having trouble getting the files to list (!CFile.open() is always returning true regardless of the number of files on the card)

#include<SPI.h>
#include "SdFat.h"
#include "FreeStack.h"

// SD card chip select pin.
const uint8_t SD_CS_PIN = 10;

SdFat sd;
SdFile file;
SdFile dirFile;

// Number of files found.
uint16_t numberOfFiles = 0;

// Position of file's directory entry.
uint16_t dirIndex[300];
//**Is there a way I make an array without allocating the size here?
//------------------------------------------------------------------------------
void setup()
{
  Serial.begin(38400);
  while (!Serial) {}

  // Initialize at the highest speed supported by the board that is
  // not over 50 MHz. Try a lower speed if SPI errors occur.
  if (!sd.begin(SD_CS_PIN, SD_SCK_MHZ(50)))
  {
    sd.initErrorHalt();
  }
  if (dirFile.open("/", O_READ))
  {
  Serial.print("Reading: ");
  Serial.println();
  printDirectory(&dirFile, 0);
  }
}
void printDirectory (SdFile* CFile, int numTabs)
{
  while (file.openNext(CFile, O_READ))
  {
    if (file.isHidden()||file.)
    {
      //file hidden, skip
    }
    else
    {
      for (uint8_t i = 0; i < numTabs; i++)
      {
        Serial.print('\t');
      }
      if (file.isSubDir())
      {
        file.printName(&Serial);
        Serial.println();
        printDirectory(&file, numTabs++);
      }
      else
      {
        // Save dirIndex of file in directory.
        dirIndex[numberOfFiles] = file.dirIndex();
        // Print the file number and name.
        Serial.print(numberOfFiles++);
        Serial.write(' ');
        file.printName(&Serial);
        Serial.println();
      }
    }
  file.close();
  }

If someone could help me catch what I've got wrong, I'd like to get a second opinion.

Edit: Updated Code

Edit 2: I'm now getting the first level, but the second level is not printing I think I may be doing something wrong with pointers?

dirFile.open("/", ...) opens the root directory which always exist, even if there are no files.

You can check if there are files by checking openNext. If the first call returns false, there are no files or folders.

Some unrelated remarks:

Name variables you use, with more than 1 character (so e.g. numberOfFiles instead of n)
Do not increase a variable inside a Serial.print statement .. if you remove the 'test/debug' code, your sketch behaves differently.

Update:

I now see your question about the array. 300 is probably what you assume is the maximum number of files. Note that if 300 is passed, the sketch will crash.

What you can do to prevent this:

Easy solution: stop storing files after 300. In this case, make 300 a constant.
Solid solution: do not use a predetermined length array. However, this means some disadvantages:

You have to create a list structure and dynamically change the code.
This is slower (probably not an issue since SD card communication is much slower)
It can result in memory gaps, resulting in hard to solve memory problems later if the code is extended and more memory is needed.

I suggest you add some code, to stop storing at 300.


Is it ok to power a Wemos D1 R2 placed outside with a smartphone charger? I'm currently playing with a wemos D1 R2 for some simple temperature / humidity logging on my balcony. For the moment the board is powered via its micro-USB entry by a small smartphone charger.

I've got two questions about this :

is there any "risk" (fire, explosion...) to let such a charger outside and plugged in continuously ?
will the charger use exactly the amount of current used by the board, or will it consume more energy than needed ?

Sorry, I realize these are really basic questions. Thanks in advance for any hint.

It might be okay, but it's better to play it safe. I would recommend putting the electronics (wemos/charger/extension cord) in a ziplock bag or plastic container designed to keep food in. You can cut holes for the sensors and power and then seal them in place. Have a look at this post. To answer your question. If water were to seep into the charger, it would have the potential to short the mains power in the charger. It could at the least ruin the charger. It might trip a breaker and or cause damage. Depending on the quality of the charger, water inside could expose the wemos to mains.
The charger may consume a small amount of extra power, but it once again depends on the quality. Apple chargers, for instance, do not. It won't be extreme, and is unlikely to go noticed, regardless of the charger.


Can't Turn Off Internal I2C Pull-Ups on ESP32 I've designed a custom ESP32 board around the WROVER-IE module. To keep power low, I'm using a GPIO-controlled high-side FET to turn off unused peripherals when in deep sleep mode.
The issue: I've pulled up an SSD1306 I2C OLED to this AUX rail. It works great when the device is awake. On setup() I start the OLED via ssd1306.begin() and from that point on, the SCL and SDA pins (22, 21) are always tied to 3.3V until I reset the ESP32.
The I2C bus always being tied to 3.3 ends up bleeding through the pull-up resistors and into the AUX rail, resulting unwanted current draw when in sleep mode.
Is there any way to turn off the internal I2C pullups on the ESP32?
Things I've tried so far:

Setting SDA, SCL as OUTPUT and writing LOW (does not work)
Setting SDA, SCL as INPUT and/or writing LOW (does nothing)
Calling gpio_hold_dis(gpio_num_t(SDA));(does nothing)

I'm now trying to dissect the esp32-hal-i2c.c lib but am not finding any fixes. Any help is greatly appreciated!
Edit, added diagram:

-N

I have solved this problem. For anyone who would like to turn off the internal pullups on the I2C bus of the ESP32, you need to disable the entire driver before putting the device to sleep.
First, include the peripheral driver library from the IDF:
#include "driver/periph_ctrl.h"

Next, call the following before sleep:
rtc_gpio_isolate(gpio_num_t(SDA));
rtc_gpio_isolate(gpio_num_t(SCL));
periph_module_disable(PERIPH_I2C0_MODULE);
digitalWrite(SDA, 0);
digitalWrite(SCL, 0);

This will stop the ESP32 from pulling up pins 21 and 22 while in deep sleep. Calling display.begin() or wire.begin() will restartthe driver upon wake.


Is it possible to get which pin generated interrupt? I wrote some code that handles rotary encoder using an interrupt, but I would like to get which pin generated the interrupt, so I'll be able to handle many interrupts in a single method.
Something like:

void ISREncoders()
{
  int pin = GetCurentInterruptPin(); // <============= this
  int dataPin = dataPins[pin];
  int data = DigitalRead(dataPin);
  if(data == HIGH)
  {
    encoders[pin] += 1;
  }
  else
  {
    encoders[pin] -= 1;
  }
}

Is it anyhow possible?

As mentioned in the answer this is not possible. Still, after peeking some encoder libraries that use interrupt found out that they do the following:
The Encoder class contains several static ISR methods hard coded.
As you create new objects it increments an internal counter and sets proper ISR method on the interrupt.
This is for sure the best solution available, but this is not at all scalable, for instance if you have an imaginary board with thousand pins that handle thousands encoders you will have to hard code each ISR method.

It is not possible to know which interrupt caused the ISR to be called. The INTFx flag gets cleared when the interrupt routine is called, so you lose that information (which is a shame).
The closest you could do is to have a separate ISR for each pin which just calls the common routine with a parameter to say which ISR it was executed via. That will add some extra latency though as it has to make an extra function call, but that can be somewhat mitigated by having the common function marked as always_inline, which means the compiler will duplicate it and place it within the code where it's being called from. This reduces latency but increases code size.
static ISREncoder(uint8_t pin) __attribute__ ((always_inline)) {
    // Do stuff with the `pin` variable
}

void ISR0() { ISREncoder(2); }
void ISR1() { ISREncoder(3); }


Delay a part of the void loop I have two different programs written for my Arduino. One checks the room temperature every 5 seconds. The other one looks for IR remote signals.

I would love to combine those 2 programs, yet the problem is the delay from the room temperature sketch.

If I would combine them. it means my IR script won't be working for a full 5 seconds (because of the delay of the room temperature script) then it will be able to receive a fraction of a second and then the temperature sketch goes again.

#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
int led = 12;
const int inPin = 0;

void setup() {
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop() {
  int value = analogRead(inPin);
  float millivolts = (value / 1024.0 ) * 5000;
  float celsius = millivolts / 10;
  Serial.println(celsius, 1);
  delay(5000);
  if(irrecv.decode(&results)) {
    //this checks to see if a code has been received
    if(results.value == 0xFF6897) {
      //if the button press equals the hex value 0xC284
        digitalWrite(led, HIGH);
        // turn the LED on (HIGH is the voltage level)
        delay(1000); // wait for a second
        digitalWrite(led, LOW);
        // turn the LED off by making the voltage LOW
        delay(1000); // wait for a second//do something useful here
    }
    irrecv.resume(); //receive the next value
  }
}

Does anyone know how to keep the IR part active and the temperature measure every 5 seconds, and do this simultaneously?

Or do I need another Arduino?

does anyone know how to keep ...

think about ways to conditionalize execution on time elapsed. I showed a short while ago ways to construct a software timer and you may want to look into that.


Help with parts identification from arduino starter kit from aliexpress Ordered an arduino starter kit from aliexpress Link

The parts list they provide (as a jpg on the order page) is vague and not very descriptive, I've gone through most of the parts and am down to three they did not list.

Capacitor? -- Looks to be a capacitor, labeled HDX and nothing else, rattles when I shake it.

Black LED -- I think this is a flame sensor; if it is, what's the difference between this and an infrared receiver (like a 1838B) or photoresistor?

They also list something as 'a digital control' near the bottom of the list, not sure what that is? Every other part from the list is matched up and I don't see anything different in the first picture (not parts list picture) from what I have received in the order.

Those are tilt sensors. The rattling is a metal ball that contacts two pins inside, closing the connection.
The 1838B is a full module that partially decodes the received IR so that a MCU can fully decode the rest easily. What you have there is a bare phototransistor with an IR window on the top. You would use it for proximity or presence sensing. Instead of varying its resistance, it varies the amount of current it will pass.
Probably the single-digit 7-segment display, as opposed to the 4-digit display they have listed as "4 digital tube".


Trying to save .wav files with new name every loop I have built a set up with an Arduino UNO hooked up to a switch, so that whenever the switch goes from HIGH to LOW it saves audio to an SD card. I am using the TMRpcm Library. The problem is the current code will only be able to record 1 audio file; I want to the Arduino to run for a long period of time collecting multiple audio files as the switch is turned on and off. I need a way that will allow it so everytime the switch is pushed back down the next file saved will have a different name than the one previously saved (preferably by an increased numeric value eg "1.wav" & "2.wav"). I have tried audio.startRecording(audiofile+".wav", 16000, A0); and it makes it so no files save to the SD card accept an empty file simple titled 'WAV'. I have tried using a switch case but it will not allow me to reach a case over 10, without running out of RAM. Currently, my code can save 1 audio file but I want it to reach a point where it can save as many as the SD card can hold, without having to restart the software.

My current code is here. Any help would be greatly appreciated

//////////////////////////////////////// SD CARD
#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#define SD_ChipSelectPin 10
TMRpcm audio;
//////////////////////////////////////// SWITCH CASE
int audiofile = 0;     // # of recording
unsigned long i = 0;
bool recmode = 0;      // recording state
//////////////////////////////////////// SWITCH
int inPin = 2;         // input Switch Pin
int state = HIGH;      // the current state switch
int reading;           // the current reading from the switch

void setup() {
  Serial.begin(9600);
  pinMode(A0, INPUT);  // Microphone
  pinMode(inPin, INPUT_PULLUP); // Switch
  //////////////////////////////////////// SD CARD
  SD.begin(SD_ChipSelectPin);
  audio.CSPin = SD_ChipSelectPin;
}

void loop() {

  reading = digitalRead(inPin);
  ////////////////////////////////////////
  while (i < 300000) {
    i++;
  }
  i = 0;
  ////////////////////////////////////////
  if (reading == LOW) {
    if (recmode == 0) {
      recmode = 1;

      Serial.println("Recording");

      audiofile++; // To move case
      audio.startRecording("1.wav", 16000, A0);
    }
  }
  ////////////////////////////////////////
  else if (reading == HIGH) {
    recmode = 0;

    Serial.println("Hung-Up");
    audio.stopRecording("1.wav");
  }
}

I would (and do) use snprintf to format a string as a filename:

// Global scope, or local static
uint32_t myFileNumber = 1;
char filename[12];

// in your function - results in 00000001.WAV
snprintf(filename, 12, "%08d.WAV", myFileNumber);

%08d will allow between 00000000.WAV and 99999999.WAV and always with 8 digits. Any more and it will get truncated and corrupted (100000000.WA) but won't cause a buffer overrun. You will have to take precautions that you never have more than 100 million files ;)


How to prevent file overwriting in processing? i am working on this arduino project using processing. There are some sensor values which should be logged, but unfortunately my processing code rewrites the file after each cycle so that i get the last sensor value only. How do i prevent this from happening? I am using the ordinary method by the way. PrintWriter command followed by createWriter

PrintWriter pw = new PrintWriter(new FileOutputStream(
    new File("persons.txt"),
    true /* append = true */));

The true is the append mode flag.
Also check if you're using

pw.append(p.toString());
        pw.append("sdf");

https://stackoverflow.com/questions/8210616/printwriter-append-method-not-appending


ATtiny85 MIDI IN with less than 3V -can it be done? I've been trying to add a MIDI INput to an ATtiny-based synthesizer, powered by a CR2032 battery (3v) and running softwareSerial.

Currently I'm using an H11L1 optocoupler, which works fine at 5v, but I am missing notes at 3V; I'm not sure whether the problem is the optocoupler, or that the ATtiny can't establish proper communication on that voltage; any pointers will be much appreciated :)

The H11L1's minimum supply voltage is 3 V.
There are low-power optocouplers like the TLP2361, but event those do not go below 2.7 V. (And those limits are actually designed for 3.3 V ± 10 % or 3.0 V ± 10 %.)

To get a high-speed optocoupler for lower voltages, you have to build it yourself from discrete parts, e.g.:

(R1 is sized for the PC817-A's minimum CTR of 50 %; higher CTRs should use a lower value for R1. Q1 can be any random small-signal transistor. Adjust R2 for about 1 mA, depending on VCC.)


X and Y axis on Arduino Serial Plotter? I am trying to plot my counter vs. time on the serial plotter, but the values on the y axis are so big there is no way that it's displaying the counter values.
I have printed both values:

  Serial.print("counter: ");
  Serial.println(counter);
  time = millis();
  Serial.print("Time: ");
  Serial.println(time);

I expected time to show up in the x-axis, but I think it's displaying on the y-axis and I'm not sure how to change this.
The plot should just be an increasing line as the counter and time get bigger...
what am I missing?
Thanks.

Slashing out the Serial.print("Time:") does not correct anything.

Inorder to plot multiple variables or waveforms simultaneously a 'space' is printed between the two print statements.

Serial.print(counter);
Serial.print(" ");
time = millis();
Serial.println(time);

OR

Serial.print(counter);
Serial.print("\t");
time = millis();
Serial.println(time);


What is the lowest resistance pot that is useful with an analog input? Background

I've dabbled in electronics since my parents gave me a 150-in-1 kit in the 1970's but never had formal training. My dad repaired Honeywell mainframes so taught me to solder when I was 8. I have a decent set of equipment like irons, parts, meters, etc. and realize I know enough to be dangerous, which is why I avoid mains-powered stuff.  I'm not a newbie but am all too aware of the many holes in my knowledge.  I'm doing this for fun and in a way that allows for failures to be expected, cheap, and educational.

Project

I have a WS2812b LED strip connected to an Arduino Uno and am using various animation libraries to drive it. The goal is to move to a pro mini once the hardware is more settled and use it for creative lighting inside my house or garage.  I started with just the strip and let it display different animations in a sequence based on time but then wanted to attach a button which would advance to the next animation.  After implementing debouncing it worked fine and I moved on to adding a potentiometer to select the speed of the current animation; increasing or decreasing the delay between each 'frame'.  Of interest here is I was using old pots (panel mount not for typical board use - hence I had to solder wires to them just to use them in any configuration) and not doing any ohms law calculations, just hooking up the hardware and tuning the values for mapping the detected voltage to the desired delay by checking printed output from the serial monitor.

I'm happy with the general setup when using a breadboard but when I went to solder something more permanent on perfboard I ran into a problem; the speed control wouldn't work.  I'm sure the first pot I used was 10k but when I checked it with the meter it registered as completely open so I figured I had blown it. Thinking that I needed to control the current I read posts like this one and this one about limiting current I felt better and proceeded to replace the pot with a 25 ohm version thinking that the only difference would be in calibrating the values for mapping the detected voltage to the desired delay.  The behavior I got was randomly fluctuating values for the delay and when I hooked up the prototype using USB to my laptop I could see that the analogread() values were fluctuating wildly within a range even when I wasn't manipulating the pot yet nothing I did could get it to be consistent.  My first thought was that there was a problem with ground so I rechecked the connections but they all tested fine, including still reading 25 ohms along the outside terminals and varying values on the wiper consistent with rotating it along its path from end to end.  When I gave up on my protoboard and returned the circuit back to the breadboard I replaced the full size pot with a 10k small one meant for breadboards and the speed control works again.  This leads to my question.

Question

Is there a minimum value for a potentiometer connected to an analog input of an arduino, or is it more likely that there was an issue with my soldering job on the protoboard?  I don't have a picture of the board because I've already desoldered components from it but I can tell you that it was my first attempt at perfboard soldering and it would not win any prizes, sort of the 'face only a mother could love' sort of thing. If it matters, I was using analog input A2.

Assuming you wired it correctly (ie. you put the wiper to the analog input) your first setup looked like this:

Your big problem here is the current flow through the pot. Using Ohms Law the current would be:

I = V / R
I = 5 / 25
I = 0.2A  (200 mA)

That is too much to be drawing from the 5V pin and it could easily drag down the voltage to the rest of the board. Also the power would be:

W = I * V
W = 0.2 * 5
W = 1W

One watt is a lot to put through a pot, and you may well have burned the track inside it.

  So, if I included a 10k resistor on either side of the pot that should address the current issue but it leaves the question of whether the remaining 25-ohm range is too small for the ADC to register distinct values, ...

The 10k resistor will stop the current problem, but now the range in the voltage divider will be ridiculously small. The setup will now look like this:

Unfortunately the range you are going to read with the analog input is going to be (voltage divider formula):

Vout = Vin * (R2 / (R1 + R2))

With the wiper at one end R1 will be 10000 and R2 will be 10025 and with the wiper at the other end it will be vice-versa. So the voltage you get will be:

Vout = 5 * (10000 / (10025 + 10000))
Vout = 5 * 0.499
Vout = 2.497

Or:

Vout = 5 * (10025 / (10025 + 10000))
Vout = 5 * 0.501
Vout = 2.503

In other words you will always be reading about 2.5V and therefore your analog read will always return around 512, which won't be much use to you.

  I'm going with a larger value pot (10k or 25k) ...

That sounds like a sensible value. A 10k pot will only draw:

I = V / R
I = 5 / 10000
I = 0.5 mA

That is a reasonable current draw and the analog input will still read it fine.

As Majenko points out in his answer you don't want a whole lot more than that resistance because of the optimal input impedance of the ADC converter (10k). A very high resistance would mean only a small current would flow into the analog input pin.

How to use your 25 ohm pots

If you want to use your existing 25 ohms pots because of their physical appearance, then a  small resistor in series could reduce the current to a reasonable amount and still give a good reading range. For example, 330 ohms on the "high" side (and nothing between the low side and ground).

Vout = 5 * (330 / (355 + 330))
Vout = 5 * 0.193
Vout = 0.963

Or:

Vout = 5 * (355 / (355 + 330))
Vout = 5 * 0.581
Vout = 2.591

That is now going to give you a reading between 0.96V and 2.59V which, whilst not the full range of 0V to 5V should give you reasonable differentiation as you turn the pot. And the current through it would be:

I = V / R
I = 5 / 355
I = 0.014A (14 mA)

Thus the power would be:

W = I * V
W = 0.014 * 5
W = 0.070 (70 mW)

References

Voltage Dividers tutorial
Ohms Law


Unintended reaction: Sketch makes LEDs turn on and of randomly/LEDs don't react Update: This piece of code does not do the same as the one in the right answer, it also reacts when one lets go of the button.

int button_prev = 0;
int button = 0;

void loop(){

    button_prev = button;

    button = digitalRead(12);

    if (button_prev != button) {

      digitalWrite(act_pin[j], HIGH);

      j = (j+1) % 5;

    }
}

I printed out j and it seems like, instead of counting up +1 everytime the button is pressed once, it turns +1 and then +1 again which makes two LEDs at a time turn on.
But I don't see where the behavior of j comes from...

[Update: There was a mistake in the code which caused the random behavior, but now, nothing happens when I push the button.]

[I wrote a sketch which is supposed to make the Arduino turn one of five LEDs on one after another every time I press the switch.

But instead of turning one LED on after another, directly after upload it just makes them turn on and of at random. I don't push the button.
Serial.println as well just spits out one character, similiar looking to a d.]

Can anyone point out my mistake to me?

This is the circuit

and this is the old code of the sketch

int act_pin[6] = {A0, A1, A2, A3, A4};

int j = 0;

void setup(){

  Serial.begin(9600);

  for (int k = 0; k < 5; k++) {

     pinMode(act_pin[k], OUTPUT); //sets analog pins A0 - A4 as output

     digitalWrite(act_pin[k], LOW); //turns LEDs connected to A0 - A4 off

     pinMode(12, INPUT); //sets pin connected to button as input

}

}

void loop(){

  char button = {digitalRead(12)}; //stores if the button was pressed

  Serial.println(button);

  if(button == HIGH){

    digitalWrite(act_pin[j], HIGH); //turns LEDs on A0 - A4 on one after one with every button press

    j = (j+1) % 5; //makes digitalWrite jump to the next LED next time the button is pressed and limits it to 4

    button = LOW; //turns the button's pin low again, so nothing will happen until the button is pressed again
}

}

Your code has a serious bug here:

if(button == HIGH){

    digitalWrite(act_pin[j], HIGH);

    j = j+1;

    button = LOW;
}

You increment j without any boundary so it will have the following cycling values:

0, 1, 2, 3 ... 32767, -32768, -32767 ... -1, 0 ...

Hence, quickly act_pin[j] will return garbage...

The solution is easy, you must limit j to [0,1,2,3,4], just replace the j = j + 1 line as follows:

j = (j + 1) % 5;

% is the modulo integral operation that will give you the reminder of dividing j by 5, which is always strictly less than 5, and it cycles as you want.


Setting the frequency of a timer interrupt The concept:
Play a sine wave saved as a character array in PROGMEM through an 8-bit DAC connected to the PORTC pins on the Arduino Mega.
This works:
// File just defines an array and a size

#include "sine440.h"

int i = 0;
void setup() {
  DDRC = B11111111;
}

void loop() {
  PORTC = pgm_read_byte(&sine[i++]);
  if(i >= sine_size){
    i = i - sine_size;
  }

  delayMicroseconds(60);
}

The above code produces a sine wave of about 440 Hz, exactly what I wanted. Now, I'd like to move this into an interrupt routine, as follows:
This doesn't work
#include "sine440.h"

int i = 0;
void setup() {
  DDRC = B11111111;
  TCCR5B = (1 << WGM52) | (1 << CS50 );
  OCR5A =  16000000/16000;
  TIMSK5 = (1 << OCIE5A);
}

ISR(TIMER5_COMPA_vect){
  PORTC = pgm_read_byte(&sine[i++]);
  if(i >= sine_size){
    i = i - sine_size;
  }
}

void loop() {

}

The above code produces a sine wave of 1721 Hz. I know that this means it's iterating through the array too fast, but I don't know how to change it. In order for it to produce 440 Hz, it needs to be preforming 16,000 iterations per second, which is what I believe  OCR5A =  16000000/16000; does. But it doesn't appear that changing the value of OCR5A does anything at all. Giving it the max value of 65,535 still produces a 1721 Hz sine wave...
So what am I doing wrong here? How do I change the speed of this timer interrupt?

I second BrettAM's comment. The Arduino IDE sets most of all the timers up for PWM, and I had to comment out a section once to use my own ISR with Timer 3 on a 32u4, because no matter where or how I set it, the CTC interrupt never went. The WGM50 and CS51 are set at the start of the Arduino files basically, so that messes with your settings.

You will need go into the Arduino core files. This is $install_path/arduino-1.x.x/hardware/arduino/avr/cores/arduino/, and under that directory you need to find file wiring.c. This file contains all the setup of the timers for PWM and the millis() or micros() functions.

Go to line 342. Located there is this:

#if defined(TCCR5B) && defined(CS51) && defined(WGM50)

  sbi(TCCR5B, CS51);           //set ter 5 prescale factor to 64
  sbi(TCCR5B, CS50);
  sbi(TCCR5A, WGM50);         // put timer 5 in 8-bit phase correct pwm mode

#endif

Here you can place another #if defined() macro around this, resulting in:

#if !defined(doNotSetTimer5)

  #if defined(TCCR5B) && defined(CS51) && defined(WGM50)

    sbi(TCCR5B, CS51);           //set ter 5 prescale factor to 64
    sbi(TCCR5B, CS50);
    sbi(TCCR5A, WGM50);         // put timer 5 in 8-bit phase correct pwm mode

  #endif

#endif

Now when you want to use your custom settings, you will put the following at the top of your .ino file:

#define doNotSetTimer5
#include <wiring.c>

That does not block the Arduino environment from setting up Timer 5 when compiled with other code, but only when you want to use custom settings (changed because of @Gerben's suggestion). When you change these settings you will lose PWM on 3 pins: 44 45 46. But you will be able to make use of setting your own PWM up or a CTC ISR().

This doesn't mess with anything else and is the easiest way to do it.


Timer1 firing immediately I'm trying to use Timer1 to get fired once a certain event occurs (about 1ms after the event). Using the timer to get a periodic interrupt works fine, but the very first interrupt fires immediately, rather than after the time I want it.

#include <Arduino.h>

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

#define ENTRIES 5
long stack[ENTRIES+1];
int ctr = 0;

ISR(TIMER1_OVF_vect) {
  cli();
  TCNT1 = 50000;

  // if (micros() - stack[0] < 500) return; // work around guard would skip stray 1st interrupt

  stack[ctr++] = micros();

  if (ctr > ENTRIES)
    TIMSK1 &= ~(1 << TOIE1);

  sei();
}

void loop() {
  if (ctr > ENTRIES) {
    for (int i = 0; i < ENTRIES-1; i++) {
      Serial.print(i);
      Serial.print(": ");
      Serial.println(stack[i+1] - stack[i]);
    }
    ctr = 0;
  }

  if (!Serial.available()) return;
  char c = Serial.read();
  if (c == 't') {
    Serial.println("testing");

    stack[0] = micros();
    ctr = 1;
    cli();

    TCNT1 = 64000; // tick in around 1ms
    TCCR1A = 0;
    TCCR1B = (1 << CS10); // no prescaler
    TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt

    sei();
  }
}

When you enter t on the console it enables the interrupt and - unexpectedly - the timer fires at once. The next one comes after 1ms. A sample output looks like

start
testing
0: 8
1: 980
2: 980
3: 980
testing
0: 8
1: 980
2: 980
3: 980

Uncommenting the guard yields

start
testing
0: 988
1: 972
2: 976
3: 976

How can I modify my code (except setting a guard in the beginning of the ISR) so it is triggered once AFTER 1ms.

Interrupt flags are set even without interrupt enable flags, so there is pending overflow that you didin't cleared. And guess what happens after enabling TOIE1 flag. It gets handled by ISR. That's on behalf of Arduino's analogWrite() PWM outputs (all timers are up and running in 8bit mode and 1.024ms period).

Btw global interrupts are disabled and reenabled inside of ISR handler by hardware so you shouldn't have cli() and sei() in it.

Also there is another issue - counter mode is preset to 8bits and much bigger prescaler, so the first round is way off.

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

#define ENTRIES 5
long stack[ENTRIES+1];
int ctr = 0;

ISR(TIMER1_OVF_vect) {
  TCNT1 = 50000U;
  stack[ctr++] = micros();
  if (ctr > ENTRIES)  TIMSK1 &= ~(1 << TOIE1);
}

void loop() {
  if (ctr > ENTRIES) {
    for (int i = 0; i < ENTRIES-1; i++) {
      Serial.print(i);
      Serial.print(": ");
      Serial.println(stack[i+1] - stack[i]);
    }
    ctr = 0;
  }

  if (!Serial.available()) return;
  char c = Serial.read();
  if (c == 't') {
    Serial.println("testing");

    stack[0] = micros();
    ctr = 1;

    TCCR1A = 0;           // you have to change the timer mode before changes
    TCCR1B = 0;           // stop the timer
    TIFR1 |= _BV(TOV1);   // clear the overflow interrupt flag by writing 1 to it
    TCNT1  = 50000U;      // tick in around 1ms / this makes more sense if it's set correctly
    TCCR1B = _BV(CS10);   // no prescaler ?????  REALLY???? this one is prescale by 8
    TIMSK1 |= _BV(TOIE1); // enable timer overflow interrupt
  }
}


HG-C 1100 measurement sensor I am using two HG-C 1100 measurement sensor for measuring the width of the metal. In the top of the sensor I will be having the measurement value. The sensor is capable of measuring the dimensions from -35mm to 35mm.
So I am using the formula:
int First_sample = analogRead(6);
int Second_sample = analogRead(7);
float First_sensor = (map(First_sample, 1023, 0, -3500, 3500) / 100.0);
float Second_sensor = (map(Second_sample, 0, 1023, -3500, 3500) / 100.0);
Serial.print("First_sensor:");
Serial.println(First_sensor, 3);
Serial.print("Second_sensor:");
Serial.println(Second_sensor, 3);
Final_sensor = (First_sensor - Second_sensor);
Serial.println(Final_sensor, 4);

If I use this code, I will get the proper width of the metal. But when I place the metal in between the sensor, I am getting the exact width in the serial monitor. But at the top of the sensors the values are different.
I don't why the analog values are different on the serial monitor and the top of the sensors. But the output of the sensor is perfect in the serial monitor.
Can anyone help me with this?

The HG-C1100 has a resolution of 70 μm (= 0.07 mm) over a measuring range of 70 mm.
You quote errors of 0.28 and 0.38 mm, which is worse than can be expected (±0,07 mm).
The resolution is 1‰ of the measuring range. Therefore the 10 bits range (1024) of the Arduino's Analog-Digital Converter (ADC) is sufficient.
You map the ADC output of 0-1023 to a range of -3500 to +3500 which results in a value in 0,01 mm. Then you divide by 100.0 resulting in a value in mm.
According to Arduino's Reference the function map() uses integer arithmetic, but the arguments are longs and the calculation order is such that maximal accuracy is maintained. This provides sufficient accuracy for this purpose. I am only not sure if you constants should be post fixed wit an "L".
So far everything looks all right.
The errors you mention correspond to about 5 counts of the ADC.
I assume the solution lies in taking measures to prevent noise entering your signals (signal conditioning).
Addition:
When you read the same sensor repeatedly do you get stable readings? You could try to use an average over multiple readings. Did you look at the signal(s) with an oscilloscope?


Question about Variables is there a way to use a previous assigned value to variable to adjust the step motor? what i mean is:

example:
Sensor reads 100 degrees so

Adjust the step motor to 100 degrees and hold, then after 10 min

the sensor reads 110 degrees so

Adjust the step motor (110 - 100) by extra 10 degrees

and so on..

I'm really new to this and i'm sorry if that's a stupid question :<

Based on your description, the program needs to know only the new target setting and the current position. That means you need two variables. Algorithmically, it would look as follows (written in C-like pseudo-code):

// initialize global variables (might need float instead of int)
int target_pos = 0;
int current_pos = 0;

void setup() {
    // add code to set up pin IO mode, prepare communication with the sensor...
}

// function to read the sensor
int ReadSensorFunc(void) {
    int reading = 0;   // local variable to store sensor reading
    reading = ...;     // add code to read sensor
    return reading;
}

// function to adjust the motor position
void AdjustStepMotorFunc(void) {
     // add code to to adjust the stepper to (target_pos-current_pos);
}

void loop() {  // repeat forever
    target = ReadSensorFunction()   // call sensor read function
    AdjustStepMotorFunc()           // call position adjustment function
    current_pos = target_pos        // update current position
    // add code to delay for 10 minutes
}

This code initializes the position as zero. In case it's not zero when the controller is turned on, you'll need additional code in setup() to assign current_pos the correct value based on user input.


Why can't the new Arduino IDE 1.6.7 compile extern "C"? Consider:

I having a problem in compiling in extern "C" code in the Arduino IDE 1.6.7 which I don't have on version 1.6.5.

The error is:

  error: conflicts with new declaration with 'C' linkage

It is complaining about the lines containing loop() and start_timer(void);.

This is my code:

#ifdef __cplusplus
extern "C" {
#endif

void start_timer(void);

#ifdef __cplusplus
}
#endif

void start_timer(void)
{
    Serial.println("2");
    Serial.begin(9600);
    delay(2000);
}

void setup()
{
    start_timer();
    Serial.println("4");
}

void loop()
{
    Serial.println("1");
    delay(2000);
}

I can't reproduce your problem still. See this:

However if you are having problems (and frankly I expected you to) then you should read this:

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

How the IDE organizes things

I can reproduce your problem in IDE 1.6.5 (not 1.6.7). The code generated by the IDE preprocessor is this:

#line 1 "sketch_jan11a.ino"
#ifdef __cplusplus
#include "Arduino.h"
void start_timer(void);
void setup();
void loop();
#line 2
extern "C" {
#endif

void start_timer(void);

#ifdef __cplusplus
}
#endif

void start_timer(void)
{
    Serial.println("2");
    Serial.begin(9600);
    delay(2000);
}

void setup()
{
    start_timer();
    Serial.println("4");
}

void loop()
{
    Serial.println("1");
    delay(2000);
}

You can see that in the automatic function prototype generation that the IDE "helpfully" generates for you, it puts the prototype for start_timer outside the extern "C" declaration. Thus one function prototype has a declaration in C++ format, and the other in C format.

Why are you even doing this? I presume this is a small example of a larger problem.

If you follow the suggestions in my link How to avoid the quirks of the IDE sketch file pre-preprocessing - did you read that? - the problem goes away, because .cpp files in IDE tabs are not subjected to this extra processing.


else if is ignored if not Serial.println anything before I encountered to me inexplicable behavior on an arduino uno.
I'm serial reading a string from the serial monitor/python serial. This string is the conditional on several if/else if statements.
The crazy thing is, some strings just get ignored, but if I print out the read string after reading it, the ignored statements then get executed and the script works the way it's supposed to.
This is the code:
// power outlet 1
# define OUT_1_1 2 // relay #4
# define OUT_1_2 3 // relay #3

// power outlet 2
# define OUT_2_1 4 // relay #2
# define OUT_2_2 5 // relay #1

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  // power outlet 1
  pinMode(OUT_1_1, OUTPUT);
  pinMode(OUT_1_2, OUTPUT);

  // power outlet 2
  pinMode(OUT_2_1, OUTPUT);
  pinMode(OUT_2_2, OUTPUT);

  // init outputs to HIGH
  digitalWrite(OUT_1_1, HIGH);
  digitalWrite(OUT_1_2, HIGH);
  digitalWrite(OUT_2_1, HIGH);
  digitalWrite(OUT_2_2, HIGH);

  Serial.begin(9600);
}

void loop() {
  String str = "";

  // checking for bytes in the buffer
  if (Serial.available() > 0) {
    str = Serial.readStringUntil("\n");
  }
  // Serial.println(str); // if this line is uncommented serial input "2_ON\n" and "2_OFF\n" is recognized and outled 2 is successfully switched

  // identity
  if (str == "IDN\n") {
    Serial.println("Serial Power Outlet");
  }

  // controlling power outlet 1
  else if (str == "1_ON\n") {
    digitalWrite(OUT_1_1, LOW);
    digitalWrite(OUT_1_2, LOW);
  }
  else if (str == "1_OFF\n") {
    digitalWrite(OUT_1_1, HIGH);
    digitalWrite(OUT_1_2, HIGH);
  }

  // controlling power outlet 2
  else if (str == "2_ON\n") {
    digitalWrite(OUT_2_1, LOW);
    digitalWrite(OUT_2_2, LOW);
  }
  else if (str == "2_OFF\n") {
    digitalWrite(OUT_2_1, HIGH);
    digitalWrite(OUT_2_2, HIGH);
  }
  delay(1000);
}

If I serial input 2_ON\n or 2_OFF\n the according else if blocks are just ignored (all other inputs work correctly).
But after I've uncommented // Serial.println(str); these blocks are executed the way they are supposed to and all works just fine.
Where is my mistake, what am I getting wrong here?
These blocks also get executed if I Serial.println any random output.
Why do I have to Serial.println something first so my script works according to plan? What am I missing?
EDIT: added all of the code.

Even though you read until \n, that just controls the ending of your buffered string.  It does not control it's start.  There may be some garbage before the command that you have not cut out.  In other words, I suggest you check if the string endsWith as opposed to == the command string.
As for what noise could be causing garbage or why activity on the tx side of the serial cleaned it up, i do not know.  Heck something might just be weird enough in the wiring that '2' is just the set of bits needed to aggravate it.


Arduino Hardware serial pins with RS485 I tried asking a question in my earlier post - SerialEvent with RS485 communication it helped me understand Hardware serial and Software serial but i had few more questions for which i started this new thread. Now i didn't write any code yet, but i will be using same code as my earlier post if i get expert inputs.

My Project - I have 6 Arduino nano which will do some simple task, mostly its one way communication at a time, like once master send message to slave i don't want immediate response slave will push button or something and then it will send response to master. So its rare that i will have two way communication at same time.

RS485 - I am going to use RS485 as distance is around 40ft.

Now my questions -

1 - Can i use Hardware serial pins with RS485 for 40ft distance, i tested code and it does work but i couldn't test that for 40ft. So not sure if it works or not.

2 - Is it good idea to use hardware serial pins for my project i explained, as i see plus and minus over internet and making me confuse. I see majority people recommend Hardware pins though.

3 - Is there limitation connecting multiple arduino nano with this approach, i only did this with 2 so far.

I would appreciate your inputs, which will make me decide to go on right path. Sorry i didn't post any code because my post is more to understand correct path to be followed...

1 - Can i use Hardware serial pins with RS485 for 40ft distance, i tested code and it does work but i couldn't test that for 40ft. So not sure if it works or not.

Yes.

  2 - Is it good idea to use hardware serial pins for my project i explained, as i see plus and minus over internet and making me confuse. I see majority people recommend Hardware pins though.

Yes. SoftwareSerial is awful.

  3 - Is there limitation connecting multiple arduino nano with this approach, i only did this with 2 so far.

Yes. The MAX485 and similar chips can only handle up to about 30 devices on one bus. The exact number is in the datasheet for the chip.


Error in Arduino Library file I am working on a project which includes Arduino and a fingerprint scanner. It is completely based on embedded system. But then, I have downloaded a library for the fingerprint scanner. When I run the program I get an error which maps to the cpp file of the library file. See below to see the error and the library file.

Error

  FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function
  Command_Packet::GetPacketBytes()':
  C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:17:
  undefined reference tooperator new[](unsigned int)'
  FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function
  FPS_GT511C3::GetResponse()':
  C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:735:
  undefined reference tooperator new[](unsigned int)' collect2.exe:
  error: ld returned 1 exit status

Library File (CPP)

  byte* packetbytes= new byte[12];

  byte* resp = new byte[12];

The core of the problem is that the code is being compiled as C and not C++.

The error says 'new[]' is undefined at the link stage.  This is because the linker is not pulling in the C++ standard libraries.  The built-in function new[] it doesn't exist in C.

The filename FPS_GT511C3.c.cpp is the elephant in the room.  You could consider renaming it (and others) to FPS_GT511C3.cpp.  Although the plain Arduino IDE does not really have a problem with building them.

Another option might be to modify the new[] (and delete[]) for C's malloc() and free().  However this is only appropriate for the allocation of simple types (byte, int, etc).  If the code also allocates objects, it's not possible to simply swap these functions out since C++ (default) initialisation is be going on.


Pass Color to a function without using a specific Adafruit_NeoPixel I'm initializing my strips as an array:
// Declare NeoPixel strip array:
Adafruit_NeoPixel strip[] = {
  Adafruit_NeoPixel(LED_COUNT[0], LED_PIN[0], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[1], LED_PIN[1], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[2], LED_PIN[2], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[3], LED_PIN[3], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[4], LED_PIN[4], NEO_RGBW + NEO_KHZ800)
};

and when I pass Color to a function, I'm arbitrarily using my first strip to create the Color:
  everyother( strip[0].Color( 0, 255, 0), strip[0].Color( 255, 0, 0), 500);

but in the subroutine I use those colors to set pixels to every strip of the array in a loop:
// set every other color to color1 or color2
void everyother( uint32_t color1, uint32_t color2, int wait) {
  for(int k=0; k<NUM_STRIPS; k++) {
    for( int j=0; j<LED_COUNT[k]; j++) {
      if( j%2 == 0) strip[k].setPixelColor(j, color1);
      else strip[k].setPixelColor(j, color2);
    }
  }
  for(int k=0; k<NUM_STRIPS; k++) strip[k].show();
  delay(wait);
}

Is there another way to define Color that isn't using a real Adafruit_NeoPixel? Yes, it works this way but it feels sloppy.

Looking at the library at https://github.com/adafruit/Adafruit_NeoPixel/blob/master/Adafruit_NeoPixel.h, you can see that the Color method is static (see line 307):
static uint32_t   Color(uint8_t r, uint8_t g, uint8_t b) {
  return ((uint32_t)r << 16) | ((uint32_t)g <<  8) | b;

This means instead of
strip[0].Color( 0, 255, 0)

You can use:
Adafruit_NeoPixel::Color( 0, 255, 0)

Your call to everyother will be:
everyother(Adafruit_NeoPixel::Color( 0, 255, 0),
           Adafruit_NeoPixel::Color( 255, 0, 0),
           500);

And since everyother is now not a good name, you can think of a better one, e.g. fillLeds (always start a method name with a verb).
Offtopic:

A subroutine is barely used anymore, I think the last time I heard it, is from the Basic programming language
A function is now used instead
But when a function is inside a class, it's not called a function, but called method.


ATTiny85 VirtualWire AnalogRead 1 My ATTiny85 is connected to a 433 transmitter and an analog sound sensor. The 433 is working fine (using VirtualWire) but when I send the reading from the sensor all I receive is a 1.

What I would like to receive is the value between 0 and 1024 like when I print the sensor to serial. I cannot check it because the ATTiny85 had no serial out.

My code is a combination of snippets I found online, I am not happy with all the magic to format the data that needs sending. I would also like to send "Reading: 637" in stead of just the number but I find the concatenation Google results extremely complicated.

Should this code send the sensor data like 672?
Could there maybe be some Fuse setting blocking the AnalogRead?

#include <VirtualWire.h>

const int transmit_pin = PB0;
const int sensor_pin = PB4;
int sensor_data;
char sensor_msg[4];

void setup()
{
  vw_set_tx_pin(transmit_pin);
  vw_setup(2000);
}

int count = 1;

void loop()
{

  sensor_data = analogRead(sensor_pin);
  itoa(sensor_data,sensor_msg,4);
  vw_send((uint8_t *)sensor_msg, strlen(sensor_msg));
  vw_wait_tx(); // Wait until the whole message is gone
  _delay_ms(1000);
  count = count + 1;

}

Receiver Code as requested
This is a Pro Mini (clone) and it has an LCD attached so I can see what is going on.

#include <VirtualWire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);

const int receive_pin = 11;
char* testje;
void setup()
{
    delay(1000);
    Serial.begin(9600); // Debugging only
    Serial.println("setup");

    // Initialise the IO and ISR
    vw_set_rx_pin(receive_pin);
    vw_setup(2000);  // Bits per sec

    vw_rx_start();       // Start the receiver PLL running

    lcd.init();
    lcd.backlight();
    lcd.home();
    lcd.clear();
    lcd.print("hello");
    delay(1000);
    lcd.clear();
}

void loop()
{
  char buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;

  if (vw_get_message(buf, &buflen)) {
    int i;
    // Message with a good checksum received, print it.
    Serial.print("Got: ");

    for (i = 0; i < buflen; i++) {
       Serial.print((char)buf[i]);
    }
    Serial.println();
    Serial.println(buf);
    lcd.clear();
    lcd.print(buf);
  }
}

I would double check the pin numbers for the attiny. They look like port bit numbers but that might just work by chance.

const int transmit_pin = PB0;
const int sensor_pin = PB4;

A quick double check with the attiny/pins_arduino.h give:

// ATMEL ATTINY45 / ARDUINO
//
//                 +-\/-+
// Ain0 (D5) PB5  1|    |8  Vcc
// Ain3 (D3) PB3  2|    |7  PB2 (D2) Ain1
// Ain2 (D4) PB4  3|    |6  PB1 (D1) pwm1
//           GND  4|    |5  PB0 (D0) pwm0
//                 +----+

As you have found they should be defined as:

const int transmit_pin = 0; // Physical pin 5
const int sensor_pin = 4;   // and pin 3

This type of issue could be avoided by using strong data typing and object oriented design. Please see for instance Cosa ATtinyX5.hh and GPIO.hh.

Cheers!

Here is something that does basically the same as the sender. Cosa supports attiny and Arduino boards "out-of-the-box".


strcmp doesn't seem to work I'm trying to compare a char array that I'm assembling to a string and I'm having trouble comparing the strings.
I'm getting the data for the char array as a set of bytes and I'm compiling it into a char array like this:
void messageHandler(char *topic, byte *payload, unsigned int length)
{
  char buffer[length];
  for (int i = 0; i < length; i++)
  {
    buffer[i] = (char)payload[i];
  }

So grabbing each of the ASCII codes and converting it into a character as I add it to the buffer.
After I do that I'm trying to print the buffer to the monitor and then compare it to a string. Though it's not working:

I know I'm getting all of those extra characters in the println b/c the buffer doesn't end in 0 so print keeps reading out memory bytes till it hits the zero, but I don't know why strcmp isn't showing the buffer matching the string "ravenclaw".
I'm sure it's for the same "missing the null terminator" issue, but I'm not sure how to fix it. Help is appreciated!!

You seem to already understand that it's not null-terminated and that's why it's not working the way you expect.  So, I'll take a different tact for "how to fix it".
You can simply not treat the payload as a string, and instead use memcmp, as in:
if (length == 9 && memcmp(payload, "ravenclaw", 9) == 0) {

memcmp behaves similarly to strcmp, except that it isn't looking for a null terminator. It just compares however many bytes (chars) you specify.  In practice you may want to use a variable to hold "ravenclaw" and to strlen() on it rather than specifying the length separately as I've done above, e.g.:
static const char ravenclaw[] = "ravenclaw";
static const size_t ravenclaw_len = sizeof ravenclaw - 1;
if (length == ravenclaw_len && memcmp(payload, ravenclaw, ravenclaw_len) == 0) {

or any number of variations on that which might use strlen(), or a pointer rather than array (if not using sizeof) or PROGMEM with strlen_P() and memcmp_P() or... etc, etc, possibly putting this into a function so you can reuse it.

As a side note, if you know payload contains non-null-terminated text that you want to print, you can use the overload of write() that allows you to specify the length.
Serial.write(payload, length);


How to write a function to return matrix? I need a function to return a 2x2 rotation matrix, something like:

float matrix(float phi){
  float R[2][2] = { {cos(phi), -sin(phi)},
                    {sin(phi),  cos(phi)} };
return R;
}

But it doesn't work obviously. What is the best way to write this function?

You cannot return an array from a function. There are several
alternatives, though. One of them is to allocate the memory for the
array within the function, as suggested by user2912328's answer. I would
not recommend this approach though, for the reasons already stated in
that answer.

For an overview of the other possible options, see this response to the
question “Returning an int array from a function”.

Now, your problem is slightly different, as you have a 2D array.
The C/C++ syntax for dealing with those is tricky, but here we go.

If you opt for the “static array” solution (make sure you understand the
implications), you could write:

float (*matrix(float phi))[2]
{
    static float R[2][2];
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
    return R;
}

and you would use it like this:

float (*M)[2] = matrix(angle);

If you instead let the caller manage the allocation, then

float (*matrix(float phi, float (*R)[2]))[2]
{
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
    return R;
}

Or maybe forgo the return value to make the syntax simpler:

void matrix(float phi, float (*R)[2])
{
    R[0][0] = cos(phi);
    R[0][1] = -sin(phi);
    R[1][0] = sin(phi);
    R[1][1] = cos(phi);
}

and you could use it like:

float M[2][2];
matrix(angle, M);

The “array in a struct” solution is more straightforward.

If the syntax for dealing with 2D arrays bothers you (which would be
understandable), you can instead use arrays of pointers to 1D arrays.
This are easier to deal with but trickier to allocate. That approach
could warrant another answer...

Edit: One common way to simplify a convoluted array syntax is to use
typedefs. As an identifier for a 2x2 array decays to a pointer to an
array of 2 floats, you can name that type:

typedef float (*pmatrix)[2];  // pointer to an array of 2 floats

Then, instead of

float (*matrix(float phi))[2] { ... }
...
float (*M)[2] = matrix(angle);

you would write

pmatrix matrix(float phi) { ... }
...
pmatrix M = matrix(angle);


List of connected clients to server I have a server on my arduino (WiFi) and want to save the clients that connect, so that I can send to them (to each separately) data later.

Is the best data structure a linked list? How can I see if this client connected already (if there is already a connection to this ip) to avoid doubles? How can I detect when they disconnect in order to delete them?

Of course, I read the ref; but I cannot find the answers there.
Here is my minimal example (The maximum number of simultaneous connections is 5):

EDIT Keep in mind, that I just want to have a simple connection using the WiFiClient/ WiFiServer class and not a HTTP-Webserver

#include <WiFi.h>

WiFiServer server(23);
void setup() {
  server.begin();
}

void loop() {
  WiFiClient client = server.available();

  if (client) {
    //if not seen yet, add to a linked list (?)
  }
}

The WiFiClient.h header and WifiClient.cpp source files are useful for reference.

  Is the best data structure a linked list?

Probably not here.  Possibly not ever.  It's a load of effort to implement, and won't give you any benefit.  Just create an array of them:

WiFiClient clients[5];

Then perhaps something like

WiFiClient newClient = server.available();
if (newClient) {
    // TODO: Check whether we have an existing connection from this IP
    // TODO: Get the first 'free' array index
    clients[firstFree] = newClient;
}

  How can I see if this client connected already (if there is already a connection to this ip) to avoid doubles?

Get the remote IP address of the new client

IPAddress = newClient.remoteIP();

Do the same with all the connected clients in your array* and compare them.  If you find a match, drop the connection

newClient.disconnect();

and, probably, don't put it in the array.

  How can I detect when they disconnect in order to delete them?

if (client[i].connected())

Lastly, how do we keep track of which items in our array are current active connections, and which aren't (either not yet used, or already disconnected).  You could do this several ways.  One would be to iterate through the array, checking whether the item is valid and connected:

// Returns -1 if no free slots
int firstFree() {
    for(int i=0 ; i<5 ; ++i) {
        if(!clients[i] || !clients[i].connected()) return i;
    }
    return -1;
}

All code untested so you may find typos, but I believe it's basically correct.


Assemble or typecast byte array to float The serial port on my Arduino Mega is receiving 3 floats as bytes (total of 12 bytes, 4 per float) over serial. Unfortunately I cannot assemble the 4 Bytes in a float, as the serial monitor only displays

0.00

0.00

0.00 etc.

Here is the code:

void serialEvent2() {
  if (Serial2.available() > 11) {
    byte yawData[3];
    yawData[0] = Serial2.read();
    yawData[1] = Serial2.read();
    yawData[2] = Serial2.read();
    yawData[3] = Serial2.read();
    float yawAngle = *((float*)(yawData));
    Serial.println(yawAngle);

    byte pitchData[3];
    pitchData[0] = Serial2.read();
    pitchData[1] = Serial2.read();
    pitchData[2] = Serial2.read();
    pitchData[3] = Serial2.read();
    float pitchAngle = *((float*)(pitchData));

    byte rollData[3];
    rollData[0] = Serial2.read();
    rollData[1] = Serial2.read();
    rollData[2] = Serial2.read();
    rollData[3] = Serial2.read();
    float rollAngle = *((float*)(rollData));
  }
}

I made sure the data coming to Serial2 is not 0.

UPDATE: The initial mistake was my byte array not being sized correctly. I fixed it. The values I print are fine until after about a second, they get totally weird. Dropped bits/Bytes maybe? Seems odd because a sample sketch written in Processing works perfectly while taking the exact same input.

I tried the code below and it worked for me, don't miss the delay() part:

Sender Code:

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

void loop() {
    float yaw = 10.5;
    float pitch = 20.15;
    float roll = 100.10;
    float ypr[3];
    ypr[0] = yaw;
    ypr[1] = pitch;
    ypr[2] = roll;
    Serial.write((byte*) ypr, 12);  // No new-line
    delay(1000);

}

Receiver Code:

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

void loop() {

}

void serialEvent() {
    if (Serial.available() == 12){
      byte yawData[4];
      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawAngle = *((float*)(yawData));
      Serial.println(yawAngle);

      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawPitch = *((float*)(yawData));
      Serial.println(yawPitch);

      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawRoll = *((float*)(yawData));
      Serial.println(yawRoll);
    }
}

Results:


Making a Bluetooth Mouse with Arduino I'm trying to make a bluetooth mouse using Arduino. I will be using an analog 2 axis thumbstick as the sensor. I understand that it's possible to do this with the Arduino connected directly to the computer (https://www.arduino.cc/reference/en/language/functions/usb/mouse/). Would it be possible for the arduino to instead communicate wirelessly using bluetooth? The controller I'm interested in is here: https://www.dfrobot.com/product-1259.html

Thank you!

With that specific board, yes you can.  According to this review:

  Bluno also supports the HID (Human Interface Device) mode. When running in this mode, Bluno simulates an input peripheral (keyboard, mouse…) connected via BLE.


delayMicroseconds- error? running a very short program on a mega, just to generate a 8 microsecond wide clock pulse on pin 18, every 250 microseconds-
closest 'delay' values I can get are delayMicroseconds(3), and (83) off, gives a 7.5 microsecond wide pulse every 249 microseconds- any suggestions on a better way?

here is whats running:

int i=0;
int req=18;

void setup(){
Serial.begin(115200);
 DDRD = DDRD | B10000010;
 interrupts();
pinMode(req,OUTPUT);
}

void loop(){
i=1;
digitalWrite(req, HIGH);
delayMicroseconds(3); //gives 7.5 microsecond pulse?
digitalWrite(req, LOW);

while(i<83){//gives 249 microseconds start of pulse to start of next pulse?
 delayMicroseconds(1);
 i=(i+1);}
 }

This a very partial answer. I do not know your requirements, whether or
not PWM can do the job, etc... I just wanted to point out that you can
make a pulse exactly 8 µs long with this:

#include <util/delay.h>
#include <util/atomic.h>

// Pulse PD3 (digital 18 on Mega 2560)
// for exactly 8 us (128 clock cycles @ 16 MHz)
static void pulse() {
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        PORTD |= 1 << 3;
        _delay_us(8 - 0.125);
        PORTD &= ~(1 << 3);
    }
}

The _delay_us() function from avr-libc is actually cycle-accurate
inline assembly. The 0.125 µs I subtracted is the time needed by
the actual port writes: both the sbi and cbi instructions take two cycles
(0.125 µs), but that delay should only be counted once.
digitalWrite() should always be avoided in time-critical code.

The 242 µs delay between pulses would be harder to generate without
PWM. A timer interrupt at 4 kHz seems like the simplest option, but
it is not cycle-accurate.

Edit: here is the scope trace, showing a quite accurate timing: