Making Cases for Projects I've been messing around with arduinos and other microcontrollers for around a year now and I've always struggled to find ways to encase my projects. I've seen some people use custom PCBs and then 3D print a case for that.  How would one go about that? I am only a computer science student so I know nothing about electrical circuitry.
For example, lets say I have a UltraSonic Sensor that uses a Arduino nano to light an LED. How would I transfer that to a single PCB? And are there websites where I can order custom 3D printed cases for my projects?
Please let me know if you need me to make my question clearer. Thank you!

Your question has multiple layers:

The custom PCB: Breadboards are good for experimenting, but not for a finalized circuit. Depending on some factors you can decide between multiple options. One, that I myself often use, is soldering the parts onto a perfboard. That are cheap PCBs, where - depending on the type - you have a grid of single through-hole solder pads or connected groups of through-hole solder pads. I like to use these:

The pads are connected nearly like a breadboard, so it is easy to use with Arduinos and such. You can build your circuit on there by soldering the parts to it, and make the PCB the right size by cutting it into the needed size.

A more professional option is to buy real custom PCBs. You need to create the PCB layout on your PC (common programs are Eagle or Kicad, though there are many others). Then you can choose the PCB manufacturer of your trust and give them your layout files. They will manufacture the PCBs and send them to you. This options costs a bit money (though not a lot) and you will have to wait for the PCBs to arrive.
The casing: There are many options to choose from:

You can buy a generic case somewhere (hardware store, or the internet shop of your trust). Then you can work on it to fit your purpose (drilling holes for the LEDs, using screws or glue to fix your PCB, ...)
There are some standard cases to buy, though most of them most likely don't fit you good, since they are made for special industrial purposes.
You can create a custom 3D printed case. For this you first need to design the case on your PC (a common program is Fusion360, though I'm using FreeCAD). For the actual printing you can either use your own 3D printer, or you can again find a good 3D printing service, that you can give your design file (commonly in the stl format). They will print it for you for a bit of money. You will have to choose between different manufacturing methods, mainly FDM (putting lines of molten plastic onto each other layer after layer) or Resin printing (curing layers of fluid resin one after another). FDM is still cheaper. And you need to decide on the material (PLA is common, others are ABS or even metal (though the last is expensive). Also you need to design your case in a way, that it is good printable with the chosen method. You need to read more about 3D printing elsewhere (there are tons of material about it on the web).

One rule of this site is to not give product recommendations. That's not, what the site is for, and they are pretty fast outdated. Instead you need to do the research yourself.


Atmega8 with Arduino bootloader - wrong serial characters I recently flashed bootloader of Arduino to Atmega8. Unfortunately I stumbled on a problem I can't solved.

I am testing SerialEvent example on Atmega8. I modified it but started debugging it on my code (I think the same problem stops SerialEvent example from working).

I think the Atmega8 reads the characters sent through serial wrongly. That's why SerialEvent 'if' condition doesn't work also. Because it never gets '\n' symbol (it receives it but wrongly interprets it).

boolean prevState = true;
boolean OnOff = false;
boolean stringComplete = false;
String inputString = "";
String OnString = "on\n";
String OffString = "off\n";

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

    while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
    }

    // reserve 200 bytes for the inputString
    inputString.reserve(200);

    DDRD |= 0b00001100;
    PORTD |= _BV(PD2);

    // synchronization info for RPi
    Serial.println("ARD - OK\n");
}

void loop() {
    // turn on
    if (OnOff == true && prevState == false){
        PORTD |= _BV(PD2);
        prevState = OnOff;
    }
    // turn off
    if (OnOff == false && prevState == true){
        PORTD &= ~_BV(PD2);
        prevState = OnOff;
    }

    if (stringComplete) {
        Serial.println(inputString);
        // clear the string:
        inputString = "";
        stringComplete = false;
    }
}

void serialEvent() {
    while (Serial.available()) {
         // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag
        // so the main loop can do something about it:
        Serial.println(inputString);
        if (inChar == '\n') {
            stringComplete = true;
            Serial.println("test\n");
        }

        if (stringComplete && inputString.equals(OnString)){
            OnOff = true;
            Serial.println("Turning on.\n");
        }
        else if (stringComplete && inputString.equals(OffString)){
            OnOff = false;
            Serial.println("Turning off.\n");
        }
    }
}

I tested a lot of behaviors. Below I attach one of the tests from Realterm:

First I reset the board - it responded with 'ARD - OK\n' - expected behavior.
Then I sent 'on\n' and it responded with two lines but the characters aren't the same as 'on\n'.
Then I sent 'test123\n' but once again got wrong characters.
It prints multiple lines because it sends the string in which it accumulates the data every time SerialEvent() is fired.

Also sending for example variabl OnString works ok.

I really don't know why is it acting like that... Help would be appreciated :).

Ok I found a solution (rather workaround).

I uploaded the same program to Arduino Uno. It worked perfectly. I transplanted the Atmega328 from Uno to breadboard. Still worked BUT the Atmega328 is using external 16Mhz crystal (which I added to the breadboard).

So what if I uploaded bootloader for 16Mhz external crystal on Atmega8?
It makes it work properly.

So in short:
Atmega8 with 8Mhz internal oscillator doesn't work properly.
Atmega8 with 16Mhz external oscillator works properly.

Don't know why does it make it work. If anyone can think of a reason I would be glad to know it. Thanks for all your help.


Serial.read() vs. Serial.readBytes()? I'm trying to do some fairly simple serial communication and have things partially working, but am pretty confused about a couple results I'm getting.

