text:
Creating linear motion using motor
I am trying to make a smart lock for bicycles. This lock can be controlled with the help of smartphones. For the purpose, I am using an Arduino interfaced with HC-05 Bluetooth Module which receive commands from an Android smartphone.
The overall project is almost over, except the actual lock. I want to create a lock with a pin which can be slide between the spokes of the wheel to cease the motion of the wheels. I can't find any product in the Indian market. Can you please suggest any product available or how to make one myself?

I've seen the solenoid locks but their stroke is too small to make a meaningful lock out of it.

Your help will be well appreciated.

Is it a proof of concept, or does the lock really have to be solid and temper proof?

You may find Robotics Stackexchange useful for questions like this.

I just have to show it as my college project @Paul

As a demonstration, you could show an servo that rotates and pushes a pin between the wheels. Or modify a regular lock in a way that you can drive it with a motor.

The pin that slides between the spokes should be just a metal bar that accepts your "small" pins in the ends to hold it in place.  Try looking at it from a different perspective and I think you will find a lot more suitable products.
You could use a worm gear, but this would be susceptible to bruit force attacks (literally) and would be easier to break.
Have you considered what happens when the power fails?  Does the lock lock or unlock?  If it unlocks on a power fail then it will be quite easy to open.  If it remains locked on a power fail then its not very user friendly, you would have to carry spare batteries and changing tools with you.
Sorry, but it is easy to poke holes in other peoples designs.

I like your suggestions @Matt, but it won't be a end product. I just have to show a working model for my college project.


text:
Vary the length of square waveform

Here in figure,  we can see two waveforms.
Below one is waveform of raw RPM signal. I want to find square waveform which based on that LOW INTERVAL of RPM signal and length must vary according our requirement. So for that purpose, I just made inverter circuit using 74HC14 and Low pass filter(for removing noise).
As a result of that circuit, I got Upper one waveform means square wave signal. Now, you can see it has also one spike beside square wave(I don't want that). And I can't vary length because inverter circuit gives only perfect inverting signal.
Is it possible to make square wave like this and also vary the length of that square wave with help of Arduino?
Here, I want to use Arduino because I have to vary the length of square wave with help of programming.  For example, if I want 10ms square wave then just enter value 10 in programming then generate 10ms square waveform. Rising edge must be same. And right now, I have no clue or idea how to do this.
If possible then please give me some suggestion how to do this.

You should probably try to filter out the spike before it gets into the Schmitt triggers.

@EdgarBonet I already tried out Low pass filter and then output of that going into 74HC14.

needs by bypass caps. tiny ones; less than 100 puff.

The most steightforward decision is to use this spike to trigger interrupt in Arduino. The interrupt procedure starts one of the counters and sets 1 at one of the pins. After N milliseconds by counter or by inner timer the Arduino outputs 0 to the same pin, so you will have needed length of the positive pulse. This will work while pulse length will be less then time between successive spikes. Do not forget to make standard spike amplitude enough to start interrupt, but not too big not to damage Arduino. Of course you can work without interrupts, just testing the input in main cycle, but it will be less presise. You will need a decision, how to conveniently control the pulse length by some tool. It can be infrared pult or some other tool and you must see the set time value, so you will need to use some indicator. May be LCD  1602 keypad shield will be enough for this.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Regarding PGA bypass in ADS1262
I want to bypass the PGA to change the input signal range from +/-2.5 to 0/5 V range.
I have taken the reference of example given in this library.
I have interfaced protocentral-ads1262-32-bit-precision-adc-breakout-board with Arduino Ethernet Board.
In the example, I have put #define VREF 5 but it shows the double the input voltage in serial window and when I put VREF 2.5, it shows regular input voltage.
For input voltage range 0 to 5V (single signal), I need to bypass the PGA but I dont know how to do it.
When the input signal is more than 2.5V then it always give the 2.5V only. If the input signal is, say 4.86V then it should give 4.86V but its gives 2.5V.

You don't want to bypass the PGA.
By default the chip uses the 2.5v internal reference. You need to switch that to using AVDD/AVSS as the voltage reference. If the library doesn't allow that you will have to do it manually referring to the datasheet.

I want to bypass the PGA to change the input signal range from +/-2.5 to 0/5 V range.

Look at the register map. it should allow you to by pass the pga.

In the example, I have put #define VREF 5 but it shows the double the input voltage in serial window and when I put VREF 2.5, it shows regular input voltage.

Simple solution: divide the library's output by 2.
Right solution: the library likely doesn't support bipolar output. So re-write  your own.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Arduino Uno with PWM driven motor and 433 MHz wireless receiver don't work
I am fairly new to the Arduino topic and I'm trying to get a few things to work together.
At the moment I'm using an Arduino Uno board, but planning to use an Arduino Nano for this.
First I tried setting up a DC motor that can be controlled via PWM, which works perfectly when used standalone. I can start/stop the motor and change speed depending on the value I send to the PWM pin.
Next, I tried to use an RF-5V wireless receiver to work with a remote control from remote switched power outlets. For this one I followed the instructions on how to build a 433 MHz sniffer. This all by itself works as well. I can receive different codes depending on which keys on the remote I am pressing.
Now the fun part started: I wanted to integrate both projects into one, so I could use the remote to start/stop the motor. So I came up with the following circuit:

(The sketch is updated so it shows the right pins matching the code)
And the following code (which is partly from the instructions mentioned above):
#include <RCSwitch.h>

// init 433MHz lib
RCSwitch mySwitch = RCSwitch();
unsigned long lOldValue=0;  // to check for consecutive reads on 433MHz
int motorPin = 5; // PWM-Pin to use for motor

void setup() {
  pinMode(motorPin, OUTPUT);
  Serial.begin(9600);
  // set-up rf receiver
  mySwitch.enableReceive(0);
  // 433MHz Receiver on interrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    int value = mySwitch.getReceivedValue();
    // only react, if at least two times same value received
    if (value == lOldValue) {
      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() );
        // One of the keys on the remote
        if (value == 274393) {
          Serial.println("got start code, starting motor");
          analogWrite(motorPin, 100); // start the motor
        }
        // another key on the remote
        if (value == 270384) {
          Serial.println("got stop code, stopping motor");
          analogWrite(motorPin, 0); // stop the motor
        }
      }
    }
    lOldValue = value;
    mySwitch.resetAvailable();
  }
}

When I run the code and click on the remote, I get different values shown depending on the key I press. So the wireless receiver works as expected.
When I receive the right value for starting the motor, the motor really begins to turn, so this works as well.
And here the fun part starts:
As soon as I use the analogWrite function to send data to the PWM port the motor is connected to, the wireless receiver stops working (or at least I do not get any more values when pressing a key on the remote).
I found a few similar posts/problem descriptions on the net which said to try the following:

Use another pin for PWM (due to possible interrupt conflicts). I tried that as well, same behaviour.
Use external power supply instead of USB-Cable, which helped somebody resolve this issue. Not here. Does not work either.

So the question is:
Does anybody know how to combine those two things together so I can use the wireless receiver to get commands and switch on/off the motor with it on an Arduino Uno?
And would this solution probably work with an Arduino Nano as well?
Update:
I changed the motor against a LED, same behaviour. So its not related to the motor itself.
I found out that when i use some timers to set the motor pwm to 0 with the analogWrite function, that the wireless receiver starts working again.
So it really looks like there is no way to use PWM and the wireless receiver together.
I also changed the pin for the receiver from 2 to 3 (and of course changed the code to use the right pin) and used other PWM pins for using with the motor. But still to no success.
Does anyone have an idea on how to bring both the wireless receiver and PWM driven things to work together? Might this be an hardware issue (due to interrupts) or a library issue for the rcswitch?

Most likely it is interference from the motor. You can add some EMI dampening capacitors (small, say 10nF) between the motor's pins and the metal body of the motor.

Double check pin assignments. Your circuit does not match sketch pin assignments.

@MikaelPatel Yes, you are right. I did not pay the neccessary attention when drawing the circuit. But even with the cables attached to the right pins as mentioned in the sketch, it did not work.

I give you +1 for a well formulated question and your debugging skills.

You are asking too much from the Arduino if you expect it to drive a motor with only the on-board 5V regulator AND the radio. Eliminate at least the motor connection to the 5V and use a MOSFET to drive the motor with a stand-alone power source like an alkaline battery pack of at least 6V - You need current to drive a motor and the UNO is limited to 500mA. Once you PWM the MOSFET, it should handle the motor with ease. A IR510 is good for this use. You will need a 10K pull-down resistor to the Gate Pin to keep it LOW when no signal is present.  This should get you going in the right direction. 0.01 ceramic filter capacitors to the - and + leads to ground around the motor is also helpful. Look up on-line how others do this.

That's for sure.  The radio itself requires at least 100 mA.


text:
Detecting I2C transfer with LED
I am going to do a project with a lot of Arduinos connected via I2C, where like of them can became master for a moment to announce an event. So I would like to see how much is the bus used. As there will be a central point, I thought about putting a LED there, from +5V to clock line, so it would shine when the transfer occurs and be black when the line is free. And so I would be able to guess the utilisation level of the bus. (The clock is effectively PWM going to zero often while in transfer, while being plain +5V when no transfer is active).
Of course direct connection is not the best idea, as it would disrupt the pull-ups and mess with the protocol (as it would drain a lot of power to clock each time it went down), there should be some separator/amplifier.
The question is - does anybody know a simple setting, where the LED would be driven by a small current to zero (that is inverting amplifier as simple as possible with high enough input impedance to not disturb I2C communication)?
Thanks for all hints :)

Just get one of the modern high power blue leds. Those will light up with as little as 0.1mA, perhaps even lower. Calculate the appropriate high value resistor to get this very low current.

Thank you, I tried it and it worked even with clasical red LED (as I have no blue at hand just now) and 2K resistor (so approx 1mA), but it was bad visible, especially for short transmitions. Still it worked reliably with 30 cm long wires (and worked even with just 330R resistor, which was easy to spot - but I would not like to test it under noise on robot), so I finally set it with bipolar PNP with emitor on Vcc, base over 2K to clock and colector over 330R + red LED to GND. Shines nice too, drains just about 2mA from I2C. (If you want, make it answer and I will accept it)