For a little background, I'm using an Arduino Mega 2560 to try to communicate with a Dynamixel servo (MX-64) over TTL (half-duplex, asynchronous) with Tx1 and Rx1.  Basically I construct some byte arrays as instructions, send them over to the servo (with Serial1.write()), and then read back a reply.  I've actually gotten it to work pretty well if I use Serial1.readBytes(), specifying the length of the buffer (number of bytes I'm expecting).  I'm also reading back what I originally sent (first) as well as the response (second), since I have Tx1 and Rx1 tied together (required in my setup because this servo only has one data wire).

However I don't understand the difference between Serial.readBytes() and Serial.read().  If I do Serial.read() just prior to Serial.readBytes(), it comes back with -1, meaning no bytes to read... but then Serial.readBytes() gives me the byte stream I was expecting from the buffer!  What's going on here?

Similarly, Serial.available() seems sort of broken in that it tells me there are no bytes to read (returns 0), but then I can read the bytes I'm expecting with Serial.readBytes(). Additionally, I can do Serial.readBytes() after there's nothing left (or rather, there shouldn't be any bytes left...) and it will give me some bytes, but they're total garbage.

I think maybe there's something I don't understand about the way the serial buffer works, but can't find a good resource on it and the Arduino reference pages are kind of useless.  Any clues about the difference in how these operate would be much appreciated!

readBytes is blocking until the determined length has been read, or it times out (see Serial.setTimeout()). Where read grabs what has come, if it has come in. Hence available is used to query if it has.

Note that it takes time for a message to go out and to receive either the echo or response. So simply checking the RX buffer immediately after sending something, is expected to be empty for some time. That is where readBytes sites and waits. And I bet the default setTimeout of 1s is sufficient, to get the response.

This is why you see the Serial.read() inside a while or if Serial.available. Hence I typically employ something like the following: Which emulates readBytes (for the most part).

    #define TIMEOUT = 3000;
    loop {
        char inData[20];
        unsigned long timeout = millis() + TIMEOUT;
        uint8_t inIndex = 0;
        while ( ((int32_t)(millis() - timeout) < 0) && (inIndex < (sizeof(inData)/sizeof(inData[0])))) {
            if (Serial1.available() > 0) {
                // read the incoming byte:
                inData[inIndex] = Serial.read();
                if ((c == '\n') || (c == '\r')) {
                    break;
                }
                Serial.write(inData[inIndex++]);
            }
        }
    }

Above code was quickly written and untested. But gets the idea across.


please explain the sketch attached Sorry about a newbie.
1. what mening of:

    if(Xstr[XstrLength-1] != '|'){
      Xstr[XstrLength] = '|';
      Xstr[XstrLength+1] = '\0';

the setup: char Xstr[60]; what means? and then: itoa(Yint,Ystr,10);

Code:

#include <VirtualWire.h>

//gamepad setup
int up_button = 2;
int down_button = 4;
int left_button = 5;
int right_button = 3;
int start_button = 6;
int select_button = 7;
int joystick_button = 8;
int joystick_axis_x = A0;
int joystick_axis_y = A1;
int buttons[] = {up_button, down_button, left_button, right_button, start_button, select_button, joystick_button};

void setup()
{

    //gamepad setup
    for (int i; i < 7; i++)
    {
        pinMode(buttons[i], INPUT);
        digitalWrite(buttons[i], HIGH);
    }

    Serial.begin( 9600 );

    //transmitter setup
    vw_set_tx_pin(12);          // Sets pin D12 as the TX pin
    vw_set_ptt_inverted(true);  // Required for DR3100
    vw_setup(2000);             // Bits per sec
}

int counter = 0;

int Xint;
int Yint;

char Xstr[60];
char Ystr[60];

void loop()
{
    // Read and store Sensor  data
    Xint = analogRead(joystick_axis_x);
    Yint = analogRead(joystick_axis_y);

    // Convert integer data to Char array directly
    itoa(Yint,Ystr,10);
    itoa(Xint,Xstr,10);

    int XstrLength = String(Xstr).length();

    if(Xstr[XstrLength-1] != '|'){
        Xstr[XstrLength] = '|';
        Xstr[XstrLength+1] = '\0';
    }

    char combinedArray[String(Xstr).length() + String(Ystr).length() + 1];
    sprintf(combinedArray, "%s%s", Xstr, Ystr);

    vw_send((uint8_t *)combinedArray, strlen(combinedArray));
    vw_wait_tx(); // Wait until the whole message is gone

    Serial.println(combinedArray);

}

This adds some end of string characters.

if(Xstr[XstrLength-1] != '|'){
    Xstr[XstrLength] = '|';
    Xstr[XstrLength+1] = '\0'

First it checks if Xstr last character is a '|', if not:
   Place a | directly after the last character
   And append a '\0', which is a symbol to 'end' a string

A string in C/C++ is normally build up like this, e.g. "Hello" contains of the bytes:

'H', 'e', 'l', 'l', 'o', \0

Where each of the above are ASCII characters/values and the last \0 a 0 byte.

char Xstr[60]; defines a character array (string) that can contain 60 characters. Note however, that the ending \0 also needs to be in this string, so you can actually only put 59 characters inside.
itoa(Yint,Ystr,10); converts Yint which is an integer value to a string (where each digit has each own byte), and 10 is the length.


CO2 sensor for arduino I want to add CO2 measuring feature to my room weather station. Can someone please recommend a CO2 sensor easy to integrate with Arduino?

You could try the K30 CO2 sensor. There is also a guide using it to make an arduino CO2 detector here.

I've also seen people use the MG-811 module, you can buy them from dfrobot.com . There is also good documentation for how to use the MG-811 with arduino here.


Over voltage on Arduino and Ardumoto I am using Arduino Leonardo and Ardumoto to drive 2 12v motors running at 1.3 amps each.

I purchased a rechargeable battery of 12V with 5AH

I first started by plugging in the battery to the Arduino via the barrel jack. Arduino then sparks and is fried.

I read somewhere that I wasn't supposed to hook it up to the Arduino and to hook it up to the VIN ports in the Ardumoto. I purchased a new Arduino and plugged in the Positive and negative from the battery to the ports and now the Ardumoto board fried (copper lining on board burnt off).

I'm reading online and from what I've gathered, the Ardumoto can handle a max of 18 volts and a maximum of 2 amps per each output. I'm obviously missing something and would not like to fry my boards next time.

Please assist?

From your description, everything should be wired correctly. It should not have failed.

Unfortunately, testing this sort of thing with a 5 amp-hour lead-acid battery is not a great way to get started, since a battery that large can source a lot of current, and doing anything wrong will likely produce immediate and spectacular failure.

Really, the only think I can think of is that you have the polarity of the output lugs/pins on the battery backwards. Buy a $5 multimeter, and check them.


Arduino 2560 as an Interface to 4 Serial Hardwares I am writing a software that runs on the PC that has a Arduino 2560 connected to it via USB. This PC needs to communicate with multiple devices through RS232.

Is it possible to use the Arduino's 4 UARTs to communicate with 4 different hardware that uses RS232 serial communication, using just 1 USB connection between the PC and the Arduino 2560?

The Arduino 2560 will basically act as an interface for 1 USB to talk to 4 RS232 devices.

No, but it is possible to use 3 of them. The reason being that one of them is the connection to the computer.

The hard part is in the programming. You will need not only a suitable sketch on the Arduino (the easy part), but also some software on your computer that presents three COM ports to the operating system and forwards the data through to the Arduino in a suitably packeted format, and receive data back and sent it on to the right COM port.  Depending on your operating system that may be a very easy task (on Linux and OS X) or a complete and utter nightmare (Windows).


LED intensity on digital pins I am using an Arduino UNO.

On any digital/analog pin, if an LED (with resistor) is connected and we use digitalWrite(pin,HIGH) the LED lights up rather dimly.

On the other hand, if we use pinMode(pin,OUTPUT) and then use digitalWrite, the LED lights up to maximum intensity.

I checked that in both cases, the voltage on the pin is 5V. Any explanation for this ? Thanks.

This is due to a specific feature of the AVR microcontrollers, where the
same register (PORTB, PORTC or PORTD) is used for controlling both
the output value of the pin and its optional internal pullup resistor.
The command digitalWrite(pin,HIGH) sets to 1 the bit of this register
corresponding to the selected pin.

If the pin is set to INPUT (which is the default), the effect of
digitalWrite(pin,HIGH) is to turn on the internal pullup.
If the pin is set to OUTPUT, the same command sets the output to
HIGH.

The internal pullup is about 30 kΩ, which lets flow a very small
current through the LED. You may notice that the voltage at the pin is
5 V if nothing is connected to it, but significantly less when the
LED is connected. Notice also that the preferred way of enabling the
pullup is pinMode(pin,INPUT_PULLUP).


Global Variable not able to be accessed in function? I am trying to compile an Arduino program that takes analog input. However, when I declare multiple global variables, it often will not compile and because it throws an error that the variables aren't within scope of the functions within the program. I am not super familiar with Arduino IDE, but this doesn't programmatically make sense to me.

This is the program:

/*
*  By Hannah Perner-Wilson, www.plusea.at
*  Modified 3/30/2012 By Brian E Kaminski, www.AdvancerTechnologies.com
*
*  IMPORTANT!!:
*  Scroll down to set your serial port
*  Scroll down to set your thresholds
*/

import processing.serial.*;

// definition of window size
// you can change the size of the window as you like
// the thresholdGraph will be scaled to fit
// the optimal size for the thresholdGraph is 1000 x 400
int xWidth = 1200;
int yHeight = 750;

// xPos input array, using prefix
int[] xPosArr= {0,0,0,0,0,0};

//
int[] messageArr= {0,0,0,0,0,0};

// Arrays for threshholding
int[] threshMax= {0,0,0,0,0,0};
int[] threshMin= {0,0,0,0,0,0};

// variables for serial connection. portname and baudrate are user specific
Serial port1;

//Set your serial port here (look at list printed when you run the application once)
String V3 = Serial.list()[1];
String portname1 = V3;
int baudrate = 9600;

int prefix = 10001;
boolean myCatch = false;
String serialIN = "";
String serialINPUT = "";
String buffer = "";
int value = 0;

// ThresholdGraph draws grid and poti states
ThresholdGraph in;

void setup(){
  // set size and framerate
  size(xWidth, yHeight);
  frameRate(25);
  background(255);
  strokeWeight(5);
  stroke(0);
  smooth();
  strokeCap(ROUND);

  // establish serial port connection
  port1 = new Serial(this, portname1, baudrate);
  port1.bufferUntil('\n') ;
  println(Serial.list());  // print serial list

  // create DisplayItems object
  in = new ThresholdGraph();

  // THRESHOLD VALUES:
  // using the thresholdGraph you can determine the MIN and MAX values
  // of your sensors. Enter these here. They must lie between 0 and 1000.

    //MIN trashhold
    threshMin[0] = 20;   // one
    threshMin[1] = 20;   // two
    threshMin[2] = 20;   // three
    threshMin[3] = 20;   // four
    threshMin[4] = 20;   // five
    threshMin[5] = 20;   // six

    //MAX trashhold
    threshMax[0] = 600;   // one
    threshMax[1] = 600;   // two
    threshMax[2] = 600;   // three
    threshMax[3] = 600;   // four
    threshMax[4] = 600;   // five
    threshMax[5] = 600;   // six
}//end setup

// draw listens to serial port, draw
void draw(){

  // listen to serial port and trigger serial event
  while(port1.available() > 0){
        serialIN = port1.readStringUntil('\n');
        //println((int)float(serialIN));
        if(serialIN != "")
          serialEvent(serialIN);
        else
          Serial.println("found empty");
        }

  // threshold serial input
  threshHolding();

  // draw serial input
  in.update();
}//end draw()

The error that are being thrown are:

testproject.ino:100:17: error: 'threshHolding' was not declared in this scope
testproject.ino:103:3: error: 'in' was not declared in this scope
Error compiling.

The problem is that this is not an Arduino Sketch, but a processing file which is noted by the initial import statement that is Java based. Because the Arduino IDE is not very sophisticated, it didn't shout out obvious errors such as import type not defined or even ThresholdGraph not defined.

To use this file it is necessary to use the following IDE: https://processing.org/reference/environment/


can arduino on output mode sink current? I have a arduino set below:

pinMode(1,OUTPUT);
digitalWrite(1,LOW);

Now, I am expecting 1.2mA current flow through the pin that is set as output. Is that accepted? If so, what it the max current a pin can sink?

The current comes from a pul up resistor on the line

note: I can't protect it with a diode.

Ok, I just found it.

from the arduno docs:

Atmega pins set aa output can source (provide positive current) or sink (provide negative current) up to 40 mA (milliamps) of current to other devices/circuits.


Check if a set of events occur in a limited time period I am making a project in which I am using 4 Infrared sensors to take an input. The way I want it to work is such that when one of the sensors is triggered, the code listens for input from the other sensors for a fixed amount of time (say 2 seconds). Based on this data, further functions are executed.

I am assigning a number to each of the sensors, and the sequence in which they are triggered is stored in an array like:

// All relevant pins of the IR sensors are set to input with names ir1,ir2,ir3,ir4
int sequence[] = {0,0,0,0}
int s1 = digitalRead(ir1); //and similarly for all other pins
int counter = 0;

if(s1==1){
  sequence[counter] = 1; //similarly 2 for s2 and so on
  counter ++;
}

What I am attempting to do is something like this:

if(s1 == 1 || s2==1 || s3 == 1 || s4 == 1){
   if(s1 == 1){
      sequence[counter] = 1;
      counter ++;

   //Start listening for other sensors
   } // similarly check which sensor is triggered first

   //Allow 2 seconds for input from all sensors (no input from either one of them is also allowed)
   // After 2 seconds execute some code based on the sequence array which got updated from inputs by different sensors
}

How do I accomplish this?

Here's some pseudocode that might help:

   if millis() - start time >= 2000
         time is up, do what you want with the sequence so far
         maybe a boolean flag here so you only do it once
   if any button is pressed
      if counter == 0
          set start time = millis() // start the timer
          set first in sequence
      else
          add the button to the sequence


SDA and SCL problem with MEMS I have a simple question to ask you about SDA and SCL pins.
I have a gyro and I use these 2 pins to make it work; how can I use an accelerometer combined to a Gyro if these 2 pins are used? I should need another 2 SDA and SCL pins for the accelerometer... Tell me that I don't need to buy an IMU :D

EDIT: I'm using Gyro LG3D20H from Adafruit, reading gyro values each 10 ms.

I2C is designed to have multiple devices connected. Assuming the gyro and accelerometer have different I2C addresses they can both be connected to the same SDA and SCL pins.

For more information see http://www.gammon.com.au/i2c

Naturally you can only "talk to" one at a time. You may need pull-up resistors on both SDA and SCL, unless the hardware already has them.


Controlling mains (230 V) supply up to 5/10 amps using Arduino I am looking for a simple, low cost solution to control on/off of mains supply to certain equipment. The control will be done using one of the output pin of Arduino Uno.

The input trigger and how to control it is application dependent.  e.g. controlling an equipment or controlling supply to section of home but in principle mains control module implementation remains same. So looking for solution which is safe while doing connections as well as while in use in  indoor conditions for years.

The PowerSwitch Tail 2 is a great way for experimenters to control mains voltages. It is insulated and internally decoupled, so you only have to hook up 5v, gnd, and a signal line to control it.

This model supports only 120V, but there are also kits for 230V.

image from sparkfun


Bluesmirf Mate Silver (RN-42) enter command mode when in HID mode I am having problems getting the Bluesmirf Mate Silver (RN-42) into command mode once I have switched to HID mode. I have bought a second new Bluesmirf Mate Silver to confirm my issue.

I soldered the Bluesmirf and connecting to Arduino Uno. I used the ‘Example code: Using Command Mode’ from https://learn.sparkfun.com/tutorials/using-the-bluesmirf to successfully enter command mode.

I then entered the following commands in command mode (leaving out the comments):

SM,5   // Mode = 5, (any) Auto reconnect
SA,2   // Authentication Mode 2 (SSP, "just works" mode)
S-,myName  // // Set BT Name, This short name with no spaces is Picked up ok on windows
S~,6   // Enable HID on reboot
R,1    // Reboot to lock in perameters

Next I use a PC and pair with the bluetooth ‘keyboard’ I have created above. I am able to use the Bluetooth and Arduino sketches to write into notepad on the bluetooth connected PC.

However now I cannot get back into command mode to make changes to the Bluesmirf config. Trying to use the example code above I can see ‘$$$U,9600,N’ typed into notepad on the connected PC each time I load the sketch, rather than being used to enter command mode.

How do I get back into command mode after HID mode has been triggered.

I believe that the problem is caused by the mode I entered. According to the datasheet on pg 10 Auto-Connect Master Mode (SM,3) enters high speed mode and this connection cannot be broken via commands or software break characters.
It goes on to explain that both Auto-Connect DTR Mode (SM,4) and Auto-Connect ANY Mode (SM,5) (which I used) function like Auto-Connect Master Mode (SM,3), so I guess that in these modes the $$$ escape characters cannot be used to enter command mode either.

I was able to resolve this by performing a hard factory reset on the Bluesmirf Mate Silver (RN-42). I previously tried following a couple of you-tube tutorials that weren't very clear and didn't have any success. I looked at the instructions in this thread titled 'Factory Reset the RN-41 or RN-42' to get me on the right lines.

This worked for me:

Connect the Bluesmirf Mate Silver GND pin to GND and disconnected all other pins
Connect a wire to 3.3v on Ardunio
Load the Ardunio with an empty sketch, and keep it powered on
Touch the 3.3v wire repeatedly (3+ times) to the GPIO4/PIO4 connection hole on the Bluesmirf. This is a third of the way down one edge of the board.
Factory reset should now be complete - note I didn't see any indication lights during this process.

Then I could wire up the Bluesmirf as normal and use ‘Example code: Using Command Mode’ from https://learn.sparkfun.com/tutorials/using-the-bluesmirf to successfully enter command mode.


Modify Arduino Due's Bootloader to flash when reset I bought an Arduino Due, and I noticed unlike the other boards, the onboard LED does not flash after reset. I prefer this behavior, so I want to modify the bootloader to do this behavior when it starts. I have burnt bootloaders before, but I never modified one before.

How can I do this?

The Arduino Due bootloader is built-in. If you check the Arduino SAM core there are no bootloader files. There is a firmware file for the ATmega16u2 on the Programming Port. You might be able to modify this to do that (given that there is a LED to flash).

The alternative solution to a modified bootloader is modifing the init() of the Arduino SAM core. Please see https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/cores/arduino/main.cpp#L36 or https://github.com/arduino/Arduino/blob/master/hardware/arduino/sam/variants/arduino_due_x/variant.cpp#L372. Blink code as proposed by Majenko could be added there.

Cheers!


Combining two sketches that both work on their own, but don't work when combined I've got a program for a password protected doorlock, which I got working.

I'm trying to add to the code, to add functionality where I can toggle an LED on/off with a button.

Both codes function on their own and serve their desired purpose, but when I try to combine them into the same sketch, the LED button works but the rest of my design stops working. I can no longer input a password to activate the motor.

How can I combine the two codes and have them both work?

Here is the working keypad/lock code

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

#define Password_Length 5

int signalPin = 10;
int greenLedPin = 11;
int redLedPin = 12;
char Data[Password_Length] = "4";
char Master[Password_Length] = "1234";
byte data_count = 0, master_count = 0;
bool Pass_is_good;
char customKey;

const byte ROWS = 4;
const byte COLS = 3;
bool ledState = 0;

char hexaKeys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {5, 4, 3};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS,     COLS);

LiquidCrystal_I2C lcd(0x3f, 16, 2);

void setup()
{
  lcd.init();
  lcd.backlight();
  Serial.begin(9600);
  lcd.clear();

  pinMode(redLedPin, OUTPUT);
  pinMode(greenLedPin, OUTPUT);
  digitalWrite(redLedPin, LOW);
  digitalWrite(greenLedPin, LOW);
}

void loop()
{
  lcd.setCursor(0,0);
  lcd.print("Enter Password:");

  customKey = customKeypad.getKey();
  if (customKey){
    Data[data_count] = customKey;
    lcd.setCursor(data_count,1);
    lcd.print(Data[data_count]);
    data_count++;
    }

if(data_count == Password_Length-1){
    lcd.clear();

    if(!strcmp(Data, Master)){
      lcd.print("Correct");
      pinMode(signalPin, OUTPUT);
      digitalWrite(signalPin, LOW); //turns on motor
      digitalWrite(greenLedPin, HIGH); //turns on led
      delay(2000);
      digitalWrite(signalPin, HIGH); //turns off motor
      digitalWrite(greenLedPin, LOW); //turns off led
      }
    else{
      lcd.print("Incorrect");
      digitalWrite(redLedPin, HIGH); //turns on led
      delay(2000);
      digitalWrite(redLedPin, LOW); //turns off led
      }

    lcd.clear();
    clearData();
  }
}

void clearData(){
  while(data_count !=0){
    Data[data_count--] = 0;
  }
  return;
}

and here is the code I'm using for the LED on/off toggle button

int button = 2;
int led = 13;
int status = false;

void setup(){
pinMode(led, OUTPUT);
pinMode(button, INPUT_PULLUP); // set the internal pull up resistor,
unpressed button is HIGH
}

void loop()
{
//a) if the button is not pressed the false status is reversed by !status
and the LED turns on
//b) if the button is pressed the true status is reversed by !status and
the LED turns off

if (digitalRead(button) == true) {
status = !status;
digitalWrite(led, status);
} while(digitalRead(button) == true);
delay(50); // keeps a small delay
}

Let's step back from the Arduino for a minute and ask: assuming you know how to cook some bacon, and also how to boil some eggs, how would you simultaneously cook bacon and eggs?

Basically you would have to interleave any process (such as waiting for the water to boil) with some other process (such as waiting for the bacon to cook).

Once you have this concept in your head you can just take the two pieces of code, and wherever you are planning to wait for something to happen, see if the other thing is able to be done.

I have done a post about this: http://www.gammon.com.au/blink

  I just figured out that the original password code will still function, but only if i keep the LED toggle button held down.

Well, you need to remove any blocking loops from either part of the code.

Your code here blocks:

if (digitalRead(button) == true) {
status = !status;
digitalWrite(led, status);
} while(digitalRead(button) == true);

That's like (in my analogy) of thinking "oh the water is boiling, I'll have to stare at the eggs until they are cooked". Instead you could check the bacon, check the eggs, check the bacon again, and so on.

I'm giving you these analogies to help you solve the general problem, not this particular bit of coding.

  i understand that the code blocks, but that code also makes the LED toggle on and off like i need, so how do i integrate that in a way that it doesnt block the rest?

Replace the LED code with something like this (not compiled or tested):

void loop ()
  {
  static int oldReading = LOW;
  int newReading = digitalRead (button);
  if (newReading != oldReading)  // it changed!
    {
    oldReading = newReading;  // remember new reading state
    if (newReading == HIGH)
      {
      status = !status;
      digitalWrite(led, status);
      }  // end of a HIGH reading
    }  // end of changed state

   // password stuff here

   }  // end of loop

Now, whatever you do with the button, the code doesn't stop (block) so the password stuff is still executed.


Why does the RCSwitch.available return false? I am trying to use this example code from the RCSwitch library:

/*
  Simple example for receiving

  https://github.com/sui77/rc-switch
*/

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on inerrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    Serial.print("Is avail");
    int value = mySwitch.getReceivedValue();

    if (value == 0) {
      Serial.print("Unknown encoding");
    } else {
      Serial.print("Received ");
      Serial.print( mySwitch.getReceivedValue() );
      Serial.print(" / ");
      Serial.print( mySwitch.getReceivedBitlength() );
      Serial.print("bit ");
      Serial.print("Protocol: ");
      Serial.println( mySwitch.getReceivedProtocol() );
    }

    mySwitch.resetAvailable();
  }
}

It seems like the mySwitch.available() is returning false, but since there seems to be no documentation for the library I don't know what it means.

So why is that?

I am trying to use this code on a A-Star 32U4 Micro, which supports Arduino code.

I think that the value of available just determine if there is a message to receive or not.


Sim800 sim card requirements What kind of a sim card is required for sim800 module? I know it must be activated and must be valid. But about 2g, 3g or LTE...What kind of a sim card in overall should I use with this module?

What kind of a sim card is required for sim800 module?

The SIM interface complies with the GSM Phase 1 specification and the new GSM Phase 2+ specification for FAST 64 kbps SIM card. Both 1.8V and 3.0V SIM card
are supported. The SIM interface is powered from an internal regulator in the module.

For more details see here and here. And remember "Google is your friend".

Cheers!


How to program arduino due without arduino ide Is it possible to program the Arduino Due without the Arduino IDE? Is there a standalone program that can be downloaded, and be used to upload a .bin file (which has already been generated from the arduino IDE) to the Due? Any guidance appreciated.

I read about SAM-BA programmer, downloaded it but double clicking the .exe file does nothing. Something seems to open but it disappers.

The standalone program for most arduinos is avrdude: http://www.nongnu.org/avrdude/

However, for the Due, it is BOSSA:

  Unlike other Arduino boards which use avrdude for uploading, the Due
  relies on bossac.
   -- Arduino Due Overview


Yellow LED got burned, green LED didn't I'm not talking about the onboard LED at the Arduino board here.  What those LED's mean, is the LED's we usually plug at the breadboard.

I plugged in a yellow LED and a green LED onto a breadboard.  I wired it up, and noticed something.  Green LED lights up at its full brightness, while yellow LED didn't emit any light.  Tried in another yellow LED, and it seems like it's smoking, which means it's burned.

I'm not using a 220 Ohm resistor or any kind of resistor that time.  I also have no idea why the green LED didn't burn itself, when you plug it directly on 5V and GND.  I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

When I plugged the green LED into a 220 Ohm resistor, it did as expected.  It lowered its brightness, of course, because the resistor is resisting some of the electricity to pass on the LED.

I'm not using a 220 Ohm resistor or any kind of resistor that time.

Well, there you go then. If you abuse an LED you can expect it to die.

  When I plugged the green LED into a 220 Ohm resistor, it did as expected. It lowered its brightness, of course, because the resistor is resisting some of the electricity to pass on the LED.

And the LED was so much happier when you weren't abusing it.

  I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

It was probably tinged with yellow. And if you left it a while it would get yellower as it got hotter, and then started to fade out, and eventually die.

Different LEDs use different combinations of elements to make the different colours. Different types of the same colour also use different elements. Old fashioned green LEDs are more reliable, though dimmer, than newer ones. They withstand more abuse. But they will still complain after a while.


Serial monitor listing unreadable characters My Serial Monitor is displaying unreadable characters.  If anybody can give me some insight on why this would be happening please let me know.

Thank You.

Change Serial.write to Serial.print (or Serial.println).

write writes in binary, which gives you unprintable characters.


Trouble understanding connection diagram The image shows a way of connecting an optocoupler.
My problem comes from how the emitter (Q1 in the image) is connected. The emmiter goes to a resistance going to ground and to v_out. When i try to add this to my circuit the pin that is suppost to be receiving data, the v_out pin goes silent. If i remove the resistance going from the emitter to ground and just have vout to the emitter everything works fine.

Normally you would connect the ground (0V) side of resistor R2 to the ground of the Arduino and the other side of R2 (which is also connected to the emitter of Q1) to an input pin of the Arduino. When the LED is energized by pressing the button it sends light to the fototransistor. Because of this the phototransistor starts conducting current (I1) which causes a voltage drop I1xR2 over R2. When this voltage is high enough the input pin will show a "1" (or HIGH) when read out.  "High enough" means >= 0.7 x Vcc, where Vcc is the voltage of the powerline to the Arduino.

The website from which the picture in your question originates (here) has an extensive article about the working and implementation of optocouplers. It also shows examples of alternative circuits.


LED dimmer not fading out I'm trying to make an LED go from no brightness to max and back down on a loop and I've encountered a problem I can't seem to crack. The LED will go to maximum brightness steadily as it should but then it will drop to zero brightness and start again... Why?

int blue_led=10;

void setup() {
  pinMode(blue_led,OUTPUT);
}

void loop() {

  int voltage=0;

  for(int i=0;i<=255;i+1){

    analogWrite(blue_led,voltage);
    voltage=voltage+1;
    delay(8);
  }
   int volts=255;

   for(int i=0;i<=255;i+1){

    analogWrite(blue_led,volts);
    volts=volts-1;
    delay(8);
   }

}

your for() loop should end with with either "i=i+1" or "i++" or "i +=1". In your code you are just saying i+1, which doesn't actually affect "i". So the first loop continues endlessly, and the "voltage" variable (which should not exceed 255) continues to go into the "illegal" range. The arduino likely translates the illegal values to 0. Eventually, since 'voltage' is just a 2 byte integer, it will finally become 0 again. This will happen in 65536 * 8ms, which should be about 8.7 minutes. But I don't think that's what you want. ;-)


Arduino Uno & ESP32 communication using RS485 I am trying to establish a communication between Arduino Uno ( Master) and ESP32 (Slave) using RS485 protocol (using MAX485 module).
I have successfully done this between two Arduino Unos. SoftwareSerial library is what i am using between two Arduino Unos, now trying with ESP32 and Arduino Uno (using MAX485 module)
.
For ESP32 i have used SoftwareSerial (https://github.com/akshaybaweja/SoftwareSerial) library.

After reading the library and making connection i am not be able to establish a communication between them. Sharing my code below.

Receiver

#include <SoftwareSerial.h>

SoftwareSerial softwareSerial(9, 10);
String str;

void setup()
{

  Serial.begin(9600);
  softwareSerial.begin(9600);

}

void loop()
{

  while (softwareSerial.available() > 0) {

    char inChar = softwareSerial.read();

    if (inChar == '$') {

        str.trim();
        Serial.println("received command" + str);
        memset(&str, 0, sizeof(str));
        Serial.flush();
        softwareSerial.flush();
    }
    else {
        str = str + inChar;
    }

 }

}

Sender

#include <SoftwareSerial.h>

SoftwareSerial swSer1(22, 23, false, 256);
String str;

void setup() {

  Serial.begin(9600);
  swSer1.begin(9600);

}

void loop() {

  String sendCmd = "MSG1$";
  Serial.println("Sending ");
  Serial.println(sendCmd );
  char copy[50];
  sendCmd.toCharArray(copy, 50);
  swSer1.write(sendCmd);
  delay(1000);

}

Here my question is where i am going wrong in this project. Please guide me.

Note : DE AND RE PINS are connected to high for sender device and to low for receiver device as given in the RS485 documentation.

Maybe you have already solved this but in any case, have you tried working with the hardware serial ports? You have three of them in the ESP32. I read sowhere else that there may be some interrupt issues using the SoftwareSerial library on the ESP devices, especially at higher baud rates.


Using random() in a header file #ifndef FOO_H
#define FOO_H

struct Foo{
  int randInt = random(0, 101);
};

#endif

I have a header file with a struct like above but when I compile I get this error:

'random' was not declared in this scope

How can I use random() in a header file?

The struct is a declaration of a type. You cannot mix it with the initialization. This is how it could be:

In foo.h:

#ifndef FOO_H
#define FOO_H

struct Foo{
  int randInt;
};

extern struct Foo foo;
struct Foo *initFoo(struct Foo *foo_ptr);
#endif

In foo.c:

#include "foo.h"

struct Foo foo;
struct Foo *initFoo(struct Foo *foo_ptr) {
  if (!foo_ptr)
    return NULL;
  foo_ptr->randInt = random(0, 101);
  return foo_ptr;
}

random() is a function and therefore its return value cannot be used as static initializer.
Unless -std=c++11 or -std=gnu++11 are enabled.


Arduino ethernet need help with game logic! I'm making a game where there are three LEDs and three buttons: 1 LED for 1 button. One has to press the button that has its LED lit. If it is correct, another (random) LED will light up and the game continues. However, if one presses one that isn't lit, one has points taken from one's score.

Example image: http://i.imgur.com/xSUrVRV.png

I'm having trouble figuring out how to find out when the wrong one is pressed. With the code below it will print "Ouch" whenever the led switches numbers.

Code that switches LED:

led = random(1, 4);
switch(led) {
  case 1:
    ledLeftState = HIGH;
    break;
  case 2:
    ledMiddleState = HIGH;
    break;
  case 3:
    ledRightState = HIGH;
    break;
}

Code that checks if the wrong button is pressed:

 if(digitalRead(BUTTON_LEFT) == LOW && led != 1 || digitalRead(BUTTON_MIDDLE) == LOW && led != 2 || digitalRead(BUTTON_RIGHT) == LOW  && led != 3) {
    static unsigned long lastTime = 0;
    if(millis() - lastTime > 400) {
      Serial.println("Ouch, minus ten miliseconds!");
      hurt += 10;
      lastTime = millis();
    }
  }

Hopefully you can figure this scenario out in your heads, otherwise simply tell me that you'd like code instead of downvoting.

Thanks for your time!

The line

if(millis() - lastTime > 400)

is supposed to test that the button press does not come right after the
LED switches. This means the line

lastTime = millis();

should be right when you change the displayed LED.


What is the maximum current for each I/O pin? Question

As far as I know each I/O pin has to keep around 20mA, what are the consequences of going higher or lower? But if I am using all I/O pins is there a maximum current value I should keep in mind? For example, the sum of all currents in all pins should not be greater than 100mA.

This comes up as first result when Googling your question:

And can be confirmed by page 313 and 314 of the datasheet:

To know where each pin is connected to (on the Arduino Uno) you can look the official (messy) schematic.

I provide an excerpt below that shows the Vin and 5V pins at the headers, and the power barrel connection.

If you want to control a 12V motor or a 12V LED strip or other DC loads you can use the following (which is also easy to find using Google):

*Note that your 12V Gnd and Arduino Gnd have to be connected.

simulate this circuit – Schematic created using CircuitLab


How might I add a delay, close the servo and go to the start again? #include <Servo.h>
Servo myServo;

  const int piezo = A0;
  const int button = 2;
  const int yellow = 3;
  const int green = 4;
  const int red = 5;

  int knockVal;
  int buttonVal;

const int quietKnock = 10;
const int loudKnock = 100;

boolean locked = false;
int numberOfKnocks = 0;

void setup()
{
  myServo.attach(9);
  pinMode(yellow, OUTPUT);
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(button, INPUT);
  Serial.begin(9600);

  digitalWrite(green, HIGH);
  myServo.write(0);
  Serial.println("The box is unlocked!");
}

void loop()
{ //start of loop
  if (locked == false)
  { //start of if1
    buttonVal = digitalRead(button);
    if (buttonVal == HIGH)
    { //Start of if2
      locked = true;
      digitalWrite(green, LOW);
      digitalWrite(red, HIGH);
      myServo.write(90);
      Serial.println("The box is locked!");
      delay (1000);

    }     //end of if2
  }      //end of if1

  if (locked == true)

  { //start of if3

    knockVal = analogRead(piezo);

    if (numberOfKnocks < 3 && knockVal > 0)

    { //start of if4

      if (checkForKnock(knockVal) == true)

      { //start of if5

        numberOfKnocks++;

      }   //send of if5

      Serial.print(3 - numberOfKnocks);
      Serial.println(" more knocks to go");

    }     //end of if4

    if (numberOfKnocks >= 3)

    { //start of if6
      locked = false;

      myServo.write(0);
      delay(20);
      digitalWrite(green, HIGH);
      digitalWrite(red, LOW);
      Serial.println("The box is unlocked!");

    }   //end of if
  }   //end of if3
}           //End of loop

boolean checkForKnock(int value)
{ //start of boolean

  if (value > quietKnock && value < loudKnock)

  { //start of if7

    digitalWrite(yellow, HIGH);
    delay(50);
    digitalWrite(yellow, LOW);
    Serial.print("Valid knock of value ");
    Serial.println(value);
    return true;
  }   //end of if7
  else
  { //start of else
    Serial.print("Bad knock value ");
    Serial.println(value);
    return false;
  }   //end of else
}     // end of boolean

if (buttonVal == HIGH)
{ //Start of if2
  locked = true;
  digitalWrite(green, LOW);
  digitalWrite(red, HIGH);
  myServo.write(90);
  Serial.println("The box is locked!");
  numberOfKnocks = 0;
  delay(1000);
}

I have added numberOfKnocks = 0 at this part of the code so your knock value goes to zero on locking it which will not open the lock again as soon as you lock it. The problem was that you did not change the numberoflnock value which remains same even after locking it so when the code loops back to the unlocking part it automatically unlocks it.
Hope this helps you.


Is there a method of figuring out whether or not my stepper drivers are dead? I'm working on a project that involves stepper motors, and I'm mainly using DRV8825 stepper drivers. At the moment, it seems like only one of my drivers actually gives the motors any current. The others usually return 0s when I measure their VREFs. One returns a value but still can't pull the motors. After checking all of my DRV8825s and finding only two returned VREFs, I checked my A4988s and none of them gave anything (aside from power supply voltage when measuring different pins). Is there a way I can figure out whether my stepper drivers are actually fried? I have a suspicion that maybe the potentiometers on the drivers are thrown off or there's some other issue I can't place. I'm happy to give more information if that can help to figure out what's going on here. Thank you!

Most surefire way to tell if your drivers work is to wire them up CORRECTLY and try them out.  You should not be frying them if you have the correct setup (including current limit) for your conditions.  That said, conditions include your heat sink install and the environmental temperature.
The usual gotchas:

Note that DRV8825 and A4988s may have different pin locations so be sure to orient them correctly (check their EN pin location) if using a shield.
Also note that the gains from the voltage to the current limits will be different for the different model #s.  Be sure to use an appropriately sized screw driver and attach the meter to the screw driver as you turn to adjust the current limit.


Arduino Pro Mini ATmega 328P: garbage output on serial console Arduino Pro Mini ATmega 328P 3.3V 8MHz, connected to USB port via USB to Serial breakout board built around the FT232RL FTDI chip. JTAGenum project code uploaded to the Arduino. I opened terminal and tried to run test command (without connecting wires between target and Arduino), but terminal output show garbage values. The baud rate of the serial console has been set 115200, as specified in JTAGenum code. Not sure whether this issue can be related to CPU_PRESCALE defintions in code.

Garbage values on output is mostly due to the baudrate.

Try changing the baudrate on the output terminal to the baudrate in the code.
Try checking the output by changing different baudrates on the terminal.

This must work for you :)


Is it possible to connect many arduino uno in one pc? We have many Arduinos and we will be putting each of them in a cubicle. All of them are connected to only one PC. The PC will stand as a server were you can control your Arduino there.

Yes, you can connect multiple Arduino UNO (USB) boards to a single PC. There's a simple way and a more advanced way to manage it.

The simple way is, having multiple boards plugged in, but using only one Arduino Software IDE to control one board at a time. (IDE = Integrated Development Environment. Some elements of the Arduino system use non-standard technical terms.) Use the Tools > Port menu to select which one of the attached boards to control. The selected board type and port appear in the lower right status bar.

A more advanced way to manage multiple boards, is to open multiple Arduino Software IDE instances -- each instance has its own independent Tools > Port setting. You could then edit, verify, and upload two different "sketches" (programs) to two different boards, without losing your place and without having to constantly change the Tools > Port setting. This would be convenient if you were developing a communications protocol between two or more boards.

This multiple-ports technique won't work unless you launch another instance of the Arduino Software IDE, without closing the first one. It isn't enough to use the File menu to open another window, because then you just get another window that shares the same Tools > Ports setting. Changing the ports setting on one window, changes the setting on all of the windows that belong to that instance. To support multiple boards at the same time, you have to actually launch the Arduino Software IDE again, without closing the first one, to create a second instance.

Usually you'd expect each window would represent a unique document, and they'd all be related to the application. But Arduino Software IDE has a hidden dependency between its windows. Whenever you restart the IDE, that opens a new and invisible instance of the IDE, where it remembers the board and port settings. If you use the File menu to open a new window, that new window is still part of the same IDE. So changing the Tools > Port setting on one window, changes that setting for all of the windows that belong to that instance of the IDE.

But if you restart the Arduino Software IDE (e.g. Windows Start Menu > Arduino-1.6.0), without closing the previously opened IDE, then you get a second instance. If you pay attention to the port setting visible on the lower right status bar of each window, you can distinguish which windows belong to which IDE instance.

Each time you launch the Arduino Software IDE, you start a new instance of the software, that can talk to one board. Each instance of the IDE can have an unlimited number of windows, but they all share the same Tools > Port setting. If you re-launch the Arduino Software IDE again without closing it first, then you get a second instance that can have a different Tools > Port setting, and thus control another board at the same time.

Verified on Windows 7, Arduino Software IDE 1.6.0, with two Arduino UNO revision R2 boards (firmware rev 0001), Arduino device driver 1.0.0.0.


split serial.readString() output I'm trying to read a string like this one:

2;12;42;43;34

over a serial connection and split this string afterwards by a ";".
So the output would be this array:

(2,12,42,34)

All the stuff runs on an arduino uno. So I made some code:

String read_input;
char read_input_char[20];
char *read_values;

void setup() {

  Serial.begin(9600);
  Serial.setTimeout(10);

}

void loop() {
  if(Serial.available()){
    read_input = Serial.readString();
    read_input.toCharArray(read_input_char, 20);

    read_values = strtok(read_input_char, ";");
    Serial.println(read_values[2]);
  }
}

However now instead of outputting the 3rd array element it outputs only an '1'. What's wrong?

This is a C question, not an arduino question, but anyway:

From the man page:

DESCRIPTION
   The  strtok()  function  breaks a string into a sequence of zero or more nonempty tokens.  On the first call to strtok() the
   string to be parsed should be specified in str.  In each subsequent call that should parse the  same  string,  str  must  be
   NULL.

You are only calling strtok() once, so it only parses the first value. You need to keep calling it until there is nothing left to parse.


Can I use this pinhole camera with arduino? The pinhole camera is a 420TVL, 3.7mm Passive Infrared Detector Color Covert Security Camera. Can I use this camera with an arduino creation?

Things I don't know to answer the question:

Does the power need something special arduino can't offer?
Is the arduino powerful enough to push the video feed/photos to a computer or any other method to video/photos.

Here are some specs from the site:

  Sensor   1/3" Sony Super HAD II CCD
  Picture Elements  NTSC 768x494
  PAL 752x582
  Horizontal Resolution 420 TVL
  Minimum Illumination  0.001 Lux
  S/N Ratio more than 50dB
  Scanning System   2:1 interlace
  Synchronous System    Internal, Negative sync
  Auto Electronic Shutter   NTSC 1/60s ~ 1/100,000s
  PAL 1/50s ~ 1/100,000s
  Gamma Characteristics 0.45
  Video Output  1 Vpp, 75 ohms
  Auto Gain Control Auto
  Power / Current   DC 12V (±10%) / 150mA
  Lens  3.7mm Taper Pinhole Lens

Is it possible? They're on sale but I don't want to throw money away and find out that they don't work with any arduino. Also, I don't have any setup for this to be plugged into. Therefore, I'm not tied down to previous creations the cameras need to fit in.

No, you cannot use this with an Arduino without additional hardware in between, and even with it, not as more than a still camera (or maybe low quality video for one of the ARM- rather than ATmega-based boards).

The first problem is that this camera has a high speed analog output called composite video.  It is basically what would be fed into a modulator to produce an old-style analog TV signal.  Capturing this digitally requires an Analog to Digital converter (ADC) capable of several million measurements per second, while that on the classic ATmega-based Arduino tops out at around ten thousand.

But let's say you had an additional Analog-to-digital converter to put in between this and your arduino.  The next problem is that the data rate out of the camera will be too high, and the Arduino won't have enough RAM memory to buffer it.

In theory, you could get a "frame grabber" consisting of an ADC and its own buffer memory, which would take a still snapshot of the video and allow the arduino to read it out more slowly.  But you can buy cameras which already do that with their onboard electronics, and allowing something like an Arduino to read the still image data out over a moderate speed serial interface.

Even the ARM-based arduino boards would be taxed to keep up with the output of a video ADC and do much of anything useful with the results - typical digital cameras do not record raw images to SD card, but do JPEG compression within a frame.  When cheap digital cameras operate in video mode, they compress each frame of the video before storing it (just as with stills - they do not compress between frames in the manner of real video recorders), and are able to get that processing done in time because the actual computing hardware is optimized for it in a way that none of the Arduinos are.

If you want to experiment with a camera on a development platform, there is one with a high speed digital interface sold as an add-on for the Raspberry Pi board.  Or you can use a more inexpensive USB webcam with that.


Generate a true analog signal using Arduino I am looking for a way to create a true analog output with the arduino uno. I am constantly reading an analog input on a0 pin, all i want to do is send the same signal as output. I know arduino convert the signal into pwm so have can i convert it back to true analog signal.I have a dac too but not getting proper output.
secondly, i want to send same signal by converting it into bits through Ethernet so how do i send and receive the signal.
here is my code for dac.
#include "Wire.h"
#include "MCP4725.h"
MCP4725 MCP(0x60);
uint32_t microphonePin=A0;
uint32_t threshold=800;
const int ledPin=13;

void setup() {
    Serial.begin(115200);
    pinMode (ledPin, OUTPUT);
    Serial.print("MCP4725 test program: ");
    Serial.println(MCP4725_VERSION);
    if (MCP.begin() == false)
     {
       Serial.println("Could not find sensor");
     }

    MCP.begin();
 }

void loop() {
   uint32_t sensorValue=analogRead(microphonePin);
   MCP.writeDAC(sensorValue);
   Serial.println(MCP.getValue());
   if (MCP.getValue()>threshold)
    {
      digitalWrite (ledPin, HIGH);
    }
   else{ digitalWrite(ledPin, LOW); }

  }

here is my circuit for audio amplifier

and for the speaker it is connected on DAC out.
FYI:I am able to read the data on my serial monitor form mic and i am also able to so do some operation by just using mic and GUi. I just want to here what i am saying on speaker.

I see that MCP4725 uses Wire library with the default clock of 100,000 kb/sec.
At a rough estimation each call to MCP.writeDAC or MCP.getValue will be at least 32 bits long and you use three of them in each loop.
This one:
   Serial.println(MCP.getValue());
   if (MCP.getValue()>threshold)

is redundant, you should store the value in a temporary variable and use-it in both "print" and "if".
With 10us for each bit that means 1060 us for each loop. The analog read also takes 100us to complete. Over all 1160us minimum.  Is the MCP.getValue() really needed?
That means that your maximum sample frequency is 860hz and the maximum bandwidth of 430hz. I doubt that this is an acceptable bandwidth for a microphone.
Even so, the output signal will not look similar at all, you need a higher bandwidth or to limit,  if possible, the bandwidth of the input signal.
In some limits you can modify the MCP4725 library to use fast wire clock four times faster if it suits your requirements. If you also drop the two MCP.getValue() calls that will be again almost three times faster, up to 5khz.
Also you might search for faster ADC on Arduino.
Update after OP microphone amplifier schematic.
The ADC works only with positive voltages. Short the output capacitor of the amplifier!


Reading text from sd card is returning weird characters? I have an ebook which is converted to a .txt file saved on an sd card which is connected to the arduino. I'm trying to display the words from the book on a 16x2 lcd display on word at a time. It works mostly except when it reads a word that has an apostrophe or a pipe symbol it does not display correctly to the lcd display or the serial output.

For example the word "author's" will be displayed as "authorâs" (edit: there is actually two boxes between the "â" and the s that is not displaying on this forum) on both the lcd display and serial output.

I've spent an entire day now with this one problem hopefully there is a mistake someone can pick up on :/

#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>

const int chipSelect = 53;

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

char nextChar;
String wordBuffer = "";

void setup() {

  lcd.begin(16, 2);

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt");

  if (dataFile) {
    while (dataFile.available()) {

      nextChar = dataFile.read();

      if (isWhitespace(nextChar)){

        lcd.print(wordBuffer);

        Serial.println(wordBuffer);

        lcd.display();

        delay(500);

        wordBuffer = "";
        lcd.clear();

      }
      else{

        wordBuffer = wordBuffer + nextChar;
        wordBuffer.trim();
      }

    }
    dataFile.close();
  }

  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }
}

void loop() {
}

The text file is not ASCII, it is UTF-8. You will either have to convert it to pure ASCII, or write (or obtain) a conversion routine to approximate the UTF-8 characters using ASCII on the Arduino.

Maybe this can help you.


Serial.print start prints unreadable character without any reason I wrote the following code. The idea is to execute some AT command on my ESP-01 module. The problem is that first command is execute without problem, the second sometimes but the reply on AT+GMR is the following:
    AT

OK
AT+GMR

AT version:1.1/0.0(May 11 3016 18:09:57)
SDK version:1.5.ar.0
AR)�WS�TZ�j
C�j�L�AZCA�O�C�

FINE

The problem is that, after some thing that I don't understand, the formatting (maybe the baud change?) gone wrong. Then the reply of the following commands became unreadable. Any idea why it happens?

#include <SoftwareSerial.h>
#define DEBUG true
SoftwareSerial wifi(2,3);

void setup() {
   Serial.begin(115200);
   wifi.begin(115200);
   sendCommand("AT\r\n", 2000);
   sendCommand("AT+GMR\r\n",2000);
   sendCommand("AT+CWMODE=2\r\n", 2000);
   sendCommand("AT\r\n", 2000);
   Serial.print("\n\nFINE");
}

void loop() {}

String sendCommand(String cmd, int timeout){
   wifi.print(cmd);
   return readSerial(timeout);
 }

 String readSerial(int timeout){
   long int time = millis();
   String res = "";
   while( (time+timeout) > millis() ){
        while(wifi.available()){
          char c = wifi.read();
           res += c;
        }
    }
    if(DEBUG)
       Serial.print(res);

    return res;
 }