It can be done with two N-channel MOSFETs or one P-channel MOSFET (depending on what you have locally / can get / is in your bits box):

simulate this circuit – Schematic created using CircuitLab
In the left schematic the first MOSFET acts like a NOT gate, and the second is a simple low-side switch. The pair together make an active-low low-side switch.
The right hand schematic, which is somewhat simpler, uses a single P channel MOSFET as a high-side switch. This is normally driven with an N-channel MOSFET to invert the logic, since it is naturally active-low. You don't want that, so you can just connect direct to the gate.
Note that all MOSFETs are "logic level" with a threshold voltage below 3V (or -3V in the case of the P-channel).

Thanks you too. I had not MOSFET at hands, so I used bipolar PNP and 2K resistor to its base (as 4k did not open it fully) in the second schema (inverted logic). Works like a charm :)


text:
Arduino Nano 3.0 dimensions without the pins
I think the title of this question is quite clear. I am looking for the exact dimensions of the Arduino Nano 3.0, with the electronic components and the USB mini port on the IC (the Atmega328 one), without the external pins.

It'll be 1.6mm plus the thickness of the thickest component - which you can find in the datasheet for that component - plus a tiny bit for solder float.

Mini-USB-B is around 4mm tall.
Most PCBs are around 1.6mm.
The FT232RL on the bottom is 2mm (max) according to the datasheet. (voltage regulator is 1.8mm). (I'm sure about this tantalum capacitors)
So that's something around 7.6mm total height

What about the components on the bottom?

@user29519 sorry about that. I always mix up those boards. I thought the nano used the ATMega32u4.

I have a nano so let me get a ruler, ok. The usb port takes up most of the room so 4mms, the board itself is 1mm and a tiny chip adds 2mms as well. So 7mms! Hope this helped!


text:
Touch-screen, 3 H-bridges and 3 sensors on Arduino Nano 3.0
I am using an Arduino Nanao andI am wondering if there is a way to connect an 2 inch touchscreen, 3 H-bridges (it takes 3digital pins to power one of them and 1 additional to control the voltage) and have 3 analog pins left for sensors?

I think, that there is at least one I2C touchscreen (eg. https://www.adafruit.com/product/1947 )(I2C need 2 pins - SCL(A5)+DATA(A4) - given by HW) and if you need 3x3=9 digital pins for setting direction, you can use also I2C multiplexer on the same 2 pins (http://playground.arduino.cc/Code/I2CPortExpander8574). So you are left with need for 3 PWM pins from (D3,D5,D6,D9,D10,D11).
So there is a way for sure.


text:
Unspecified running error while programing WeMos D1 in wireless mode
I've tried to program WeMos D1 directly by wireless connection. I've test my D1 so it had no problem. after setting SSID and Password I've programed it for wireless using. It ran well. as I want to programing thought wireless there was an Unspecified error for running python.exe !
java.io.IOException: Cannot run program "python.exe": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at processing.app.helpers.ProcessUtils.exec(ProcessUtils.java:26)
    at cc.arduino.packages.Uploader.executeUploadCommand(Uploader.java:129)
    at cc.arduino.packages.uploaders.GenericNetworkUploader.uploadUsingPreferences(GenericNetworkUploader.java:99)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
    at processing.app.SketchController.upload(SketchController.java:709)
    at processing.app.SketchController.exportApplet(SketchController.java:682)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2190)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
    at java.lang.ProcessImpl.start(ProcessImpl.java:137)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 8 more
An error occurred while uploading the sketch

I've python on my PC  and it works. to clear my problem I've attached  the following gif

any help would be appreciated.

You might have Python installed, but can you run it?
Open a command window on you PC.  (Windows button R then CMD)
Then in that type python.
If python starts up then it should be working, but I suspect you will get an error saying:
'python' is not recognized as an internal or external command, operable program or batch file.
To fix this you need to edit you path and restart the IDE.  (How you edit you path depends on your version of Windows so you would be best searching for edit environment path and your version of windows and that should come back with an answer quickly.
Of course if its Linux/mac then it could still be the same issue.


text:
avrdude: stk500_recv(): programmer is not responding after serial
I have searched but have not found any solution to my problem so I am asking it here.  I make a program in python that makes serial communication with the Arduino. I started to upload my Arduino code but I forgot that my python program was open in the terminal (I use Ubuntu). So, I think the Arduino code and python output went to the same port which the Arduino is on. After that I couldn't upload any code into the Arduino.
Every time it prints the following error:

avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

and then makes more 9 attempts.
Any help?

Likely all you really need to do is exit/kill every process trying to use the Arduino, un-plug it from the USB port, and plug it back in.
This is in part because Linux doesn't really block multiple programs from trying to use the serial device at the same time, unless they take particularly efforts to claim it exclusively, but the attempted sharing may result in serial traffic that doesn't make any sense.
Another issue can be that if a still-running program was using a device that vanished, when that device is reconnected it will not be assigned to the in-use port number, but to a free one.


text:
Arduino Uno as keyboard
I am trying to make Arduino Uno to act as a keyboard. I have successfully flashed the USB-HID firmware in it using this link also and programmed it like this.
uint8_t buf[8] = {
 0
};

int inpin1 = 7;
int inpin2 = 8;
int val1 = 0;
int val2 = 0;

void setup() {
  Serial.begin(9600);
  delay(200);
  pinMode(inpin1, INPUT);
  pinMode(inpin2, INPUT);
}

void loop() {
  val1 = digitalRead(inpin1);
  if(val1 != HIGH) {
   buf[2] = 80; // Left Arrow
   Serial.write(buf, 8);
   releaseKey();
  }
  val2 = digitalRead(inpin2);
  if(val2 != HIGH) {
    buf[2] = 79; // Right Arrow
    Serial.write(buf, 8);
    releaseKey();
  }
}

void releaseKey() {
  buf[0] = 0;
  buf[2] = 0;
  Serial.write(buf, 8);
}

The above code works fine but the problem is that when I tried to play a game, which uses right arrow and left arrow, and to control a car I was using the push button, which I connected to Arduino as left and right arrow keys. But suppose I want to turn a car. I have to press the key and then release the key to move it a very little to the right or left. So, if I want to turn the car either left or right, I have to press and release so many times that it becomes impossible to play the game. Do you anyone know how to resolve this problem?

I believe this library that goes along with it. That would be the way to go instead of sending byte array through serial. This way you have the functions press and release, that you need.

+1 for impressive.  I know the RpiZero has been used for this, but this is the first time I've seen a write-up of an Arduino doing it.  Coolness.

You should just not call the releaseKey function, until the button is released.
int oldVal1 = 0;
int oldVal2 = 0;

void loop()
{
    val1 = digitalRead(inpin1);
    if( val1!=oldVal1 )
    {
        oldVal1 = val1;
        if(val1 != HIGH)
        {
            buf[2] = 80; // Left Arrow
            Serial.write(buf, 8);
        }
        else
        {
            releaseKey();
        }
    }

    val2 = digitalRead(inpin2);
    if( val2!=oldVal2 )
    {
        oldVal2 = val2;
        if(val2 != HIGH)
        {
            buf[2] = 79; // Right Arrow
            Serial.write(buf, 8);
        }
        else
        {
            releaseKey();
        }
    }

}

Right sort of idea, but I don't this is going to work since there are two buttons and releaseKey() doesn't seem like it will distinguish.  So probably the un-pushed button will immediately undo the pushed one, preventing any improvement.  I'm not sure if the problem can be solved with shared "had anything been pushed?" tracking or if the key states will need to be tracked and released independently.

Perhaps things might be simplified by writing the code so that if one button is pushed the other gets ignored, but the code will need to be sure to release any pushed  button before it indicates the push of another.

Just asking, why not using "while-loop" instead?

@ChrisStratton good point. Changed it so it only send press or release when the button state has changed. That doesn't handle pressing multiple buttons at the same time, but keeps it simple enough to understand.

@dhimaspw A while loop would block any other code. So that will work for this simple sketch, but will cause issues if you ever want to add additional code. Like for example pressing multiple buttons at the same time.


text:
Arduino Starter Kit - firmly wiring longer parts
I am getting started with project 01 on the Arduino starter kit. I'm facing an issue when wiring parts with long ends e.g. led & resistor. To make the simple circuit with led, resistor & switch work, I have to hold down the resistor & led, and then press the button. The parts don't connect well to the wires underneath the breadboard.
I want ask if someone could suggest how to better deal with such parts. On searching, I found people cut their parts short, but are there other approaches ?
Thanks.

In the good old days, 1/4 watt resistors had nice firm leads that may have been actually steel with plating (you could pick them up with a magnet!) and worked pretty well on halfway decent breadboards.  It seems today though that it's hard to buy resistors with anything but very thin soft leads, and meanwhile there are a lot of rather bad breadboards on the market.  Mainstream suppliers increasingly don't even carry "everyday" through hole resistors.

You could try folding the ends over (effectively doubling the width) if the wires are thin.

Cutting them short is proven solution, but there is sometimes still problem with legs too thin to fit good.
Other, even more reliable, is to solder them to pinheader https://commons.wikimedia.org/wiki/File:16_Pin_Header.jpg (just break away 2 or 3 pins depending on how many legs you need). Works even for SMD resistors and diodes https://divnoblog.files.wordpress.com/2015/10/005-odpor_1.jpg
Also you can use small piece of universal stripboard https://en.wikipedia.org/wiki/Stripboard / perfboard https://en.wikipedia.org/wiki/Perfboard, to solder anything on that and solder the pinheader under it. Works perfectly for switches etc.
(of course you can buy "modules" from any suplier, where is the part, maybe accompanied by one or two resistors or such, but the price is higher, than is you do it manually at home and there is not such wide range, as is in normal analog/digital parts, which you can solder to fit your needs)
The problem with https://en.wikipedia.org/wiki/Breadboard is, that usually the holes are good just for the pinheader-sized legs (a lot of IC have the right dimensions too), while nearly any pasive/simple parts are much thinner and do not fit reliably. But for some fast playing with and non-critical application it is usually usable enough.


text:
DHT sensors with RGB LED
I have a DHT11 that outputs temperature and humidity values to my serial monitor. I'm trying to serial the COLOUR of the light based on the temperature conditions. So far I only get 1's and 0's. How can I change these integer values to output string say RED, GREEN or BLUE?
Code
#include <dht.h>

dht DHT;
#define DHT11_PIN A5
int redPin = 10; // Red LED,  connected to digital pin 10
int grnPin = 9; // Green LED, connected to digital pin 9
int bluPin = 8;  // Blue LED, connected to digital pin 8

void setup() {
  Serial.begin(9600);
  // Sets the pins as output for RGB LED
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  int t = DHT.temperature;
  int h = DHT.humidity;
  Serial.print("Temperature = ");
  Serial.print(t);
  Serial.print( "," );
  Serial.print("Humidity = ");
  Serial.print(h);
  Serial.print("\n");
  delay(60000);
  if((DHT.temperature < 26) && (DHT.temperature >= 23.2)) {
    // Writing the LED colour pins HIGH or LOW to set colours
    digitalWrite(redPin, HIGH); // yellow
    digitalWrite(grnPin, HIGH);
    delay(100);
    digitalWrite(bluPin, LOW);
  }
  if((DHT.temperature < 23) && (DHT.temperature > 20.2)) {
    digitalWrite(grnPin, HIGH); // green
    delay(100);
    digitalWrite(redPin, LOW);
    digitalWrite(bluPin, LOW);
  }
  if((DHT.temperature < 20) && (DHT.temperature > 17.2)) {
    digitalWrite(grnPin, HIGH); // aqua
    digitalWrite(bluPin, HIGH);
    delay(100);
    digitalWrite(redPin, LOW);
  }
  if(DHT.temperature <= 17) {
    digitalWrite(bluPin, HIGH); // blue
    delay(100);
    digitalWrite(grnPin, LOW);
    digitalWrite(redPin, LOW);
  }
  delay(1000);
  // Sensor shouldn't be read too frequently so delay of 1s
}

I will be grateful if I can get some help. Thanks!

Add Serial.print() in each block that sets the pins to new values.

So far I only get 1's and 0's

Before moving into the LED parts, you have to make sure that your system can correctly read the DHT sensor. There are debugging example from arduino-info.wikispaces.com

How can I change these integer values to output string say RED, GREEN or BLUE?

You can do it by simple if-else statement. This would be better than your original code, because there are multiple if's without any else which is (although not so significant) less optimal.
So, if put together, you can try:
void loop()
{
  int t,h,chk = DHT.read11(DHT11_PIN);

  switch (chk)
  {
    case DHTLIB_OK:
                Serial.print("OK,\t");
                break;
    case DHTLIB_ERROR_CHECKSUM:
                Serial.print("Checksum error,\t");
                break;
    case DHTLIB_ERROR_TIMEOUT:
                Serial.print("Time out error,\t");
                break;
    case DHTLIB_ERROR_CONNECT:
        Serial.print("Connect error,\t");
        break;
    case DHTLIB_ERROR_ACK_L:
        Serial.print("Ack Low error,\t");
        break;
    case DHTLIB_ERROR_ACK_H:
        Serial.print("Ack High error,\t");
        break;
    default:
                Serial.print("Unknown error,\t");
                break;
  }
  //moving on into next parts only if you get "OK" from serial reply, which means you successfully read the DHT11
  t = DHT.temperature;
  h = DHT.humidity;
  Serial.print(DHT.humidity, 1);
  Serial.print(",\t");
  Serial.println(DHT.temperature, 1);

  //----end of sensor reading and debugging

  if (t<=17)
  { //blue
   digitalWrite(bluPin, HIGH);
   digitalWrite(grnPin, LOW);
   digitalWrite(redPin, LOW);
   delay(100);
  } else
      if (t<20)
      {
       digitalWrite(grnPin, HIGH);  // aqua
       digitalWrite(bluPin, HIGH);
       digitalWrite(redPin, LOW);
       delay(100);
      } else
      if (t<23)
      {
        //....
      }
      //....
      //and goes on

 delay(1000);
}

And yes, as @Matt suggest, it would be better if you use PWM to control the RGB led which will give you (mathematically) 255*255*255 colour possibilities instead of 8 combinations from digitalWrite(). For example:
//....
//....
  if (t<20)
  { //aqua
   new_t = map(t,DHT11_min_temperature_reading,DHT11_max_temperature_reading,0,255);
   //you can do self research about DHT11 maximum and minimum temperature reading
   //parameters 0 and 255 is the minimum value of PWM(0) and the maximum value(255)
   AnalogWrite(bluPWMPin, new_t);
   AnalogWrite(grnPWMPin, 255-new_t);
   AnalogWrite(redPWMPin, 0);
   delay(100);
  }
//....
//....

Hope it helps :D

You need to use analogWrite(). You use this with a digital pin and it does Pulse Width Modulation (PWM) which will give you are larger range of colours. Have a look at the Reference page for the function.
You might even be able to use the map function (something like that) to 'map' the temperature to the colour values without all the if statements.

The PWM pins have a ~ next to them on the PCB.

Thanks for your response. Do you have an idea of how I can implement the map function?

Erm...  not a clue, I've never used it, but I have seen it on here.


text:
Timer3 Arduino maximum period
At the moment I'm trying to learn microcontrollers with Arduino, and have a problem with the timer.
Arduino works at 16MHz clock, and the best prescaler is 1024, which means the timer increments the value every 64 us. Timer 3 is a 16 bit timer, which gives us a maximum time of 64*65535= 4194240, ca. 4s
But what if I want to do a job every 8 seconds? Any idea?
Here's my code:
TCCR3A = 0;
TCCR3B = 0;
TCCR3B |= (1<<WGM32); //CTC
TCCR3B |= (1 << CS32);
TCCR3B |= (1 << CS30);// 1024 prescaler
TIMSK3 |= (1<<OCIE3A);
sei();

Schedule it every second time the interrupt fires.

You can't - not directly. Instead you do a job at a higher frequency which just counts. When it has counted enough you do your other job.
For instance, you might trigger your interrupt once a second. That interrupt just adds 1 to a count and returns. Unless that count just hit 8, when you reset the count to 0 and run your 8 second routine.

+1 This is indeed generally how it is done.  Though if the system doesn't need to do much else or more frequently, you can ultimately save power by activating the divider on the MCU clock itself (and/or put the MCU to sleep in between events). However those are advanced topics and introduce various complications that may not be warranted for the current goal.

You know that the inbuilt function millis() would let you achieve that goal?
For example:
unsigned long startTime;

void loop ()
  {
  if (millis () - startTime >= 8000)
    {
    startTime = millis ();  // reset start time to now
    // do something that needs doing every 8 seconds
    }

  // do other stuff

  }  // end of loop

If the 5% error (~4.2 sec vs. 4.0 sec) isn't a problem, 2 counter overflows will give 8 seconds with the same 5% error, or ~8.4 sec. If you need higher accuracy, either start the timer with a slightly smaller initial counter value, (62500 * 64 = 4000000 uSec), choose a divider value that naturally overflow at convenient sub-multiples of the intervals your program will need, and again count N overlows of the timer before your code responds.


text:
Understanding SevSeg
I need to write a library for a display I created with eight segments. So, I decided to try to use SevSeg (https://github.com/DeanIsMe/SevSeg) as a starting off point. It can't be that different, right?
Well, I think I have hit a roadblock that indicates I must basically do everything from scratch. Here is how the information on what segments correspond to letters are stored in SevSeg:
 // The codes below indicate which segments must be
//illuminated to display each number.

static const byte digitCodeMap[] = {
  //     GFEDCBA  Segments      7-segment map:
  B00111111, // 0   "0"          AAA
  B00000110, // 1   "1"         F   B
  B01011011, // 2   "2"         F   B
  B01001111, // 3   "3"          GGG
  B01100110, // 4   "4"         E   C
  B01101101, // 5   "5"         E   C
  B01111101, // 6   "6"          DDD
  B00000111, // 7   "7"
  B01111111, // 8   "8"
  B01101111, // 9   "9"
  B01110111, // 65  'A'
  B01111100, // 66  'b'
  B00111001, // 67  'C'
  B01011110, // 68  'd'
  B01111001, // 69  'E'
  B01110001, // 70  'F'
  B00111101, // 71  'G'
  B01110110, // 72  'H'
  B00000110, // 73  'I'
  B00001110, // 74  'J'
  B01110110, // 75  'K'  Same as 'H'
  B00111000, // 76  'L'
  B00000000, // 77  'M'  NO DISPLAY
  B01010100, // 78  'n'
  B00111111, // 79  'O'
  B01110011, // 80  'P'
  B01100111, // 81  'q'
  B01010000, // 82  'r'
  B01101101, // 83  'S'
  B01111000, // 84  't'
  B00111110, // 85  'U'
  B00111110, // 86  'V'  Same as 'U'
  B00000000, // 87  'W'  NO DISPLAY
  B01110110, // 88  'X'  Same as 'H'
  B01101110, // 89  'y'
  B01011011, // 90  'Z'  Same as '2'
  B00000000, // 32  ' '  BLANK
  B01000000, // 45  '-'  DASH
};

As you can see this is a one dimensional array of 8-byte binaries that encode the segment. I don't understand the purpose of the B0 at the beginning of each byte. Could I use the 0 column to encode my eighth segment?
Am I right to assume this will change everything about the code and maybe I should start from scratch with a 2-D array?
This is roughly what I want:
//  ABCDEFGH  Segments      8-segment map:
  11000011, // 0   "0"       A BBBBB H
  10000000, // 1   "1"       A C   D H
  01011010, // 2   "2"       A C   D H
  11101010, // 3   "3"       A  C D  H
  00110101, // 4   "4"       A  E F  H
  01011010, // 5   "5"       A E   F H
  11101110, // 6   "6"       A E   F H
  01011000, // 7   "7"       A GGGGG H
  01111110, // 8   "8"
  01100101, // 9   "9"
  11111101, // 10  "A"
  10001110, // 11  "b"
  11000010, // 12  "C"
  00001111, // 13  "d"

What data type should I use for the array? Would byte work since I'm not using the B0?
Thanks.

I don't understand the purpose of the B0 at the beginning of each byte.

That's just Arduino's rather weird way of doing binary constants. For example, in the file binary.h are lines and lines of stuff like this:
#define B1011 11
#define B01011 11
#define B001011 11
#define B0001011 11
#define B00001011 11
#define B1100 12
#define B01100 12
#define B001100 12
#define B0001100 12
#define B00001100 12

A better way is to use standard C++ constants, eg.
0b00001100

instead of:
B00001100

Could I use the 0 column to encode my eighth segment?

Yes, they are just bytes, so you can use all 8 bits.


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

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


text:
Why does static member std::map reset ESP8266 when outside the .ino file?
Here's an example of a class which crashes the ESP8266-03 causing it to reset:
Test.hpp file:
#include <map>

class Test {
public:
    int data() const;

    Test(int x);
    ~Test();
protected:
    int _data;

    static std::map<int, Test const *>thing;

    static void _Reserve(Test const * const t);
};

Test.cpp file:
std::map<int, Test const *> Test::thing;

int Test::data() const
{
    return this->_data;
}

void Test::_Reserve(Test const * const t) {
    Test::thing[t->data()] = t; // Works fine if this line is removed.
}

Test::Test(int x): _data(x)
{
    Test::_Reserve(this);
}

Test::~Test() {};

Project.ino:
#include "ESP8266WiFi.h"
#include "Test.hpp"

Test test(2);

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

void loop() {
    Serial.print("Timer: ");
    Serial.println(millis());
    delay(1000);
}

The following does NOT crash the ESP8266-03 and prints the time as it should:
#include "ESP8266WiFi.h"
#include <map>

class Test {
public:
    int data() const
    {
        return this->_data;
    }

    Test(int x): _data(x)
    {
        Test::_Reserve(this);
    }
    ~Test() {};
protected:
    int _data;

    static std::map<int, Test const *>thing;

    static bool _Reserve(Test const * const t) {
        Test::thing[t->data()] = t;
    }
};

std::map<int, Test const *> Test::thing;

Test test(2);

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

void loop() {
    Serial.print("Timer: ");
    Serial.println(millis());
    delay(1000);
}

When the first version is uploaded to the board, I get the following in the serial monitor:
 ets Jan  8 2013,rst cause:1, boot mode:(1,7)

 ets Jan  8 2013,rst cause:4, boot mode:(1,7)

wdt reset

When I reset it and boot it regularly, no upload mode, the following repeats every ~1 second:
 ets Jan  8 2013,rst cause:1, boot mode:(3,7)

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

Does accessing a static POD variable cause the same issue?

@Matt I believe I haven't tried that, but will check later on today. It's a bit strange since removing that line with a comment works fine. I can even add the same line to another method in the class (such as a new setData method, in that example up there) and it works properly... If I make the variable public, I can access it properly as well from outside the class. It probably has something to do with the constructor.

Why does static member std::map reset ESP8266 when outside the .ino file?

What happens if the Test() constructor is run before the map constructor? This is the problem: you are assuming order of execution.
Use a Singleton pattern or init() member function to force the ordering that is required.
Cheers!

Like you said, it was an initialization issue. Turns out the Test instance in the first example is considered static, making it run before std::map is initialized since it's static code is in another translation unit (another file),  but I think this comment better explains the reason for the problem: http://stackoverflow.com/a/26996015/3342154


text:
why leonardo bootloader is bigger than UNO?
Apparently leonardo and UNO are very similar boards.
However, despite that both have the same flash memory size, Leonardo bootloader is considerably bigger than UNO bootloader (4KB vs 0.5KB).
what would be the reason? it is there any way to use smaller bootloader in leonardo?
Uno specs: https://www.arduino.cc/en/Main/ArduinoBoardUno
Leonardo specs: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo
Thanks!

Apparently leonardo and UNO are very similar boards.

No, they are very, very different.
The Uno uses an external USB-UART bridge. This means that the bootloader code only has to read from the UART in order to program the device.
The Leonardo has USB support built into the MCU. This means that the bootloader must contain an entire USB Device stack in order to process the USB packets and then pass the payload to the programming routines.


text:
Find the time between HIGH state & LOW state of push button(switch)
I want to find the timing between HIGH state and LOW state of push button. For that, I made a program. You can see my program below. In my program, I made logic like that when switch is pressed then one variable "currentMillis" store the value of millis() and it store value until button pressed. But whenever I pressed button again then it also add previous value. For example, if button pressed for first time then suppose we got 200ms, now suppose if button pressed second time then we got 500ms and if button pressed third time then we got 1000ms. That mean every time value added. No doubt I made a logic which seem to be perfect but I can't figure out what is problem. Please give me some suggestions.
const int  buttonPin = 2;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
unsigned long finalMillis = 0;

int buttonPushCounter = 0;

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

   pinMode(buttonPin, INPUT);
   digitalWrite(buttonPin, HIGH);
}

void loop()
{
  if (digitalRead(buttonPin) == LOW)
  {
    buttonPushCounter++;
    Serial.println("on");
    Serial.print("number of button pushes:  ");
    Serial.println(buttonPushCounter);

    while(digitalRead(buttonPin) == LOW)
    {
      currentMillis = millis();
    }

    finalMillis = currentMillis - previousMillis;
    Serial.println(finalMillis);

    previousMillis = finalMillis;
    //finalMillis = 0;
  }
}

Here, it is my serial monitor output.
on
number of button pushes:  1
0
on
number of button pushes:  2
775
on
number of button pushes:  3
873
on
number of button pushes:  4
1425
on
number of button pushes:  5
1496
on
number of button pushes:  6
2073
on
number of button pushes:  7
2010
on
number of button pushes:  8
2643
on
number of button pushes:  9
3052
on
number of button pushes:  10
3195
on
number of button pushes:  11
3396
on
number of button pushes:  12
3575
on
number of button pushes:  13
3737

TL;DR make sure you keep switch-bounce in mind.

While the previously given answers should work for you, they share a
couple of problems with your original code:

they do not debounce the button
they block while waiting for the button to be released

Blocking the program is not a big deal if you do not have to do anything
else. However, chances are you are showing us only a fraction of what
will ultimately be a larger program. In this case, doing a busy wait
(like while (digitalRead(buttonPin) == LOW) ;) will block the whole
program, not only this particular feature. Then, I suggest you get
immediately in the habit of writing non blocking code:

when the button is pressed, record that fact and the current time
when the button is released, report to the user

The important notion is that you never wait for anything. Instead, you
check whether something has to be done right now and, if so, you do
it.
Here is a non-blocking version of your program, with some debounce
added:
const uint8_t button_pin = 2;

void setup()
{
    pinMode(button_pin, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop()
{
    static int last_button_state = HIGH;
    static unsigned int push_count;
    static unsigned long last_press_time;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if (last_button_state == HIGH && button_state == LOW) {
        push_count++;
        last_press_time = now;
    }

    // Report when the button is released.
    if (last_button_state == LOW && button_state == HIGH) {
        unsigned long push_duration = now - last_press_time;
        if (push_duration < 10) {  // discard bounce
            push_count--;
        }
        else {
            Serial.print(F("pushes: "));
            Serial.print(push_count);
            Serial.print(F(", duration: "));
            Serial.print(push_duration);
            Serial.println(F(" ms"));
        }
    }

    last_button_state = button_state;
}

Thank you for your suggestion. It's works great. Yes, you're right. Previous answers gives me result which I expected but sometimes it's provides garbage value even if I pressed button for same time.

First of all, frarugi87 is right.
Second, why not use this:
finalMillis = millis() - previousMillis;
previousMillis = millis();

Instead of what you wrote.
if (digitalRead(buttonPin) == LOW) {
    buttonPushCounter++;
    Serial.println("on");
    Serial.print("number of button pushes:  ");
    Serial.println(buttonPushCounter);
    finalMillis = millis() - previousMillis;
    previousMillis = millis();
    Serial.println(finalMillis);
    while(digitalRead(buttonPin) == LOW){}
  }

It works great.
Hope it helps.
Yoav

You wrote
previousMillis = finalMillis;

This means that you store the duration of the pulse, not the last time it was pressed.
Change it with
previousMillis = currentMillis;

and you will be able to detect the high + low time.
By the way, constantly reading the millis function is useless. You can change your code to
while(digitalRead(buttonPin) == LOW);
currentMillis = millis();

which reads only once.


text:
Is the A6 module broken?
Hi recently I've could send some messages with the A6 GSM module, which uses AT commands. To switch on the board, you need to press the power button about 4 seconds or connecting the VCC pin to the PWR pin to avoid manual switching on. In this Andreas Spiess' video (minute 2:21), he recommends reset the device to give to the board a defined state. I had not done this until the device didn't work properly with some scripts. To reset it, he advises to reset the modoule. Its RST pin needs 0.70 mA and works at low level. In addition, the Arduino can not provide that current with a single pin so he uses a N-channel MOSFET (3055) to reset the board.
In my case I used a transistor (I don't know if it's NPN or PNP) and I connected the circuit like in his video. It worked! But it given strange results to the serial monitor  (yes, I set the baud rate correctly). After reset the board it switched on automatically because it was connected the PWR pin and VCC pin. The mistery occured when I unplugged the board (even its current) and then I reconnected it again. Since that moment it doesn't work, it doesn't switch on its LED to show you that the board is working. So, can anyone explain me why the 3055 it's neccesary to reset the board? Can it be done using Ohm's Law, a digital pin and a big resistance to give to the board the 70 mA?
Thanks!

try use program "at command tester" with ftdi for example, it works in my case but the the free license only works to 30 days.

Its RST pin needs 0.70 mA and works at low level. It is 0.70 mA or 70 mA as you mention later on?

I come across this problem too..based on what you said, i think it works like this:
The parameter you are looking for is power rating.. Arduino digital pin can only tolerate some amount of current, and im guessing it is less than 70mA..if you still do that, it is possible to damage that pin..since you want a LOW level for trigger, you can connect that RST manually to GND.. GND is also 0V just like the DIGITAL LOW, but it has no internal circuitry as of digital pin - meaning that you can sink a lot more current to GND..
If you want to be on the safe side, connect a limiting resistor(use ohm law for value), and also take note on the resistor power rating..


text:
MPU6050 safe to use with glue?
My current project involves embedding an MPU6050 accelerometer into straps, one of which goes below the knee, the other above the knee.
I need to fit the sensor into the strap and currently i have 6-core multi-threaded wire soldered directly into the board. This doesn't facilitate the greatest of long term stability, as too much strain and the wires will just pull out and break.
What I am wondering is if it is OK to:

cover the wire side of the board in glue from a hot glue gun?
                 Would this have any possible conductivity issues or risk damaging the wires or board itself?
If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance. This would leave me with a really solid sensor for embedding if so!

Any answers to the above questions would be greatly appreciated and I would be extremely grateful for any alternative options as well. I would like to keep the wires soldered into the board as it is extremely tidy and makes for easier embedding than if I were to use another connector.

1) I do not see any problem here - I myself used hot glue to fix and isolate power source of robot from the copper side. It does not leak any (measurable by my tools) current, does not show any sign of detorations and works well both electrical and mechanical way. I used it only on copper side, where was risk of shortcuts and where were no heat dissipators (as it isolate also heat). But I think, that the MPU does not generate so much heat, to be worry about - body proximity and weather on summer would affect it more.
2) Hot glue is not as hot as soldering lead/tin so short contact with the MCU should not harm it. (You can shortly touch hot glue to manipulate it and not get burned, so it is not so hot). Anyway I would apply it as fast as possible and would leave it cool down before swithing it on (the working and the storing temperatures are different case). Be carefull with the wires, as the isolator can be melted, if heated by hot glue and moved at the same time. Also take in mind, that the hot glue should be little around the whole, to isolate from humidity. And that it would be complicated to solder anything after the glue is applied - so have all contacts (you may possibly need access) somehow lead out of the glue. And try the construction before applying the glue, to be extra sure, that nothing is missing and everything works.
I personally would place the MCU on some kind of PCB and solder the wires to the PCB organized the way the wires would continue to form "cable" and to have extra sure there is no force on the connection of MCU pins. Also I would fixed the whole cable to the PCB with something, so the solder itself is not under any force, as it is the most probabely place to broke there. An I would ensure, that the cable goes smoothly away from the PBC, as it would be bad, if it would be bent ower sharp edge at the place where it leave its glue support.

Brilliant response! Thanks so much! Regarding your last point, I was thinking the exact same. A small pit of pcb will provide me with somewhere to attach the MPU6050 but also to possibly have some sort of restraint on the cable, to, as you mentioned, take the force off the solder joint itself. Thanks again!

Would this have any possible conductivity issues

Nope.

or risk damaging the wires or board itself?

Nope.

If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance.

Sure.
This is known as "potting". You can get special potting compounds, but hot glue is just as good.

Thanks man! Would there be any chance that I could melt off the insulation on the wiring in doing this. Or would there be a special (maybe low temp) glue gun I should use?

The melting point of hot glue is considerably lower than the insulation of the wire.

@EoinClancy just avoid touching the wire directly with the glue gun tip, even if even this should not melt the insulation


text:
Mapping PPM Signals to Servo Values
This question is an extension of this question.
Accessing Values From Array Within a Library
The answer provided by Mark showed me how to read and print a single value from a particular array by using the index number to print to the serial console.
The second part of this question is how to get these values from the array to map to 0-180 for values that are useful to the servo.
The below code is my attempt that is not working. I used the servo sweep example from the Arduino examples which worked fine with a potentiometer but not with the ppm input. What am I doing wrong here? This won't compile. (I am using TinyServo.h library since this is for an attiny85. Works with with the pot mapping just fine.)
#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int PPM_INPUT_PIN = TinyPpmReader.width_us(3); //<------- Doesn't work

//int potpin0 = 3;    <---------          // This worked
int val0;                     // integer to store value

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

void setup()
{
  setupServos();
}

void loop()
{
  val0 = analogRead(PPM_INPUT_PIN);  <---------          //Doesnt work// reads the value of the       potentiometer (value between 0 and 1023)            // reads the value of the 2nd potentiometer (value between 0 and 1023)
  val0= map(val0, 1000, 2000, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)
       // scale it to use it with the servo (value between 0 and 180)

moveServo(PANSERVO, val0);

  delay(5);                           // waits for the servo to get there
}

For some background, the ppm library outputs like this to the serial monitor:
Ch4=1560 us
These values move from ~1000 - 2000 depending on the ppm signal input. (The input is from a RC remote control receiver)
This example below prints only channel 4 (Ch4=1560 us)from  a total of 8 channels. Now, I want to map this to the values of 0-180:
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

#define PPM_INPUT_PIN  2

void setup()
{
  Serial.begin(38400);//attiny tx - rx uno does not work at 9600 baud. Set to 38400 @ attiny 1mhz and uno serial console to 38400 baud
  TinyPpmReader.attach(PPM_INPUT_PIN); /* Attach TinyPpmReader to PPM_INPUT_PIN pin */
}

void loop()
{

Serial.print(F("Ch"));Serial.print(3);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(3));Serial.println(F(" us"));

 display results */
  delay(500);
}

What am I doing wrong?

int PPM_INPUT_PIN = TinyPpmReader.width_us(3); contain a reading result, when followed by val0 = analogRead(PPM_INPUT_PIN); it's clearly absurd.

Yes, this is where my problem is. I am trying to understand this.

int PPM_INPUT_PIN = TinyPpmReader.width_us(3);

will save the result into variable PPM_INPUT_PIN, while
val0 = analogRead(PPM_INPUT_PIN);

will save an analog reading results from PPM_INPUT_PIN channel into variable val0. This is (one of) your problem.
To map the PPM value, you can do:
#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int val0,                     // integer to store value
    mappedval0;               // integer to store mapped value;

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

const int PPM_max_value = xxxxx; //put the max value of PPM reading result
const int PPM_min_value = yyyyy; //put the min value of PPM reading result

void setup()
{
  setupServos();
}

void loop()
{
  val0 = TinyPpmReader.width_us(4);   //get PPM reading result from index 4
  mappedval0= map(val0, PPM_min_value, PPM_max_value, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)

  moveServo(PANSERVO, mappedval0);
  delay(5);                           // waits for the servo to get there
}

I think I see what I was doing.Thanks. Why is int left out before mappedval0; ? EDIT. I see the comma after val0. Just extending the variable int type to the next line.

This does in fact compile but does not work.

sorry, there's a mistake in my code. It should be moveServo(PANSERVO,mappedval0);. I've edit the answer

Yes, I saw that before compiling and replaced it with the new variable. It does compile but does nothing.

have you tried to see the result of PPM reading? And have you successfully make the servo rotate (without using PPM result as input)?

Yes, I just connected the attiny85 back to the UNO to read the ouput from ppm on pin 2. It is reading the ppm value to the serial console using this line in a serial print sketch:
Serial.print(TinyPpmReader.width_us(3));
Yes, I have tested the servo with a potentiometer to map. That worked fine also.

The PPM stream behaves as expected. It is connected to a radio controlled receiver that is taking a signal from a transmitter. When I move the stick for channel 3, the values move exactly as they should, from ~980 - 2000.

try print the mappedval0. If the result is between 0-180, then the possibility of problem is on moveServo()

Yep, That works. I am able to print the mapped values. For some reason it still doesn't work. I posted another follow-up question here: –
http://arduino.stackexchange.com/questions/33327/attiny-mapping-ppm-inputs-to-move-servo-issue


text:
Accelerometer readings on a moving object
I hope this stack is the right place for this question.
I have an accelerometer mounted securely on a swaying object -lets say a stick or pole-
this object is swinging back and forth in small angles (+- 20) with a frequency of about 2-3 times a second.
Im using the accelerometer output to calculate the tilt of the object, however since the frequency of the swings is relatively high the accelerometer readings are very high as well, and not reliable for calculating the tilt.
from my research i have seen that accelerometers work best in a stable environment.
Is there any way to improve the reliability of my accelerometer output in this setup?

Is the pole tilt the value, which you want to measure? Or could be the accelerometer placed on some base, where the pole is attached, measure the tilt of the base and have another sensor (like potentiometer) set to measure the tilt between the base and the pole?

You will probably need to model the physics of the system, establish what can be known (for example, length of the stick) and characterize the cause of the oscillation, (restoring force, stiffness, etc).  Then you need to consider the time-domain performance of the accelerometer.  From that you can probably get enough information about what is actually happening to fit your model in real time, and from that deduce the angle.  Or you could measure it externally.  At any rate, this is not an Arduino question - first it is an issue of definition, then physics, finally more general engineering.

Use a faster output accelerometer? I'm regularly using ones with 2 kHz or faster output rates.

@andrew That actually did help improve accuracy

I'm voting to close this old abandoned question as off-topic because it is about physics, not Arduino

A few things to consider.
First. An accelerometer isn't that great here. Low output frequency is one issue. Noise is another. A pot or an optical encoder would be better.
Secondly. Even if output frequency isn't an issue. You will need some sophisticated math to reconstruct the instantaneous tilt, as the measurements are essentially a sine function, but with an acceleration away from the center of the rotation.  Getting to the max tilt is easier mathematically.
Just for starters.


text:
Arduino Problem with using SoftwareSerial and SPI
I am using an external ADC (via SPI) and also a GPS receiver (Software Serial). I tried each one of them and it's working fine. Now, when I try to integrate both of them in one sketch, I can only make the ADC work, the GPS is not receiving something.
void setup()
{
  pinMode(ADS1220_CS_PIN, OUTPUT);
  pinMode(ADS1220_DRDY_PIN, INPUT);

  Serial.begin(115200);
  ss.begin(9600);

  //while(!Serial);
  //SPI.begin();                           // wake up the SPI bus.
  //SPI.setBitOrder(MSBFIRST);
  //SPI.setDataMode(SPI_MODE1);

  //ADS1220.begin();
  Wire.begin();
  delay(1000);  // Give things time to "warm-up"

  delay(1000);
  pre_time = millis(); //store current time to be used as "previous" time
}

I found out that in the setup(), when I comment out all those SPI functions, the GPS returns something. What seems to be wrong with this? thank you so much for any help

I suggest  editing your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  Also part numbers, datasheet links, and circuit diagram showing terminators etc, and photo of project and scope traces if layout matters.

@jwpat7 i'm sorry for my post, but I managed to solve it already just by changing the Rx pin from 10 to digital pin 4. Thanks for the information by the way, will do better next time

Ralph, it may often happen that if you try to provide all the info, you solve the problem :)