The problem was about high baud for SoftwareSerial. Changing it to 9600 the problem disappears.


Uploading code to Mega 2560 is stuck I'm trying to upload code from a Mac (online Arduino editor) onto an Arduino Mega2560, to connect a motor to pin 52 and Ground to get it to move. But at the top it says busy (like it does when it uploads) and doesn't do anything else. Refreshing the page doesn't work. The code is verified, and here's the code:

void setup() {
}

void loop() {
  digitalWrite(52,HIGH);
}

The Arduino application (with same code copied in) comes up with this error:

Arduino: 1.8.4 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)" Sketch uses 1190 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't open device "COM1": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device
ioctl("TIOCMGET"): Inappropriate ioctl for device
avrdude: ser_send(): write error: Bad file descriptor
avrdude: stk500_send(): failed to send command to serial port
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
the selected serial port avrdude: stk500v2_getsync(): timeout communicating with programmer does not exist or your board is not connected

I hope someone can work out why it doesn't upload!

I would suggest to download the Arduino app (https://www.arduino.cc/en/Main/Software).

Download both the latest version and an a legacy build (https://www.arduino.cc/en/Main/OldSoftwareReleases#00xx). Within the DMG for the legacy you'll need to install the FTDI drivers to allow Arduino app to see the Arduino in ports.


Module and library for self healing large sensor network I have to build a wireless sensor network with arduinos on my project. It does not need to be a mesh network, but it needs to have self healing capabilities.

I would like to use something cheaper than XBees. I tried the NRF24L01 with maniacbug's, TMRh20's and MySensors' libraries. However they aren't solving the problem and I'm wasting a ton of time trying to figure out how to make them work.

Another thing, I need a lot of repeater nodes between the base and the sensors because the office is 2 km far from the monitoring area and some of these libraries have a limitation of 5 level deep network, so I'd have max 4 repeaters between the base and sensor, which is bad.

And the last, my project is going to be fine with 15 sensors for now, but it'll have 500-1000 nodes in a couple of months and most of these libraries assign 8 bit addresses (256 nodes), which does not cover that amount of nodes.

What do you suggest?

A few thoughts:

For ~$20 per unit, the 1mW Digimesh modules will take care of reliable mesh networking plus provide a high degree of configurability and scalability. Depending on the budget for your sensor nodes this might be better than "wasting a ton of time" messing with bare-bones hardware and third party code.
Constrain the mesh network within the "monitoring area" and set up dedicated point-to-point links (with higher power and directional antennae) between it and your office. Set up two or three if you want redundancy.
If you can't afford better hardware but have time to spare, consider reading up on mesh protocols and implementing one you think best fits your project. Many of them are reasonably simple if you are not pushing for maximum efficiency or performance.


Arduino Pro Micro not recognized by PC so I've got myself a Arduino Pro Micro ATmega32U4 5V 16MHz and my PC (Win10 64bit) won't recognize it.
So, after I firstly plugged it in, it was detected as a Leonardo, rather than a Pro Micro, afterwards I installed hte drivers as noted by Sparkfun, and added the board to the IDE. Afterwards, my Arduino got detected as an unknown device where I can't use it anymore. I tried installing the drivers as given by sparkfun over the "unknown device" and no luck by trying, I always get an error saying that Windows has already the best drivers for it already installed.
And later, I uninstalled the "uknown device" in hope that it will re-install itself upon pluggin it back it, and it actually disappeard totally and got repalced by "Unknown USB Device (Device Descriptor Request Failed)" under USB controllers in the Device manager.
And I'm stuck here. In the IDE, the Pro Micro is detected as being on "COM1" no matter what COM port it really is, or is it even plugged it at all. Uploading a code results in the bar being filled up and "Uploading..." message, while maybe after a few minutes a very long error pops up without anything specific since you can plug out the board and get the same error.
I also tried a different PC with Windows 7 64bit on it, and instead of getting recognized as a Leonardo, this time it came straight to becoming a "Unknown device". I tried installing drivers multiple times with no luck, also again tried manually overiding the drivers in the Device manager and it always says that the best drivers are already installed.
I'm really stuck here.
Pics of  the board: https://postimg.cc/gallery/rwCDRfv

It was wrong of you to try and install the driver as this board SHOULD be recognized as Leonardo. I would try to reinstall the Arduino IDE, it will also reinstall the drivers (hopefully)


Flash an ESC Through Serial USB without Arduino Interrupting the Signal So I have four Electronic Speed Controllers (ESC's), each connected to a motor. I am building a drone with an Arduino UNO board as my flight controller. For convenience, I have soldered the signal wires on each of the four ESC's onto the bottom of the Arduino where the Arduino's pin headers are soldered on. The serial ground pins on the ESC's are soldered to the ground pins on the Arduino.

The ESC's I am using can be found here.

In order to change settings on my ESC's, I am trying to use this Turnigy USB linker to connected to the BLHeli software on my computer.
The linker has a signal and a ground wire for Serial Communication, as well as a positive wire (I think this is just to fit the connector on ESC's with a BEC, but mine are OPTO, and have none). To connect the USB Linker to an ESC, I should be able to plug it into appropriate female pin headers on the Arduino using some breadboard-type jumper cables.

At least that's what I thought...

Whenever I try to connect to an ESC with the BLHeli software, I get a message:
Please Connect ESC and power up or cycle power.

Earlier, I was able to make the connection and change the settings on my ESC's when they weren't connected to the Arduino board, but now that they are soldered and hot-glued on there, they won't work. So the question is: What is the Arduino doing to the Serial connection, and how can I fix it without desoldering my ESC's whenever I need to change some settings?

Now before you ask:

Yes, the ESC is powered up and connected to a motor. It gives me a happy beeping sound.
Yes, I definitely have the signal and ground wires connected correctly. I have been trying to figure this out for days, and have even tried switching them.
The Arduino is turned off when I try to connect an ESC to the USB Linker.
Only one ESC is powered on at a time.

Maybe the Arduino has some kind of protection circuit for the IC that is messing up the signal, or maybe the ESC's have something similar that's messing it up too, because some of the ground wires are connected together. I'm going to have a very difficult time figuring this out myself, so hopefully someone out there has an idea of what's going on.

Thanks for any help you have to offer.

-- Ember

I can offer general advice without reference to specific implementations.

By driving the Arduino pins when it is powered off you are potentially exceeding it's maximum rated specifications for voltage on any ping, and possibly for current into a pin, and you risk damaging it.
When the Arduino is powered down its Vdd pin and power supply rail will be at about 0.0 volts and will be loaded to ground by power supply capacitors and various other items connected to Vdd - including the OUTPUT of the Vdd voltage regulator in many cases.
Each Arduino pin is connected to the Vdd rail by a body / protection diode. To drive the pin high you must also raise Vdd to high-1 diode drop and must drive the Vdd rail load from your signal line via the body diode.
If your programmer has the ability to do this there is a reasonable chance that you may damage the body diode. For extra points, a very capable signal input MIGHT damage the Arduino's voltage regulator and possibly other on board devices - but I'd think that to be unlikely.

The technically best solution is to disconnect the Arduino's relevant pins when programming. As you obviously would rather not do that, then ...

Probable solution: If you power on the Arduino and run a program which ensures that the relevant pins are set to input mode then it should work as required. IF the Arduino default program sets the relevant pins to inputs then just powering it on should suffice, but odds are that the serial port pins are not both configured as inputs.
If the Arduino has a USB to serial port IC or other devices connected to the pins in question then you will need to also ensure that they do not load the pin excessively and that they will not be damaged by programming signals. eg if you were trying to drive the Arduinos serial RX_in pin which was connected to the TX_out pin of a USB-Serial IC then the programmer would be attempting to drive the USB-serial output pin and this must be dealt with in some way.

Checklist:

Is there something else connected to this pin.

If so

What state is it in during ESC programming
Will it be damaged by programming
Will it affect programming.
What action is thus needed.


How much can I recurse? How much can I recurse? How much ca!@#QFSD@$RFW The Arduino Uno board has limited RAM which means it has a limited call stack available. Sometimes, recursion is the only quick option to implement a certain algorithm. So, given that the call stack is severely limited, what would be a way to find out that given a certain program running on the board, exactly how many recursive calls can you afford before there is a stack overflow (and bad things happen)?

If you really want to recurse (and as @jippie said it is a bad idea; subliminal message:  don't do it) and want to know how much you can recurse, then you will have to perform some calculation and experiments; also you generally will have only an approximation of it as it depends a lot on the memory state at the time your recursive function will be called.

For this, you should first know how SRAM is organized inside AVR-based Arduino (it won't apply to e.g. the Arduino Galileo by Intel). The following diagram from Adafruit shows it clearly:

Then you need to know the total size of your SRAM (depends on Atmel MCU, hence what kind of Arduino board you have).

On this diagram, it is easy to find out ths size of Static Data block as it is known at compile-time and won't change later on.

The Heap size can be more difficult to know as it can vary at runtime, depending on dynamic memory allocations (malloc or new) performed by your sketch or the libraries it uses. Using dynamic memory is quite rare on Arduino, but some standard functions do it (type String uses it, I think).

For the Stack size, it will also vary during runtime, based on the current depth of function calls (each function call takes 2 bytes on the Stack to store the address of the caller) and the number and size of local variables including passed arguments (that are also stored on the Stack) for all the functions called until now.

So let's suppose your recurse() function uses 12 bytes for its local variables and arguments, then each call to this function (the first one from an external caller and the recursive ones) will use 12+2 bytes.

If we suppose that:

you are on Arduino UNO (SRAM = 2K)
your sketch does not use dynamic memory allocation (no Heap)
you know the size of your Static Data (let's say 132 bytes)
when your recurse() function is called from your sketch, the current Stack is 128 bytes long

Then you are left with 2048 - 132 - 128 = 1788 available bytes on the Stack. The number of recursive calls to your function is thus 1788 / 14 = 127, including the initial call (which is not a recursive one).

As you can see, this is very difficult, but not impossible to find what you want.

A simpler way to get the stack size available before recurse() is called would be to use the following function (found on Adafruit learning center; I have not tested it myself):

int freeRam ()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

I strongly encourage you to read this article at Adafruit learning center.


What is the best arduino board for a robotic arm? In my university we need to buy arduino boards and kits to build a moving robotic arm, that moves up and down and clockwise in a specific degree (almost like humans's).

So, what's the most suitable arduino board to build this arm?
I suggested to use the basic UNO board, but we may need to use relays (for example) if the power source is 12volts. So there is should be a better one.

My regards.

If you are hoping to drive the arm straight from the Arduino, that's not going to work.

What you should do is:

Define the maximum weight and size of the load your arm will carry.
Define expected precision and speed of the movements.
Count the Degrees of Freedom (DoF) your arm will need (1 DoF = 1 simple joint)
Figure out size and materials of each part of the arm
Calculate the torque required at each joint (yes, you need some basic physics calculation)
Identify the motors you want to drive (DC are inexpensive but not very well suited for this, without lots of additional control logic & HW - stepper motors are better, but they still do require some additional effort - servos are the easier way but they are a bit more expensive)
Define the requirements for both the micro controller and the power supply, based on the previous choice.

If you can refine your question, based on the few points I sketched, you will get ahead much faster and with less risk later on to have to backtrack and re-design something.

You might have already answered some of those steps, then I suggest you list here your choices.

Similarly, if you are referring to some link you found (instructables, etc.) please post it.

As reference, hobbyking has an extensive catalog of motors and power supplies. You can find the same items also on ebay, but hobbyking can be used at least as reference for various specs (power, torque, weight, etc.).


2.8 inch tft LCD displays / Max Brightness / Startup White Screen / mirror text for Head Up Display Usage hi does anyone know how to

1) set Max Brightness
2) change the start up splash screen from being white to black
3) how to change settings so that text can be mirrored so when display is reflected into mirror or glass window the text reflects onto the mirror / glass so that it is readable

The code from the sketch may answer some of your tecnical question re the environment i am working with

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_TFTLCD.h> // Hardware-specific library

#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0

1) set Max Brightness

You set the brightness of the backlight (usually) using PWM.

  2) change the start up splash screen from being white to black

That's not a splash screen. That's just the back light being on before the screen is initialised. Just don't turn on the back light until you need it.

  3) how to change settings so that text can be mirrored so when display is reflected into mirror or glass window the text reflects onto the mirror / glass so that it is readable

Either do it in software (tricky) or look at the MADCTL (many have it called that) register in the datasheet.  The library probably won't support it, but it's part of how it deals with display rotation, so you could examine that function and compare it with what's in the datasheet (hint: 180° rotation is actually flipping both the X and Y axis).


Time counting using millis I am trying to write a code where photoresistors (a or b) sense blinking of the light, and lights LED (k and d) simultaneosly with that blinking. And I want that when both photoresistors sense dark for more than 3 secs, the LEDs would light up and stay until one of them again gets lighting. But I cannot understand in which part should I put millis time count?

int k = 2;
int d = 3;
int fk = A0;
int fd = A1;
int a = 0;
int b = 0;

void setup() {
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  a = analogRead (fk);
  b = analogRead (fd);
  while (a < 1000 && b < 1000)
  {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    a = analogRead (fk);
    b = analogRead (fd);
  }
  if (a > 1000)
    digitalWrite(2, HIGH);
  else
    digitalWrite(2, LOW);
  if (b > 1000)
    digitalWrite(3, HIGH);
  else
    digitalWrite(3, LOW);
}

This is one of those cases where the solution is simply to implement a
finite state machine. Consider a state machine with these three
states:

LIGH: light has been detected by at least one of the sensors, the
LEDs follow the light sensors
SHORT_DARK: neither sensor sees light, both LEDs are off
LONG_DARK: it has been at least three seconds since neither sensor
saw light, both LEDs are on.

The transitions between those states can be depicted by the following
state diagram:

where “darkness detected” means that no sensor sees light, and “light
detected” means that at least one sensor sees light.

As a general rule, it is a good practice to always draw a state diagram
before you start writing code. Once you are sure your diagram describes
the desired behavior, it is almost trivial to translate it into code.
Here is how I would code it:

void loop()
{
    bool light_k = analogRead(IN_K) >= 1000;
    bool light_d = analogRead(IN_D) >= 1000;

    static enum { LIGHT, SHORT_DARK, LONG_DARK } state;
    static uint32_t darkness_start;
    switch (state) {
    case LIGHT:
        digitalWrite(OUT_K, light_k ? HIGH : LOW);
        digitalWrite(OUT_D, light_d ? HIGH : LOW);
        if (!light_k && !light_d) {
            darkness_start = millis();
            state = SHORT_DARK;
        }
        break;
    case SHORT_DARK:
        if (light_k || light_d) {
            state = LIGHT;
        } else if (millis() - darkness_start >= 3000) {
            digitalWrite(OUT_K, HIGH);
            digitalWrite(OUT_D, HIGH);
            state = LONG_DARK;
        }
        break;
    case LONG_DARK:
        if (light_k || light_d) {
            state = LIGHT;
        }
        break;
    }
}


Run multiple function with different argument/return structure by one function pointer Edit:
I tried a simple code in Arduino IDE which should've done in the first place instead in doing it in a desktop compiler. Because the results are different by experiment. In the desktop C compiler, it's working and bypassing the code without much problems, just one or two warnings.
But in Arduino IDE, it's not acceptable and gives error.
This is the code:
// functions
void function1(uint8_t x, uint8_t y){
  int z = x + y;
  Serial.println("function1\n");
  Serial.println(z);
}
uint8_t function2(uint8_t x, uint8_t y){
    Serial.println("function2\n");
    return 1;
}

void (*fun_ptr)();

void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);
  fun_ptr = (void (*)())function2;
  int value;

  value = fun_ptr(1,2);

}