SoftwareSerial is very inefficient.  AltSoftSerial is best.  See this answer for a complete list of alternatives.
You may want to look at my NeoGPS library.  It is smaller, faster and more accurate than all other libraries.  The examples are structured better.  You don't show your whole sketch -_-, but the loop structure could be your real problem.  Be sure to read the Troubleshooting page for more suggestions.

thanks for the advice! I managed to solve my problem already just by changing the Rx pin from 10 to 4, will give AltSoftSerial a try and see the performance difference, thanks!

hey just wanna say thanks for introducing me to AltSofSerial, apparently I've had some issues and was guessing if the problem was the softwareserial library, and it really was since i'm transmitting data and for some moment receiving too. And it really is faster!

You're welcome! Would you mind pressing the green triangle (Accept) to indicate that this is the answer that worked for you? Thanks!

is there a way to print more than 2 decimal places in altsoftserial? i tried altSoft(float_num,4); but it doesn't work

Did you mean altSoft.print( float_num, 4 );?

digital pin 10 is slaving pin for SPI on the arduino, maybe that is why.

I managed to solve this just by changing the Rx pin to digital pin 4 from digital pin 10, I don't know what causes the problem but it did the job for me

For the Arduino to be SPI master, the SS pin (D10) must be an output. Using it as software serial input (Rx) is no good. If you had used it as the Output, Tx, you would likely have been ok.  I try to use 10 as SS for the first SPI device I have connected all the time to avoid that pitfall.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Reading updated serial data from ESP8266
I have connected my ESP8266 to my Arduino Uno on pin 2 & pin 3 as RX & TX. I adjusted the baud rates and I have no issue receiving the data from the ESP8266.
The ESP8266 gets connected as a client to a server and grabs the likes count of a Facebook page. The data on the ESP8266 serial port is updated correctly every time the ESP sends a get request to the server to get the updated likes count of a particular Facebook page.
Unfortunately I'm not receiving this updated likes count on my Arduino serial port. I'm always receiving the same likes count. I have to close the serial window and open it again to receive the new count. Or reset the Arduino itself to receive the new likes count.
So why isn't it posting the latest likes count sent from the ESP to the Arduino instantly without having to reset the Arduino? Maybe I have an issue in the void loop().
Because I display this data on an external display and I need it to be updated without me needing to reset the Arduino every time to receive the latest count.
void loop() {
  char c;
  while (esp8266.available() && c != '\n') {
    c = esp8266.read();
    response += c;
  }
  //If end of line
  if (c == '\n') {
    //Getting the likes string only
    if(likes = response.substring(response.indexOf("Likes:")+6, response.indexOf("::"))) {
      //Filtering some unneeded strings
      if((strstr(likes.c_str(), "URL")) == NULL) {
        currentLikes = atol(likes.c_str());
        Serial.print(currentLikes);
        //Printing likes count on serial port
      }
      Serial.println();
    }
  }
}