void loop() {
  // put your main code here, to run repeatedly:

}

I assume, that the fun_ptr points to the different service functions to do some kind of animation other other long running tasks on your display, thus you want to repeatedly call them in a structured way.
What you are currently doing will not really work. When you call a function, you need to provide its arguments. That's the same for a function pointer. You cannot call a function, that demands parameters, without any parameters. While you can still set a function pointer of type (void (*)(void*) to a function of type (void (*)(uint8_t)), the compiler warns so, because you still cannot call the function without any parameter. If you are trying to do so, you will still get an error of too few arguments to function ....
I see 2 ways to go from here:

You could overload your functions, so that a version without any parameters exists. Like this:
  void foo(uint8_t i){Serial.println(i);}
  void foo(){foo(10);}

With 10 being the value, with which the function should be called, when you provide no parameters. You can of course also use variables or function calls here, to actually get that value for the parameter i. Then you can use the pointer to call that function:
  void (* p)(void);
  p = &foo;
  p();

The assignment of the pointer will choose the version of the function without any parameters out of the overloaded pool of this function, since that matches the type of the pointer. Note, that I removed the * from the void parameter definition. I don't understand, what that would mean anyway (pointer to void?). The function pointer p() can now be called without any parameters, since it points to a function without any parameters.

You could ditch the function pointer and use a simple switch case statement with a state variable (which holds some identifier for the corresponding function), to call the correct service function. I won't go into detail here, since that is already basically, how an FSM can be programmed in C++, which is covered on this site and on the web numerous times.

If I were you, I probably would go with the first option, though that might also depend on the overall logic, that I currently don't really understand (too few information).


expected unqualified-id before '.' token //my coding

#include<DHT.h>              // Including library for dht
#include<LiquidCrystal.h>
LiquidCrystal lcd(14,15,16,17,18,19);
#include<Timer.h>
Timer t;
#include <SoftwareSerial.h>
SoftwareSerial Serial1(2, 3);

#define dht_dpin 12
#define heart 13

DHT dht;

char *api_key="0UXHCZ777V0PAWPW";     // Enter your Write API key from ThingSpeak
static char postUrl[150];
int humi,tem;
void httpGet(String ip, String path, int port=80);

void setup()
{
 lcd.begin(16, 2);
 lcd.clear();
 lcd.print("   Humidity   ");
 lcd.setCursor(0,1);
 lcd.print("  Measurement ");
 delay(2000);
 lcd.clear();
 lcd.print("Circuit Digest ");
 lcd.setCursor(0,1);
 lcd.print("Welcomes You");
 delay(2000);
 Serial1.begin(9600);
 Serial.begin(9600);
 lcd.clear();
 lcd.print("WIFI Connecting");
 lcd.setCursor(0,1);
 lcd.print("Please wait....");
 Serial.println("Connecting Wifi....");
 connect_wifi("AT",1000);
 connect_wifi("AT+CWMODE=1",1000);
 connect_wifi("AT+CWQAP",1000);
 connect_wifi("AT+RST",5000);
 connect_wifi("AT+CWJAP=\"1st floor\",\"muda1884\"",10000);
 Serial.println("Wifi Connected");
 lcd.clear();
 lcd.print("WIFI Connected.");
 pinMode(heart, OUTPUT);
 delay(2000);
 t.oscillate(heart, 1000, LOW);
 t.every(20000, send2server);
}