Please could you explain what you've done here: if(likes = response.substring(response.indexOf("Likes:")+6, response.indexOf("::")))

If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From Review

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Thank you everyone I had to just clear the response string every time.
I have just added response = ""; after the Serial.print(currentLikes);


text:
Arduino Leonardo clone voltage question
I'm planning my first Arduino project which involves a MPU-6050 accelerometer(3.3V) and a RGB led(5V). I've found this Arduino Clone but i'm not sure if it has 3.3V and 5V outputs that I can use. The pins do exist on the original Leonardo board but i'm not sure if the clone contains them as well.

That has a 5V pin (Vcc) but no 3.3V. Also the 5V pin can't provide more than a few hundred mA.
Better specifications are here: https://www.sparkfun.com/products/12640

I see, thanks a lot. If I find a 5V accelerometer would I be able to connect it + the led to the same 5V pin?

Yep. Note that a 5v accelerometer will probably be a 3.3v one with built in 3.3v regulator, so you need to take the same precautions as a 3.3v one.

What kind of procautions do you mean? Could you maybe give me term to google to send me down the right path?

Logic level shifting. Interfacing a 5v Arduino to a 3.3v device. If the accelerometer is I2C include that in your search too.


text:
Wearable GPS Antenna
I am using the Adafruit Fona 808 to make a wearable device. One of the main features is GPS but I cannot seem to find a suitable antenna for wearables. My question is: What is a good GPS antenna for a wearable project and should it be active or passive?
Thanks

Whats wrong with the recommended antenna on the product page?

I too thought whats wrong with a normal Antenna, but the answer is the problem is the human body.
There are manufacturers that make "fabric" antennas, but these tend to be Mil-Spec so are going to cost a fortune.  (http://www.pharad.com/gps-wearable-antenna.html)
I found this site that explains what the effect of the body is, and seems to make their own antenna.  http://www.pharad.com/gps-wearable-antenna.html
I think you might be better off looking for a high gain antenna and the choice of active or passive will probably be based on the interference you get from the body.


text:
Digital Band pass filter on Arduino
I am working with sensors on Arduino and would like to filter the sensor's output to a certain band of frequencies.
I found many examples online on how to implement simple digital low-pass filters in Arduino code, but not for band pass filters.
Is it even possible to achieve this in the scope of an Arduino program?
If anyone can share some tutorial for this, that would be much appreciated.

On an Arduino I would be tempted to do it in hardware. You really need a DSP to do filtering like that.

See http://www.iowahills.com/Example%20Code/WindowedFIRFilterWebCode.txt from http://www.iowahills.com/A7ExampleCodePage.html

A band pass filter simply means that it a filter between a certain interval of frequencies thus it can be made from a high pass filter and a low pass filter
e.g. this fact is mentioned here http://www.electronics-tutorials.ws/filter/filter_4.html
as well as lots of other web pages which a search by you can find.
So yes a band pass filter can be implemented on arduino if you can implement the corresponding high pass and low pass filter too.

The link you posted leads to analog filters where i specifically asked about ones implemented within the Arduino code, im afraid it is not relevant.
if i were to somehow implement both a low pass and a high pass filter separately in an arduino program, ill just lose both my high and low frequencies as they will both get filtered out.

Its easy enough to find the defintion of a band pass filter by a simple search which you can do

for a more relevant link

Sounds like you need to use two arduino (or at least two different signal filter circuits) to make a band pass filter

you implmented a low pass filter, you merely have to implment a high pass filter then combine the two to get a band pass filter.


text:
Reading serial buffer taking newline character instead of user input
I am trying to compare whether the user input matches a user ID or not. When I read the input from serial, the program is taking the last character which is newline char '\n' and moving it into the char data value to compare against the stored user ID and I don't understand why it's taking the '\n' value instead of the actual user input.
int Gled = 7;
int Rled = 8;
int wait = 5000;
char UserID = "12345";
char data;
char incoming;

void setup() {
  Serial.begin(9600);
  pinMode(Gled,OUTPUT);
  pinMode(Rled,OUTPUT);
  Serial.println("Please Enter your username or ID:");
}

void loop() {
  if(Serial.available()>0) {
    while(1) {
      data=Serial.read(); //read user input and move to data char
      if(data !='\n')
        incoming = data; //if data doesn't equal newline data = incoming
      if (data == '\n')
        break; // newline char detected break
      if (data == -1) //continue reading all of user input
        continue;
      Serial.print(data);
      Serial.print(incoming);
    }
    Serial.println(incoming);
    if(incoming == UserID) { //if user input matches run statement
      digitalWrite(Gled, HIGH);
      Serial.println();
      Serial.println("Access Granted");
      Serial.println("Hello User Name");
      delay(wait);
      Serial.println("Login time exceeded, you are now logged out.");
      Serial.println("Reenter your UserID to log back in.");
      digitalWrite(Gled, LOW);
      Serial.end();
      Serial.begin(9600);
    } else if(incoming != UserID){
      //user input doesn't match run statement
      digitalWrite(Rled, HIGH);
      Serial.println();
      Serial.println("Access Denied");
      Serial.end();
      delay(wait);
      Serial.begin(9600);
      digitalWrite(Rled, LOW);
      Serial.println("Please Enter a Valid ID to Continue.");
    }
  }
}

Your whole data reading and user ID storage and comparison is completely wrong.

Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Some parts of this can help too: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

Thanks for those links, I read them and figured out what I was doing wrong.

if(data !='n')

This should be
if(data !='\n')

NEXT.
data=Serial.read();

only reads ONE character. You should add to a buffer, not assign a single character.

Thats my mistake for leaving that in there I had already copied the text before fixing that typo but the program still has the same issue.


text:
How can I connect H-Bridge motor driver (using four 2n222 transistors) to Arduino?
First of all I'm a noob.
I was trying to do the H-Bridge using 2N2222 controlled by an Arduino Uno.
This is the design--->

I joined A1 and A2 to form a common terminal (say A), similarly, I joined B1 and B2 to form B. Now I connected A and B to 2 pins of the arduino (say pin 9 & pin 10 respectively).
So, theoretically, when I should digitalWrite pin 9 HIGH, then current should flow via A1 and A2, i.e. left to right in the motor AND when I should digitalWrite pin 10 HIGH, then current should flow via B1 and B2, i.e. right to left in the motor.
Hence, I can control the direction of rotation of the motor.
BUT.....it wasn't working...!!!!
I need help...!!!
After much thinking I had a hunch...."Perhaps, I am not giving GROUND to the transistors". I thought about it, but was unable to figure out the way of doing it.
So, again, please help me...!!!

If Ground is the issue, connect it to the -ve of the battery. You can't just run one wire to the bridge, voltages are meaningless without a reference (commonly called Ground).

This circuit will not take advantage of your 9v supply when you only have 5v logic to drive the upper transistors, and designing a circuit that could is not really a question about Arduino.  If your goal is just to control something, look at an FET bridge like a TB6612FNG.  If you want to get into the details of designing a bridge from scratch, you are going to need to spend a lot more time understanding transistor circuits.

Make sure you have connect Arduino ground with -VE of battery. 2. If it still does not work, try to drive A1 A2 B1 B2 separately first.

Transistor needs like 0.7V from base to emitor to open. Arduino have 5V pins. So the voltage on motor can be max 4.3V to be able open A1. But if you open that, than you connect it to 9V of batery, the motor gets most voltage so there would be more then 8V on the side of motor and A1 closes, as B-E voltage is like 5-8=-3V enough to close it. You can drive the motor from 5V batery (and loss a lot of power), or you need more complicated schema of the H-bridge. I suggest reading http://scolton.blogspot.cz/p/motor-controllers.html  http://web.mit.edu/first/kart/controller_rev1.pdf to get some ideas

I am not an electronics guru yet either so others might give you a better answer, but this is one circuit I have messed with a lot because I keep trying to build robots, so I will take a shot at an answer.
Normally you need both NPN and PNP transistors for an H-bridge:

The 2N222 is NPN so you'd want to pair two of them with two equivalent PNPs such as the 2N2907.
I've see diagrams that have all NPNs but I have never gotten a circuit to work that way. There is a distinction about where the load goes, before or after the transistor, that makes you chose to use an NPN or a PNP in order to make it all flow properly.

This circuit won't work for the question's power supply, either, as the supply voltage is more than a diode drop above the logic voltage.  The maximum voltage at "Forward Input" is 5v, but the emitter of your PNP transistors is at 9v, so they will always be "on" with no way for the Arduino to turn them off.  Designing a working H-bridge is not trivial.


text:
ADS1262 and 2.2 SPI TFT (Two SPI Slave) with Arduino
I am interfacing two SPI slave module i.e. ADS1262 and 2.2 SPI TFT with the Arduino Ethernet board.
When I test each device on its own it works. Initially, I interfaced the TFT to the Arduino and it is working fine. Likewise, the example code of ADS1262 is working fine when I am running it alone.
So after successfully running the TFT alone, I then wire-up the ADS1262, add the corresponding code, however the ADS1262 doesn't seem to respond.
I think the issue may be related to the ADS1262_CS or ADS1262_START or ADS1262_DRDY pin sequence to access the ADS1262.
I have used the ProtoCentral_ads1262 library from GitHub and have used the example code.

From Comments:
We have already reserved D10 for Ethernet Controller and D4 for SD Chip select. The issue is, how to communicate both of them, one by one. I can access one of them only when code is prepare for both devices.

// Portion of the code is given here

// https://github.com/adafruit/Adafruit_ILI9341 library used for TFT

// Code start from here

for(j=initvalue;j<=finalvalue;j+=x)
{

      dacvalue=((j*5)/65535);

      writeValue(j);

      tft.fillRect(30,150,70,28,ILI9341_BLACK);

      tft.setCursor(30,150);

      tft.println(dacvalue,3); // dac value is showing on TFT

      Serial.println(dacvalue,3);

// ADS1262 is need to communicate here as per https://github.com/Protocentral/ProtoCentral_ads1262 library

// Which pins are need to control here to communicate with ADS1262???

      volatile int p,data;

      if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data ready(DRDY pin)
     {
       SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes conversion register
       Responsebyte = true ;
     }

      if(Responsebyte == true)
      {
       for(p = 0; p <5; p++)
      {
        SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + p);
      }
      Responsebyte = false;
      }

       if(SPI_RX_Buff_Count >= 5)
      {
        ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
        ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
        ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
        ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

        uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)|((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
        sads1262Count = (signed long) (uads1262Count);      // get signed value
        Serial.println("sads1262Count:");
        Serial.println(sads1262Count);
        resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
        Serial.println(resolution,15);
        volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
        volt_mV   =   volt_V*1000;                           // voltage in mV
     tft.setCursor(166,150);
     tft.println(volt_mV,3); } //not printed on TFT

In above code, ADS1262 is not activated so not giving value on serial window or TFT.
How to activate the ADS1262 module.

Did you use two different pins for the CS? Can you show the electrical connections you used and the code which uses the TFT?

If you are using an Arduino Ethernet board you need to reserve and set the Ethernet Controller and SD chip selects (D10 and D4).

We have already reserved D10 for Ethernet Controller and D4 for SD Chip select. The issue is, how to communicate both of them, one by one. I can access one of them only when code is prepare for both devices.

Could you please give you a link of the partcular display you used? There hundreds of 2.2" SPI TFT modules. Some of them lack proper level translation circuitry.

I would suggest that
1) you debug individual code and to make sure that they work separately before integrating them.
2) you put those code pieces in logical blocks. for example, you are likely going to read something from the adc and displaying it on the lcd. so your code flow should be something like this:
  vol_adc = ad1262_read(ADC1_CH); //read analog from ADC1_CH
  vol_mv = adc2mv(vol_adc); //convert the adc results to mv
  lcd_display(vol_mv);  //display vol_mv on the lcd