void loop()
{
***DHT.read11(dht_dpin);     error in this line***
  lcd.setCursor(0,0);
  lcd.print("Humidity");
 **humi=DHT.Humidity;**   error in this line

  lcd.print(humi);   // printing Humidity on LCD
  lcd.print(" %    ");
  lcd.setCursor(0,1);
  lcd.print("Temperature");
**tem=DHT.Temperature;**  error in this line
  lcd.print(tem);   // Printing temperature on LCD
  lcd.write(1);
  lcd.print("C   ");
  delay(1000);
  t.update();
}

void send2server()
{
  char tempStr[8];
  char humidStr[8];
  dtostrf(tem, 5, 3, tempStr);
  dtostrf(humi, 5, 3, humidStr);
  sprintf(postUrl, "update?api_key=%s&field1=%s&field2=%s",api_key,humidStr,tempStr);
  httpGet("api.thingspeak.com", postUrl, 80);
}

//GET https://api.thingspeak.com/update?api_key=0UXHCZ777V0PAWPW&field1=0
void httpGet(String ip, String path, int port)
{
  int resp;
  String atHttpGetCmd = "GET /"+path+" HTTP/1.0\r\n\r\n";
  //AT+CIPSTART="TCP","192.168.20.200",80
  String atTcpPortConnectCmd = "AT+CIPSTART=\"TCP\",\""+ip+"\","+port+"";
  connect_wifi(atTcpPortConnectCmd,1000);
  int len = atHttpGetCmd.length();
  String atSendCmd = "AT+CIPSEND=";
  atSendCmd+=len;
  connect_wifi(atSendCmd,1000);
  connect_wifi(atHttpGetCmd,1000);
}