this approach allows for much easier programming and debugging for you and your readers.


text:
Arduino connection websocket always fails
I am using the Arduino Websocket Client library to connect my Arduino Uno to a Socket.IO server. But the connection always returns 0 (fail) after the handshake.
Anyone has used this library before? How could I debug this?
#include "Arduino.h"
#include <Ethernet.h>
#include <SPI.h>
#include <WebSocketClient.h>

byte mac[] = {0xB8,0x27,0xEB,0x7E,0x2D,0xC9};
char server[] = "labathome.rexlab.ufsc.br";
int port = 8001;
WebSocketClient client;

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac);
  Serial.println(client.connect(server, port));
  client.setDataArrivedDelegate(dataArrived);
  client.send("Hello World!");
}

void loop() {
  client.monitor();
}

void dataArrived(WebSocketClient client, String data) {
  Serial.println("Data Arrived: " + data);
}

PS: I tested the server and it works fine, and I also tested with a normal WS server instead of the Socket.IO, and nothing :(

Wireshark is a nice tool for protocol analysis.

I know nothing about this library but it looks like the setup of your Arduino is incorrect.  What IP address has your Arduino got?  Where is the DNS server to resolve the server's address and how are you telling the Arduino this? Does it work if you use the IP Address rather than the name for the server?

And like @MikaelPatel says, download wireshark (or similar) and verify that the Arduino is connecting to the server.  (You might be able to see the server's logs).  I suspect it isn't.

@MikaelPatel how could I forget about wireshark! Thanx

@Matt oops, true. I am using DHCP (I'm printing the IP got by the Arduino here), and I usually use IP addresses rather than the name, my bad.

With the help of the library developer, I found out that it was a problem on the handshake version. So, I just downgraded my socket.io app from 1.0 to v 0.9.11 and it worked.

What version were you using?  (What version has the handshaking problem?) - Useful in case anyone searches and lands on this thread.  Also its OK to accept your own answer.


text:
What does the following code in Morse Code Arduino mean?
  struct node *root, *currentNode;
  root = (struct node*)malloc(sizeof(struct node));
  root->value = '\0';
  root->next = 0;
  currentNode = root;

It means allocate a structure of type and size node and initialize it - then copy the contents to another local variable called currentNode.

Just want to add, that the copied content of the variable root is a POINTER, so after theat root and currentNode points to the same place in memory. So for example after you do currentNode->value='a'; then root->value becames 'a' too, as it is on the same place in memory. (until you move root or currentNode to poit to other place - I would bet, that somewhere else is command like currentNode=currentNode->next;)

@gilhad The post has changed since I commented. Originally currentNode wasn't a pointer, but a local variable.

What does the following code in Morse Code Arduino mean?

Step by step:
  struct node *root, *currentNode;

Pointer variables root and currentNode. Pointers to struct node.
  root = (struct node*)malloc(sizeof(struct node));

Allocate memory for a struct node and assign root pointer.
  root->value = '\0';
  root->next = 0;

Assign struct node members using the root pointer. Assign value member to character 0. Assign next to zero, NULL, i.e. often marks end of list.
  currentNode = root;

Last assign currentNode to point to the save value as root, i.e. the allocated struct node.
Next question?

What's missing from this tiny code excerpt is the definition of 'struct node'. From the name, 'node', the member name, 'next', and the way these are being assigned, it's very likely that these 'struct node's are part of a linked list structure; a collection of data that is arranged, not by location as in an array, but by each node having a pointer (memory address) to the next one in sequence. One fixed memory location (apparently 'currentNode') points to the first datum; that one points to the next, and so on until the last one in sequence whose pointer value iz zero (or NULL, the symbol commonly used for an invalid pointer value).
Sorting a list is quicker than sorting an array or a collection of arrays of data, because only the pointers need to be changed; no data needs to be moved. Adding or deleting data in the middle of the list benefits even more; in an array you'd have to move all of the data following the add- or delete-point to create or close a gap for the new or removed datum.
Look at the rest of the code. It's quite likely that is how the 'node's are being used. Also read about linked lists, if that is a new concept.


text:
How can I setup a LED state change with push buttons?
I'm doing a project using Arduino Uno R3 and I'm trying to use two buttons to change LED state between HIGH and LOW. I have already a code but someting its not right because the LED should be starting in LOW state but it's starting in HIGH state. I checked the circuit and its all good none of the components is connected in wrong place or not connected corretly and the resistors I used are the right ones.
Here is the code I'm using:
 int ledpin = 13;
 int pushbutton1 = 8;
 int pushbutton2 = 7;
 boolean lastbuttonstate1 = LOW;
 boolean lastbuttonstate2 = LOW;

void setup()
{
  pinMode(ledpin,OUTPUT);
  pinMode(pushbutton1,INPUT);
  pinMode(pushbutton2,INPUT);
}

void loop() {

static bool ledState = false; // LED is off by default
 if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
    digitalWrite(ledpin, HIGH);
    ledState = true;
 }
  if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
    digitalWrite(ledpin, LOW);
    ledState = false;
  }
}

You need some PULLUP there - either external resistors or INPUT_PULLUP settings, otherwise disconnected pin have not defined valou (so it can be LOW even if button is not pressed.

I tryed the INPUT_PULLUP and it worked but now the LED state turns LOW when I stop pressing the button and the other button does the same thing.

I tried that on my arduino and it works - when I press button1, LED goes ON when I release it, the LED is still ON. When I press button 2, LED goes OFF and stays OFF even when I release the button. I would check all your connections if they are reliable (do not lose contact when you manipulate the buttons - I have universal shield with LEDS and buttons soldered fast - I had recently some problems with some breadboards) and if the led is on pin 13(the build in is), while buttons are between pins 7,8 and ground. (and that the script uploaded correctly)

Also note, that your loop can be as simple as: loop() { if ( ! digitalRead(pushbutton1) ) digitalWrite(ledpin, HIGH); if ( ! digitalRead(pushbutton2) ) digitalWrite(ledpin, LOW); }

This is an excellent tutorial for exactly that:
http://www.instructables.com/id/How-to-use-a-Push-Button-Arduino-Tutorial/
Its a bit hard to give you a specific answer without seeing you circuit.
but as a start, i would set the ledPin to LOW in the setup routine.
void setup()
{
  pinMode(ledpin,OUTPUT);
  pinMode(pushbutton1,INPUT);
  pinMode(pushbutton2,INPUT);

  //initialize the pin to low
  digitalWrite(ledpin,LOW);

}

I think you have just minor changes. First of all, you haven't applied pullup. And here, what is the use of boolean lastbuttonstate1 = LOW; and boolean lastbuttonstate2 = LOW;? I think it not useful for the code so I remove it. And always initialize flag or something in starting of the code means globally. I update your code, just check it out. It might be helpful.
int ledpin = 13;
int pushbutton1 = 8;
int pushbutton2 = 7;

static bool ledState = false; // LED is off by default

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

  pinMode(pushbutton1,INPUT_PULLUP); // Provide pullup
  pinMode(pushbutton2,INPUT_PULLUP); // Provide pullup
}

void loop()
{
  if((digitalRead(pushbutton1) == LOW) && !ledState) // 1 pressed & led is off
  {
    digitalWrite(ledpin, HIGH);
    ledState = true;
  }
  if((digitalRead(pushbutton2) == LOW) && ledState) // 2 pressed & led is on
  {
    digitalWrite(ledpin, LOW);
    ledState = false;
  }
}


text:
Better way to remap 16-Key Touch keypad
I have written a code that remaps the buttons of TTP229 touch keypad which works as it is. Is there any way to optimize this code:
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#define SCL_PIN 11
#define SDO_PIN 12
#define I2C_ADDR    0x3F
#define BACKLIGHT_PIN     3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7

byte Key;
String keyRemap[12][2] = {
    {"1","1"},{"2","2"},
    {"3","3"},{"5","4"},
    {"6","5"},{"7","6"},
    {"9","7"},{"10","8"},
    {"11","9"},{"14","0"},
    {"13","Clear"},{"15","Enter"}
};

LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

void setup()
{
    lcd.begin (16,2);
    lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
    lcd.setBacklight(HIGH);
    lcd.home ();

    pinMode(SCL_PIN, OUTPUT);
    pinMode(SDO_PIN, INPUT);
}
void loop()
{
    Key = Read_Keypad();
    if (Key != 0) {
        lcd.clear();
        lcd.setCursor (0,0);
        for (int x = 0; x < 12; x++) {
            if (Key == keyRemap[x][0].toInt()) {
                lcd.print(keyRemap[x][1]);
            }
        }
        delay(160);
    }
}
byte Read_Keypad(void)
{
    byte Count;
    byte Key_State = 0;

    for (Count = 1; Count <= 16; Count++)
    {
        digitalWrite(SCL_PIN, LOW);
        if (!digitalRead(SDO_PIN))
            Key_State = Count;
        digitalWrite(SCL_PIN, HIGH);
    }
    return Key_State;
}

What do mean exactly by "optimize the code"? Do you have problems with its speed, its size, or anything? What is your question really?

Is there any way to optimize this code:

Absolutely, yes. Don't use String for this, you are seriously wasting memory. Instead you can use a struct:
struct keymap {
    uint8_t code;
    const __FlashStringHelper *value;
};

const struct keymap keyRemap[] = {
    { 1, F("1") },
    { 2, F("2") },
    { 3, F("3") },
    { 5, F("4") },
    { 6, F("5") },
    { 7, F("6") },
    { 9, F("7") },
    { 10, F("8") },
    { 11, F("9") },
    { 14, F("0") },
    { 13, F("Clear") },
    { 15, F("Enter") },
    { 0, 0 }
};

void loop() {
    int Key = Read_Keypad();

    if (Key != 0) {
        lcd.clear();
        lcd.setCursor(0, 0);

        for (int x = 0; keyRemap[x].code != 0; x++) {
            if (Key == keyRemap[x].code) {
                lcd.print(keyRemap[x].value);
            }
        }

        delay(160);
    }
}

Will you stop posting faster than me :)

I can't help it if I had 2 coffees this morning :P

You could also fully populate the table with all possible answers and then this would remove the loop when looking for answers, but you would need to handle 4 and 12 specially.

It would remove the need for the struct entirely then - a simple 16-entry array. But where would the fun in that be?

@Majenko I used your code and I got an error

@conquistador Probably something odd with the Arduino IDE (that I never use) - some flag not being set or being set that shouldn't really be being set.


text:
Using SIMCOM SIM800 as a Bluetooth SPP Client
I just bought a SIM800 module for my Arduino project and I found that I supports Bluetooth too. I have already worked with HC-05 and my Android phone.
I tried to play with this module and able to connect it successfully with my Android mobile. I am able to make a call using it, accept a call, etc. But when I tried to send text data using it (in SPP mode), I ran into problem.
I have an app called Bluetooth Terminal in my mobile with which I use to communicate with my HC-05. But with SIM800, I can't connect.
I have read all the AT commands which are used to make a SPP connection. Here's a screenshot of the PuTTy terminal where I tried to make the connection:

As you can see in the image, whenever I try to call

AT+BTGETPROF=1

It never returns to me. I also tried the command with my Bluetooth visible in the mobile, but still no result.
Whenever I try to run the command or

AT+BTCONNECT=1,4

My SIM800 goes into state 2 and I have to manually reset it.
Can someone please help me with this problem? I just want to use my SIM800 as a SPP client/server so that I can exchange text data with my Android APP.
Thanks in advance.