void connect_wifi(String cmd, int t)
{
  int temp=0,i=0;
  while(1)
  {
    lcd.clear();
    lcd.print(cmd);
    Serial.println(cmd);
    Serial1.println(cmd);
    while(Serial1.available())
    {
      if(Serial1.find("OK"))

      i=8;
    }
    delay(t);
    if(i>5)
    break;
    i++;
  }
  if(i==8)
  {
   Serial.println("OK");
        lcd.setCursor(0,1);
      lcd.print("OK");
  }
  else
  {
   Serial.println("Error");
         lcd.setCursor(0,1);
      lcd.print("Error");
  }
}

You declare an object of type DHT and name dht. Then you try to call a method of DHT.read11().

Instead, you should be using the object name, dht.read11(), or as @Gerben points out, change the way you declare the object:  DHT dht;.


Modifying smart watch or activity armband with further sensors I want something like an activity armband where I would like to add an bend sensor or EMG sensor for simple hand gesture recognition tasks. I could probably build it from scratch with arduino-like parts, but it will be much more bulky then the ones on the market and I would rather not reinvent those things that already do what I want. This is the type of device I am thinking about.

Is there an feasible task to try to modify an existing activity armband or smart watch by adding one of these sensors? If so, do you have any suggestions of what should be considered? Should I try something completely different? I am open to ideas.
I have a background in Physics and Computer Science with an basic understanding of electronic devices but I am eager to learn.

there are a few DIY, open source armband or watch models like :

https://www.tindie.com/products/ttgo/t-wristband-diy-programmable-smart-bracelet/

which has the sources and tutorials on :

https://github.com/Xinyuan-LilyGO/LilyGO-T-Wristband

it's based on ESP32 and is Arduino ready.the space constraint may not allow for adding a new sensor, but it already comes with a few onboard sensors.
after getting along with ESP32 and the TTGO libraries (which are all provided by the manufacturer LilyGo) that wouldn't be too hard to design a custom band.


How to read response from server using an Ethernet shield? I want to control a relay by reading values from MySQL. I'm using an Arduino and an Ethernet shield. So far, I can get the response from server and get the value. I just need the value 10110110, but I get a response in the serial monitor like this:

HTTP/1.1 200 OK
Date: Sun, 02 Jul 2017 07:53:29 GMT
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By: PHP/5.3.1
Content-Length: 13
Content-Type: text/html

<10110110>

How to remove this long response and get the value 10110110?

There are, obviously, a great number of ways that this can be achieved. The simple brute force way would be to have a series of if statements, looking for a sequence of eight consecutive 0s and/or 1s, and loop through the string containing the response.

Or you could loop through the response, using strcmp(), similar to what is described here: how to do like a grep in a sketch?

However, a more intelligent method would be to use pattern matching and regular expressions.

From New regular expression library released, Nick has provided a Regexp library. It uses Lua for the expression syntax, see string.find, for more details.

I am still playing with this code, but your sketch would need something like this:

#include <Regexp.h>
void setup ()
{
  Serial.begin (115200);
  Serial.println ();

  unsigned int index = 0;
  char buf [100];

  MatchState ms;
  ms.Target ("HTTP/1.1 200 OK\
Date: Sun, 02 Jul 2017 07:53:29 GMT\
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
X-Powered-By: PHP/5.3.1\
Content-Length: 13\
Content-Type: text/html\
\
\
<10110110>");  // what to search

  while (true){
    char result = ms.Match ("^<([01][01][01][01][01][01][01][01])", 0);  // look for an eight bit binary digit
    if (result == REGEXP_MATCHED)
    {
      Serial.println ("-----");
      Serial.print ("Matched on: ");
      Serial.println (ms.GetMatch (buf));
      Serial.println ("Captures:");
      for (int j = 0; j < ms.level; j++)
         Serial.println (ms.GetCapture (buf, j));
      // move past matching string
      index = ms.MatchStart + ms.MatchLength;
    }  // end of match
    else
      break;  // no match or regexp error

  } // end of while

}  // end of setup

void loop () {}

This code assumes that you are looking for a line beginning with < and captures an eight digit binary thereafter - as determined by the expression within the inner (), in the line:

    char result = ms.Match ("^<([01][01][01][01][01][01][01][01])", 0);  // look for an eight bit binary digit

So, it should output:

-----
Matched on: <10110110
Captures: 10110110
-----

Obviously, instead of just outputting the captured binary digits to the serial monitor, you need to save them for your relay control.

For neatness, you could replace

 ms.Target ("HTTP/1.1 200 OK\
Date: Sun, 02 Jul 2017 07:53:29 GMT\
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
X-Powered-By: PHP/5.3.1\
Content-Length: 13\
Content-Type: text/html\
\
\
<10110110>");  // what to search

with

  char * str = "HTTP/1.1 200 OK\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
    X-Powered-By: PHP/5.3.1\
    Content-Length: 13\
    Content-Type: text/html\
    \
    \
    <10110110>";

  ms.Target (str);

Note the use of the backslashes at the ends of the lines. I've included them here, in order to get the test sketch to compile. You probably will not need them as you would be receiving the response from the server, and not providing an example string for testing.

Here is a working version, along with multiple test strings (input_str) and example match strings (match_str):

#include <Regexp.h>
void setup ()
{
  Serial.begin (9600);
//  Serial.begin (115200);
  Serial.println ();

  unsigned int index = 0;
  char buf [100];

// Simple test pair
//  char * input_str = "RGB:123";
//  char * match_str = "(%a)";

// Simulated MySQL responses
// Most basic
//  char * input_str = "<10110110>";
// Over two lines
//  char * input_str = "http\\n<10110110>";
// Full response
  char * input_str = "HTTP/1.1 200 OK\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
    X-Powered-By: PHP/5.3.1\
    Content-Length: 13\
    Content-Type: text/html\
    \
    \
    <10110110>";
// Full response with newlines
//  char * input_str = "HTTP/1.1 200 OK\\n\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\\n\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\\n\
    X-Powered-By: PHP/5.3.1\\n\
    Content-Length: 13\\n\
    Content-Type: text/html\\n\
    \\n\
    \\n\
    <10110110>";
// Shorter version of full MySQL response with newlines
//  char * input_str = "Content-Type: text/html\\n\
    \\n\
    \\n\
    <10110110>";
// Shorter version of full MySQL response with newlines with no preceeding spaces
//  char * input_str = "Content-Type: text/html\\n\
\\n\
\\n\
<10110110>";

// Match strings for MySQL response, containing an eight bit binary number
// Match at beginning of line
//  char * match_str = "^<([01][01][01][01][01][01][01][01])";
// Match at beginning of line with multiple newline characters
  char * match_str = "[\n]*<([01][01][01][01][01][01][01][01])";
// Match at beginning of line with zero or one newline characters
//  char * match_str = "[\n]?<([01][01][01][01][01][01][01][01])";
// Match at anywhere
//  char * match_str = "<([01][01][01][01][01][01][01][01])";

  MatchState ms;

  while (true){
    char result = ms.Match (match_str, 0);

    if (result == REGEXP_MATCHED)
    {
      Serial.println ("-----");
      Serial.print ("Matched on: ");
      Serial.println (ms.GetMatch (buf));
      Serial.println ("Captures:");
      for (int j = 0; j < ms.level; j++)
         Serial.println (ms.GetCapture (buf, j));
      // move past matching string
      index = ms.MatchStart + ms.MatchLength;
    }  // end of match
    else
      break;  // no match or regexp error

  } // end of while

}  // end of setup

void loop () {}

For the match_str line,

char * match_str = "[\n]*<([01][01][01][01][01][01][01][01])";

you may or may not need the caret (^) to match at the start of the line, and the [\n]* or [\n]?. See which combination works for you.


12V but what Ampere? So if my arduino will draw around 800mA @5V and the dc-dc buck converter around 266mA @5V plus solenoid 1.2A @12V, is it a good idea to get 12V 4A (48W) power supply? Since Filip Franik told me that it is a good practice to get 2 times the current I need just in case. Then what will happen to the current that are no in use?

So you want to use the 5V voltage regulator on the Arduino serve as the supply for your 5V components, and feed the 5V regulator from the 12V supply that powers your solenoid?

The problem with that plan is heat. The voltage regulator on the Arduino is a poorly heat-sinked (heat-sunk?) "linear" regulator. A linear voltage regulator is basically a solid state circuit that converts excess voltage to heat.

The higher the supply voltage you provide to the voltage regulator, the more heat it generates for a given current load.

If you feed 12V into the Arduino's voltage regulator, it needs to reduce the voltage from 12V to 5V. 12V - 5V is 7V. So it will convert 7V to heat. You're only drawing ≈220 mA. Total power that will be converted to heat is 7V*0.22A, or around 1.54 watts of power. You should budget for at least 50% more current than you think you'll need, so lets use 330 mA. 7.0*0.33 is about 2.3 watts.

From a little research I did, it sounds like a typical Arduino voltage regulator can dissipate around 1 watt of heat. You're well over that limit even at your low ≈220mA number, so you need a solution that won't overheat your Arduino's voltage regulator.

If you were to instead supply the Arduino's voltage regulator with 7.5V, it would have a lot less work to do. That's a voltage drop of 2.5V. So for a 0.33 max current draw, that would be 2.5*0.33, or about 0.83 watts. That would be under the 1 watt ceiling. However, it sounds like your project is based on a 12V supply.

You could instead use an external switching voltage regulator to reduce 12V to 5V. (search for "boost voltage regulator".) Those are much more efficient, and don't generate nearly as much heat. You could then feed regulated 5V directly into the USB input on your Arduino, as well as supplying it to your other 5V components.