I tried to make my SIM800 as server by making the request from the mobile, but now I can't send data from SIM800 and the data send by mobile is echoed back.

AT+BTGETPROF failed, so no sense making AT+BTCONNECT=1, (where n should be SPP profile index on the list returned by AT+BTGETPROF). Make sure that SPP is listed first. Also did you get +BTPAIRING: message? If so answer with AT+BTPAIR=1,1

Yes I know that there is no sense making AT+BTCONNECT. Yes I got the +BTPAIRING: message when I make the request from my mobile, but then my SIM800 enters into Server mode because of which I can't use AT+BTSPPGET and AT+BTSPPSEND

In server mode, module shall received +BTCONNECTING: "...","SPP" message - reply with AT+BTACPT=1 (shall return OK) and  AT+BTSPPGET=0 (auto mode). Then you can do AT+BTSPPSEND. For client mode, isn't you module shall start the initiation?

For being in client mode, yes I should initiate, but the same problem occurs with me which I have posted in the image @Flanker. The server mode works well but whatever I send to SIM800, it is echoed back and I receive nothing at my terminal.

By default i see that the Android handset i used did not have SPP profile enabled. You need to open a App which enables the SPP profile to be advertised. Then after that you can get that in AT+BTGETPROF list. I made a tutorial for this, Have a look here,
https://youtu.be/zdQb8r2xRK8
and
http://www.raviyp.com/embedded/215-sim800-series-bluetooth-at-commands


text:
Yet another "Mac cannot find USB serial port" post
I have read about every post about people having issues with their Arduinos on Macs. I have a 100% authentic Arduino UNO, that I cannot by any circumstance manage to connect to my late 2009 iMac with macOS Sierra 10.12.2.
I tried just about anything from disabling Apple FTDI drivers, installing FTDIUSBSerialDriver, D2XX drivers and even the CH34X drivers (for knockoffs). NOTHING works.
Not even setting boot arguments, not disabling default extensions/drivers, not removing extensions/drivers.
I am completely stuck, and no guide has ever worked. I've tried rebooting numerous times, but still no luck. The only port available in the Port menu is the Bluetooth Incoming port.
Does anyone have any tips or hints? I am on the verge of doing a complete reinstallation of my computer just to have all drivers back to default.

What does dmesg tell you while you plug it in?

Alot of "AMFI: allowing exception handler for 'polard' (3658) because the process is unsigned." (I guess polard is my Polar heart rate monitor). Other messages: IO80211Interface::updateReport _peerManager is missing. That is basically it.

A little research and I'm not so sure polard is the heard rate monitor at all. For every time I connect the Arduino, a new line with this message shows up.

Does the same USB port work for other USB devices? Try another port? Can you test whether another computer sees your Arduino? Substitute a different USB cable?

An actual Uno does not require drivers on OSX as support for CDC/ACM is built in.  Fair warning: answers which ignore this and propose installing FTDI, CH340, CP210x, etc drivers will be severely down-voted.  This question is about an Arduino Uno; it is not about random other boards with different details.

@JRobert I've tried all ports on my iMac (4) plus the 2 on the keyboard. Not one of them is working with the Arduino. All of them are working with other devices. The Arduino does not work with my girlfriends MacBook Pro (OS X El Capitan 10.11.5), but it did work on my dads MacBook Pro (macOS Sierra 10.12.2). My dad only had to install the FTDI drivers to get it to work.

It sounds a lot like the Arduino or the cable, just by the fact that it fails on at least two machine. I'm surprised, though, that you needed install any drivers. Macs have understodd FTDI out of the box since at least OS 10.6.8; It's just the alternative USB <-> serial chips that have needed any additional drivers.

Thanks @JRobert. Are there some way to reset the whole Arduino to factory settings?

Just by powering it off. There aren't any arduino settings relevant to how it appears to a computer. That's built in to the auxilliary 8u2 or 16u2 processors' firmware and not configurable any way that I've ever heard of.