text:
Arduino Uno - relay with separate power
i want to operate a relay with an ARDUINO UNO, but i want to use a separate power supply for the relay. Ive seen relays with VCC and jVCC (dont know what that is), but mine only has this pins: GND, IN1, IN2, VCC.
how should i connect it to the Arduino and the external power supply?

That doesn't look like a relay board set up for separate power supply. Those that do will have an opto-isolator per relay.

jVCC (where avail) is used to drive the magnetic relay coils, VCC is used to drive the logic/LEDs.

This relay is designed to operate on 5V.
Most commonly this will come from the Uno's 5v pin.
If you want to externally power the relay itself then make sure to connect the +5 to the Vcc on the relay board and the - lead to the GND on the relay board.
Uno's GND must also be connected to the GND on the relay so the Digital outputs from the Uno will properly control the IN1 and IN2 inputs to the relay board.

The Uno has multiple GND connections so it makes the most sense to connect the - to one of them then another to the relay.

Note that the Uno's 9V Vcc external power comes in through the barrel connector on the Uno itself. The Uno will pass power through its internal regulator to provide 5v at the appropriate connection.

If you are switching external devices that run on 120V it would be on the screw-terminal side of the board only.

To prevent accidental activation of the relays, note that this particular board is ACTIVE-LOW which means that as you initialize the output pins you should first set them HIGH so setting the pinMode will not default to LOW which would trigger the relay.

In the setup() section, using pins D5 and D6 as an example:
digitalWrite(5,HIGH); pinMode(5,OUTPUT);
digitalWrite(6,HIGH); pinmode(6,OUTPUT);

The question is "but i want to use a separate power supply for the relay".

The Arduino and the external PSU should have the GND or - connected with each other.
Then connect the external PSU + or Vcc to the relay boards Vcc.

Regarding jVCC see https://arduino-info.wikispaces.com/RelayIsolation .
It is used when you have optocouplers isolating the power supplying the relay coil from the Arduino's power (VCC).

External psu to gnd and vcc, in1 and in2 to arduino pins which control each relay (on is LOW) and most importantly gnd also to arduino gnd.


text:
Controlling 10+x 5m led strips with 10+ individual analog floor switches
I am looking to control around 10 (exact number TBD) non-addressable 5m led strips with an Arduino. Each led strip will be activated when a corresponding DIY analog floor switch.
The idea is to have a hallway with a number of these led strips oriented vertically from the floor to the ceiling and when somebody walks on the corresponding floor switch under the strip, the strip will light up.
I have a number of questions:

How could I have a setup that is scalable from 10 led strips and floor switches to 20? (having enough analog and digital pins)
How should I best distribute power to all the strips and for each switch? This is how I understand to setup 1 of the switches:
How do I wire the one colored non-addressable LED strips to the Arduino?

Note: I have coded before and done some soldering and simple electronics but have never used Arduino.
Thank you!

You don't need an Arduino to light up LEDs from switches, you just need wires.

And maybe MOSFETs if the switches good be a higher resistance than you would like.

look into SPI/I2C "IO expander"s, or shift registers. 2. see #1. 3. use a logic level n-chan mosfet, like the irlz44n: drain to LED-, gate to MCU/IO, source to ground (both MCU and LED PSU).

I think that the best solution for you, unless you want a simple on/off control (if you want it just go with Majenko's solution) is to use port expanders.
Maybe this can be slightly overkill, but you can think of using a MAX7313.
This IC is I2C controlled and has 16 I/O; you can configure each as input or output, and with automatic PWM generation too. This means that the uC just has to send it the value of light you want to output and it automatically keeps the LED strips at the correct duty cycle.
This way you can connect a sensor to P0, P2, P4, ... and configure them as input, then a pull-up resistor and a MOSFET to P1, P3, P5, ... and configure them as output with PWM. From the arduino, you will just have to connect two pins (SDA, SCL) and, of course, GND, then you will have the ability to control eight sensor/led pairs to one sensor. You want to extend it? Just solder another IC and assign it another address (pins AD0..2 serve for this purpose). You can set 64 different addresses, thus being able to drive 512 sensor/led pairs.
Want more? Use RGB led strips. Connect P0 to sensor, P1 to R, P2 to G, P3 to B, and with each IC you'll be able to drive four sensor/led pairs. You'll be able to drive only 256 sensor/led pairs, but they will be rainbow colored...
This solution has only one drawback: I could not find any pre-made board with the MAX7313 on ebay. So you'll have to design your own PCB and solder it. If you are not able to do this, alternatives exist.
Adafruit has a PCA9685 16-channels port expander board (and a lot of other manufacturers made this). This has also integrated PWM and a lot of addresses possible, but the PCA has only outputs (so no inputs). You will be able to arrange them in a matrix (so with the 18 pins remainig you will be able to control 81 switches).
Another alternative is the MCP23017; this has inputs and outputs, but no automatic PWM; this means that if you want turn them on and iff ok, but if you want a variable light you will have to "manually" pull the pin high or low (very heavy on the I2C network).
Other solutions using SPI may have better performances (SPI is faster than I2C), and a lot of other ICs with SPI, I2C or other serial connections exist. You just have to find out the most suitable for you

Unless you want to do fancy things with the LED strips you really don't need an Arduino to accomplish this task.  You can just switch each strip with a powerful enough MOSFET and control the gate with the sensor:

simulate this circuit – Schematic created using CircuitLab
If you really want the Arduino (for example to add effects like delays, fading, blinking patterns, etc) it would basically go into the circuit at point A in the circuit. The sensor into an input and the MOSFET into an output.
Since these are just presence sensors (not pressure sensors, they don't sense pressure, only presence) you don't need an analog input to read them - a digital one will suffice and also make your programming simpler.
You can use shift registers or IO expanders to increase the number of input and output pins you have, or you can use a larger Arduino with more pins.

I have a number of questions:

use a transistor to turn on / off each leds. size the transistor based on the leds' voltage / current requirement.
make sure that your arduino has sufficient number of pins for the sensors + leds. if not, you can split the tasks among multiple arduinos.

source: Stack Exchange

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

sort: votes


text:
Using Raspberry Pi to Receive Float from Arduino using NRF24L01
Good day. I've been learning on how to transfer data from Arduino to Raspberry Pi wirelessly using NRF24L01 based on the following reference:
Raspberry Pi 3 Tutorial 14 – Wireless Pi to Arduino Communication with NRF24L01+.
The reason why I want to do this is to log temperature and humidity data wirelessly using DHT22 sensors.
The Arduino code is shown below:
//SendReceive.ino

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

// CE, CSN pins
RF24 radio(9, 10);

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

    radio.begin();
    radio.setPALevel(RF24_PA_MAX);
    radio.setChannel(0x76);
    radio.openWritingPipe(0xF0F0F0F0E1LL);
    const uint64_t pipe = (0xE8E8F0F0E1LL);
    radio.openReadingPipe(1, pipe);

    radio.enableDynamicPayloads();
    radio.powerUp();

}

void loop(void){
    radio.startListening();
    Serial.println("Starting loop. Radio on.");
    char receivedMessage[32] = {0};
    if(radio.available()){
        radio.read(receivedMessage, sizeof(receivedMessage));
        Serial.println(receivedMessage);
        Serial.println("Turning off the radio.");
        radio.stopListening();

        String stringMessage(receivedMessage);

        if(stringMessage == "GETSTRING"){
            Serial.println("Looks like they want a string!");
            const char text[] = "Yo wassup, haha";
            radio.write(text, sizeof(text));
            Serial.println("We sent our message.");
        }
    }
    delay(100);

}

Meanwhile, the Raspberry Pi code is shown below:
import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import time
import spidev

GPIO.setmode(GPIO.BCM)

pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

radio = NRF24(GPIO, spidev.SpiDev())
radio.begin(0, 17)

radio.setPayloadSize(32)
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)

radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openWritingPipe(pipes[0])
radio.openReadingPipe(1, pipes[1])
radio.printDetails()
# radio.startListening()

message = list("GETSTRING")
while len(message) < 32:
    message.append(0)

while(1):
    start = time.time()
    radio.write(message)
    print("Sent the message: {}".format(message))
    radio.startListening()

    while not radio.available(0):
        time.sleep(1 / 100)
        if time.time() - start > 2:
            print("Timed out.")
            break

    receivedMessage = []
    radio.read(receivedMessage, radio.getDynamicPayloadSize())
    print("Received: {}".format(receivedMessage))

    print("Translating the receivedMessage into unicode characters")
    string = ""
    for n in receivedMessage:
        # Decode into standard unicode set
        if (n >= 32 and n <= 126):
            string += chr(n)
    print("Out received message decodes to: {}".format(string))

    radio.stopListening()
    time.sleep(1)

Based on the Arduino code above, the code that shows the data that is transmitted is shown below:
const char text[] = "Yo wassup, haha";

Based on the Raspberry code above, the codes that decode the received data from Arduino are shown below:
for n in receivedMessage:
    # Decode into standard unicode set
    if (n >= 32 and n <= 126):
        string += chr(n)

However, these decoding code only works if I transmit string or integer from Arduino to Raspberry Pi. It doesn't work if I transmit float. Since DHT22 records temperature and humidity up until 1 decimal point, it is required for me to transmit float. Can anyone here please teach me how to decode the float values?
Thank you very much.

If you say you only need one digit, why not multiplying your value with 10 (with rounding), transmit it as a 4 byte (unsigned?) integer, and divide by 10 after receiving.
You only need to check if you have little or big endian conversion needed (swapping MSB/LSB 2 byte or single byte). But you see this very fast if you print the values in hex format.

Yes, but keep in mind that an Arduino's unsigned int is 16 bits while a pi's is 32 - you want an unsigned long, or better yet a portable type like uint32_t

@ChrisStratton Fully agree, whenever I want to control my type lengths, I always use (u)int8/16/32_t. This mostly is to reduce space (longer arrays) and sending data to other devices.

But now you used float?

Agree. I was also considering about multiplying the float by 10 in arduino, then transmit the value from arduino to pi, then divide back the value by 10 in raspberry pi. I also need some time to try doing this & will update you guys with my progress later. Thank you very much.

Somebody suggested me to convert the float to string in Arduino, then transmit the string from Arduino to Raspberry Pi throught NRF24L01, then convert back the string to float in Raspberry Pi. I think I will also try that. Below are some of my references:
Arduino - StringConstructor
https://www.arduino.cc/en/Reference/StringConstructor
Parse String to Float or Int
https://stackoverflow.com/questions/379906/parse-string-to-float-or-int
I will inform the result once I tried this.

Note that a string cost more bytes than an integer. E.g. "1234.4" would cost 6 bytes and 12344 2 bytes (assuming the max value can be 65535 and unsigned or -32768..32767 signed).

Instead of converting float to string in Arduino, I think I need to convert the float to char because the example that I refer transmit char from Arduino to Raspberry Pi through NRF24L01. However, I still don't know how to convert the float value to char at this moment.

@foxfaisal dtostrf might help: http://forum.arduino.cc/index.php?topic=85523.0

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


text:
Arduino Mega and other modules power consumption
I have an Arduino Mega 2560 to which I have connected:

Arduino GSM Shield 2
Waveshare 10 DOF IMU sensor
Waveshare NEO-7M-C (B) GPS module
HC-05 ZS040 Bluetooth module

I am feeding my Arduino a 12V current via the VIN pin, yet both the GSM shield and the GPS module are misbehaving due to low power working conditions. All the modules work perfectly fine individually, or in any combination that does not have both the GSM and the GPS module, as they consume the most power.
My question is how high a voltage would be necessary in order for all of the modules to function correctly and how this voltage should be connected to the Arduino.


text:
Arduino Mega and other modules power consumption
I have an Arduino Mega 2560 to which I have connected:

Arduino GSM Shield 2
Waveshare 10 DOF IMU sensor
Waveshare NEO-7M-C (B) GPS module
HC-05 ZS040 Bluetooth module

I am feeding my Arduino a 12V current via the VIN pin, yet both the GSM shield and the GPS module are misbehaving due to low power working conditions. All the modules work perfectly fine individually, or in any combination that does not have both the GSM and the GPS module, as they consume the most power.
My question is how high a voltage would be necessary in order for all of the modules to function correctly and how this voltage should be connected to the Arduino.

Current is what matters, not input voltage.

This question has been already answered by 3 pp in the arduino.stackexchange. Not only the recommended voltage is 7-12V, but also you should not increase the voltage, as the Arduino Mega 2560 has a linear voltage regulator. The larger the voltage, the larger the power dissipation, with 0 benefits. Beware that the headers on the arduino board cannot handle a very large current (maybe 500mA?).

You can't fix it with more voltage. The board you are using (schematic here) uses a linear voltage regulator. All increasing the voltage does is make the regulator run hotter.
You could try running from around 7V, this will minimize the heat dissipation in the regulator and may allow you to pull more current through it but I suspect you've simply hit the design limits of the power supply circuits.
Instead of using the Arduino's built in power supply to convert from 12V to 5V you could try using an external 5V supply with a greater current capability connected directly to the Arduino 5V rail.

You should not try to power your arduino with more than 12 V.  The barrel jack connector can take between 7 and 12 V and from there steps it down to the proper voltage for the Arduino (5V).  Anything being powered by the arduino is limited to how much current it can output, so if you have too many modules, you may need to have a separate power supply for those.  If you do this, there several things you need to consider:

What voltage does each module need? (This is probably 5V, but you should check the datasheets or any documentation you have)
How much power does it consume? You might find this in documentation, but you can also calculate it yourself: P = I*V  Once you know how much power each module/sensor consumes, you know how much your power supply needs to supply.

If you use a separate power supply for any of your modules/sensors,  make sure the ground pin is also tied to Arduino's ground.

Power applied to the VIN pin is regulated down to 5V by the on-board regulator on the Mega. The minimum voltage is about 6.2V because of the regulator dropout (that is, the regulator needs at least 1.2V above it's 5V output in order to operate.) 9-12V is recommended.
Applying a higher and higher voltage will not provide any more power to the Mega and it's peripherals/shields. Instead, the excess power is dissipated in the regulator as heat.
If you experience low-power situations, the solution is to power the peripheral devices from a separate regulator than the one built-in to the Mega, which is really intended to power the Mega board/processor and maybe 1 shield.
You could obtain a high-current (3A or more) 5V supply, and connect the peripherals' power inputs to it, as well as power the Arduino in via the 5V pin (leaving VIN disconnected!). Be sure to tie the grounds of all peripherals and the arduino and power supply together.
Be sure also to pay attention to the voltages required by the peripheral modules, as it's common now to find modules that are rated for 3.3V and would be damaged by 5V. This is probably not the case for you, since your system is working sometimes.


text:
How can I swap a servo with a stepper motor?
I'm looking for a way to swap servo 1 with a stepper motor to achieve a single direction circular motion with stops and delay. Instead, now I have the servo going back and forth to repeat the action.

This is the code I'm currently using to drive the servo:
void loop() {
  topServo.write(115);
  delay(500);

  for(int i = 115; i > 65; i--) {
    topServo.write(i);
    delay(2);
}

This is a schematic of my project:

simulate this circuit – Schematic created using CircuitLab
Can anyone help me to configure this? or point me into the right direction.
Any help would be greatly appreciated!

When you got the 28-BYJ48 stepper motor, did you also get a ULN2003  Motor driver board?

@sempaiscuba Yes, I do have a ULN2003 Motor driver board

Firstly, I'm going to assume that you got a ULN2003 Motor driver board something like this along with your 28-BYJ48 stepper motor.
Secondly, I would always recommend using a separate power supply for your stepper motors. Even a small stepper motor like the 28-BYJ48 can draw up to 320mA, (160mA per winding).

I've used the following code to test a setup using a 28-BYJ48 stepper motor and an Arduino. The connections to the driver board (IN1 - IN4) are mapped to pins 8-11 on the Arduino in this case. The code will cause the stepper to rotate 1 full revolution in one direction, pause for 1 second and then rotate one full revolution in the other direction.
(I've often found this simple piece of code really handy for troubleshooting!)
#include <Stepper.h>

const int stepsPerRev = 2048

// initialise the stepper library on pins 8, 9, 10 & 11
Stepper myStepper(stepsPerRev, 8,10,9,11);

void setup() {
  // set the speed
  myStepper.setSpeed(4);

}

void loop() {
  // step one revolution in one direction:
  myStepper.step(stepsPerRev);
  delay(1000);

  // step one revolution in the other direction:
  myStepper.step(-stepsPerRev);
  delay(1000);

}

thank you for your answer! I will give this a try. Is it mandatory to use a separate power supply for the stepper motor? I don't think it's drawing that much current. Or do you recommend this for other reasons? I don't have an extra power adapter laying around to test this at the moment. Could I use a battery instead?

A suitable battery will work fine, but even a small stepper motor like the 28-BYJ48 can draw up to 320mA, (160mA per winding).


text:
Using Li-Poly battery to run UNO + Adafruit data logger
I want to power Arduino UNO+Adafruit data logger (https://www.adafruit.com/product/1141) with a 3.7V 2000mAh Li-Poly battery. I am providing an excitation voltage of 3V, through one of the digital pins and a potential divider arrangement, to a sensor which is providing output signal in analog (voltage) form. I am using ADC to read that voltage. My question is, since the battery voltage is going to drop during its operation, would the voltage output from the digital pin, and thus the potential divider, also drop? Could this voltage drop also affect the reference for the ADC?

The UNO is a 5V board. How do you plan to run it from 3.7V?

I have read on the forums about different methods to power a Arduino from a Li-Poly battery:

Using a boost converter to boost the voltage beyond 5V and then using Vin pin to power the board (not preferable as the boost converter +linear regulator connected to Vin pin will decrease efficiency)

Directly connecting the battery to 3.3V pin on the board (the 3.3V pin is connected to a regulator)

You can't run the Arduino UNO directly from 3.7V.
You can use a boost regulator to step up to 5V and feed that into the 5V pin - in which case your question becomes null and void, since you are running at 5V, not 3.7V.
Or you can perform some hardware and/or fuse modifications and run the board directly from 3.7V into the 5V pin:

You will have to change the surface mount resonator to an 8MHz one instead of the normal 16MHz, or
Switch the clock to use the internal RC oscillator by reprogramming the fuses.

Either way you will then have to also modify the board configuration in the IDE to run at the new clock speed.
So given all that the simplest thing to do is to invest in a 5V boost regulator. Personally I'd suggest the LiPower Shield from Sparkfun. It also has a "fuel gauge" chip to monitor the batter charge.
Either that or scrap the Uno and invest in a development board that is designed to run from a Li-Poly / Li-Ion / LiFePO4 battery.


text:
Multiple sensors connected to Arduino MEGA 2560 Serial ports
I am using Arduino MEGA 2560 to read values from two sensors. Sensor 1 is providing us two values separated by a comma and a space followed by a newline character. e.g.:
2.277, 7.942
2.269, 7.897
2.263, 8.040

Sensor 2 is providing us a single value followed by a newline character. e.g.
1.213
1.333
1.17

Sensor 1 gives twice as many readings as Sensor 2 in the same amount of time. Sensor 1 is connected via Serial1 and Sensor 2 is connected to Serial2 on MEGA board. I am using the following code to read the values:
void setup() {
  Serial.begin(57600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  while (!Serial)
  {
  }
}
void loop() { // run over and over
  if (Serial1.available()) {
    {
      Serial.print(Serial1.readStringUntil('\n'));
      Serial1.flush();
    }
  }

  Serial.print("\t\t\t");
  if (Serial2.available()) {
    while(Serial2.available())
    {
      Serial.write(Serial2.read());
      Serial2.flush();
    }
  }
  Serial.println();
  delay(1000);
}

I am expecting an output similar to this:
2.409, 8.150            2.134
2.490, 7.851            2.133
2.603, 8.759            2.122
2.634, 8.305            3.12
2.727, 8.408            1.32
3.018, 7.982            2.543
3.030, 7.982            1.345
3.020, 8.587            2.435
2.844, 8.034            2.763
2.690, 8.690            5.433
2.721, 8.011            2.348
2.705, 8.242            7.654
2.670, 8.713            2.123
2.756, 8.563            2.098
2.899, 8.413            2.765
3.464, 8.196            2.654
3.705, 8.437            2.343
3.435, 8.558            1.245
3.446, 8.592            2.345
3.421, 8.075            1.234

Instead I am getting something like this:
2.770, 8.332.635, 8.281         2.345
2.690, 8.690            2.674
2.721, 8.011            2.356
2.705, 8.242            2.345
2.670, 8.713            3.002
2.756, 8.563            2.094
2.899, 8.413.102, 8.523         2.984
3.464, 8.196            2.398
3.705, 8.437            2.745
3.435, 8.558            2.789
3.446, 8.592            2.543
3.421, 8.075            2.984
3.504, 8.153.772, 8.770         2.183
3.705, 8.552            2.784
3.653, 8.443            2.567
3.908, 7.971            2.098
5.020, 8.581            2.20
3.913, 8.247            2.342
3.762, 8.023.575, 8.345         2.123

The sensor readings after every few lines are distorted. I understand this might has something to do with the serial buffers. How could I rectify this and obtain the desired output?

You should use a method similar to this: https://majenko.co.uk/blog/reading-serial-arduino - expand it to work with multiple line buffers and multiple serial ports.

Your serial buffers and moving in and out of phase, which is distorting your display.
Try something like:
void setup() {
  String sensor1;
  String sensor2;
  Serial.begin(57600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  while (!Serial)
  {
  }
}
void loop() { // run over and over
  if (Serial1.available()) {
    sensor1 = Serial1.readStringUntil('\n'));
  }

  if (Serial2.available()) {
    sensor2 = Serial2.readStringUntil('\n'));
  }

  Serial.print(sensor1);
  Serial.print(sensor2);
  Serial.println();
  delay(1000);
}

I would also recommend the method suggested by @Majenko in his comment below your question.

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


text:
Analog output low voltage issue, how to troubleshoot
I have connected my arduino according to the schematics in the image, with a few additions.
The setup

A DC motor (water pump) drawing power from Vin, going to ground via a transistor based in A0 analog output. Between the transistor and A0 is a 270 ohm resistor. In parallel to the motors poles is a diode, for protection.
A 3,1" (4x20) LCD screen with an I^2C chip (draws 5V, A4 and A5 and GND)
A Potentiometer directly on the I^2C chip LED pins (replacing the jumper) - for control of the light intensity. (Vin and middle pin of pot, gnd unconnected)
A Potentiometer connected to A1, 3,3V and GND.

Code description:
Using the Timer and the LiquidCrystal_I2C library,
Once every other second the LCD is refreshed
Once every day the water pump is started with an analogWrite(A0, HIGH) and it runs for 1-60 seconds based on the potentiometer setting.
The issue.
It seems the output of A0 does not deliver enough voltage to trigger the pump. This is a new error, before I got the screen, it ran the pump fine.
I suspect one of three things. 1: I have broken something in the arduino power regulator, and the voltage outputs on analog pins are lower than they should be (or their ability to supply current) -> Must get new arduino. 2: I have somehow saturated the ground pin or there is a connection issue. 3: The LCD display is drawing too much current. (Leading to either 2 or 1, but won't be fixed by getting a new arduino)
What have I already tried
I have tried, with the arduino connected via mains to short it between 3,3V and the transistor base, and then it runs. So the transistor is OK, the pump is OK. I have tried to map the output to another analog pin to display the value of this pin while the program is running, and it does display a value while the pump is supposed to be running, so it is doing something. I have used a multimeter to measure the pins, but I really don't know what "normal" is so I decided to stop fiddling around with that. I have also tried using other analog outputs (excepting 4 and 5, they are claimed by the lcd I^2C logics)
Can anyone of you please give me some pointers in the right direction, to help me to determine the error in question? What should I try?
Disclaimer, due to having the normal issues of life, love and the fact that a day only has 1440 minutes, I usually only have time to work on my pet projects during weekends...
If this question is not relevant or poorly written, please let me know, I'll try to clarify (or delete it).

Looks to me like your transistor is wired backwards...

@majenko It is drawn backwards then. I am not entirely sure which side of the icon is e and c.... The circuit works.

The arrow is on the emitter. It should be flipped left/right.

The analog pins are for analog input not output. You can only use them for digital output.
Change
analogWrite(A0, HIGH)

to:
digitalWrite(A0, HIGH)

analogWrite() can only be used on PWM capable pins (the ones marked with ~). On any other pin it sets the pin HIGH if the analog value > 127 and LOW if the analog value <= 127.
Since you are writing HIGH, which is equal to 1, the output is LOW because 1 < 127.

Thanks for the clarification. I was under the illusion that digitalwrite only produced a pulse. I will test this at the earliest possibility and report back.

No, digitalWrite sets a HIGH or LOW output. To send a pulse you have to use two digitalWrite calls - one to set it HIGH and then one to set it LOW. Where did you get the idea that digitalWrite creates a pulse?

Confirmed as solution, thank you to both juraj and @Majenko. I learned something new and useful! (and let's not mention eff'ing obvious, slightly shameful about it ;-)

Don't be. There's nothing wrong with being wrong or lacking some knowledge. Unless you're wrong sometimes how can you learn how to be right in the future?

Shameful because such an error, I should have found while researching, not asking high skilled people to answer a low skill question. But thank you again, it is all the more appreciated.

why analogWrite? analogWrite parameter values are 0 to 255 (or 1023) so analogWrite(pin, 1) is close to 0.
analogWrite is PWM on digital ports and doesn't work on analog ports
analogWrite reference
use digitalWrite

I thought digitalwrite was only a single pulse... I will try that asap, if my mistake is this silly I am going to feel ashamed... Thanks for the info in any case!


text:
The most efficient way to test whether a byte is "empty" (B0000000) or not?
I have completed a small project I did to challenge myself to learn more about my arduinos programming. In this project, inside a for loop I have to check whether a MyVar byte fetched from an array of bytes, is "empty" (or 0, or B0000000 what applies best). Rough description of the program in note 1.
I did a lot of trial and error, and quickly realized that just asking
byte MyVar = B0001111
if {MyVar = 0 ; DoSomethingSpecial() } else {ProceedLoop()}

did not produce anything near the desired state. I deduced that testing bytes probably need to happen bitwise, or something clever (=beyond my understanding) is going on in how the compiler interprets the conversion.
So I created a dummy variable byte
byte EmptyValue = B0000000

and then did a logical AND between the MyVar and the EmptyValue
if (MyVar&EmptyValue) {DoSomethingSpecial(); } else {ProceedLoop(); }

which seemed to do the trick - it was getting late and my ability to find useful Serial.print() to capture the different values was getting low, but the results running the program were at the time indistinguishable to me from the expected way.
My question, firstly - is this a reasonable way to check if a byte is zero? Does it actually do that? I have been reading up on these bitwise calculations and I am truly confused to how it compares a final TRUE or FALSE from comparing.
Secondly, what would be a more processing-time-optimal way of doing this comparison? Is there a null-test of sorts? Should I have cast it into integer and tested against integer 0?

  const int interval=400;
  const byte ByteArrayMakeSound[11]={
    B0001111,                                       //H - length 4
    B0001111,                                       //E - length 4
    B0001111,                                       //L - length 4
    B0001111,                                       //L - length 4
    B0000111,                                       //O - length 3
    B0000000,                                       //
    B0000111,                                       //W - length 3
    B0000111,                                       //O - length 3
    B0000111,                                       //R - length 3
    B0001111,                                       //L - length 4
    B0000111                                        //D - length 3
    };
  const byte ByteArrayLongShort[11] =   {
    B0001111,                                       //H = --- --- --- ---
    B0000001,                                       //E = o o o ---
    B0001011,                                       //L = --- o --- ---
    B0001011,                                       //L = --- o --- ---
    B0000000,                                       //O = o o o
    B0000000,                                       // (pause 7 intervals)
    B0000100,                                       //W = --- o o
    B0000000,                                       //O = o o o
    B0000101,                                       //R = --- o ---
    B0001011,                                       //L = --- o --- ---
    B0000011                                        //D = o --- ---
  };

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

void loop()
{
  for (byte x = 0; x < 10; ++x) {
   byte sound = ByteArrayMakeSound[x];
   byte longshort = ByteArrayLongShort[x];
   byte emptyvalue {B0000000};
    if (sound&emptyvalue) {
      delay(7 * interval);
    }    else    {
      for (byte y = 0; y < 7; ++y)  {
        if (sound & (1<<y)){
          if (longshort & (1<<y))     {
            MakeSound(3);
            delay(interval);
          }   else    {
            MakeSound(1);
            delay(interval);
          }
        }   else      {}
      }
    }
      delay(3 * interval);
  }
}

void MakeSound(int del) {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(interval * del);
  digitalWrite(LED_BUILTIN, LOW);
}

Note 1: Program purpose

The program started as a hello world program with me trying to write
  "hello world" in morse code with the builtin led. The two byte arrays
  store the "letter length" of the morse and the "daa" / "dit"
  assignment. I use empty bytes to separate words, which means a delay
  of 3 intervals (= length of "daa") should happen. Then including the
  entire letter-table of morse and a string to byte table conversion (to
  create the byte arrays). It is not very quick... But I am tinkering
  with moving the byte arrays into the flash memory. Just for Hello
  World it is fast enough, but the "daas" and the "dits" are slightly
  uneven so programming time is impacting performance.

@LookAlterno Thanks for the tip, let's hope Amazon delivers as quickly as stackexchange =)


text:
Reload only one variable in loop()
I need some information for the TFT screen 2.8 and arduino mega.
The screen works very well and displays the data.
The small problem I encounter is for the text display, the page is reloading every second and this makes a small black screen every second.
I would like to know if it was possible to reload only one part of the screen display?
See in video
https://youtu.be/vxSa6xkH0vU
My loop()
void loop(void) {
   tft.fillScreen(BLACK);
  unsigned long start = micros();
  tft.setCursor(0, 0);
  tft.setRotation(3);
  dt = clock.getDateTime();
  clock.forceConversion();

  // Go
  tft.println();
  tft.setTextColor(GREEN);
  tft.setTextSize(5);
  tft.println("Info");
  tft.println();
  tft.setTextSize(2);
  tft.println(clock.dateFormat("d-m-Y H:i:s", dt));
  tft.println();
  tft.setTextSize(2);
  tft.println("Temperature: ");
  tft.println(clock.readTemperature());

  delay(1000);
}

Don't do a fillscreen when you don't need to.

@ratchetfreak When i remove fillScreen this generates a dual display :/

You can use tft.rect(x,y,width,height) to clear only a portion of the screen. Make sure to set tft.fill before calling it.


text:
BMP 280 exact Altimeter readings
I was just going through this pressure sensor tutorial.
What I want to know is how can I set the exact altimeter in my readings depending upon my different geographical place ? or may be if I am attaching the sensor to my balloon.

If you can know an exact height at the start of the sketch (or maybe just assume 0m for start), you could save the starting pressure in setup(), then use that pressure (converted from Pa to hPa) to calibrate the loop() altitudes.

The tutorial sample source code has the line:
Serial.print(bmp.readAltitude(1013.25)); // this should be adjusted to your local forcase

That 1013.25 value should be the local pressure at sea level in hundreds of Pa. If want to show altitude above ground level, you will need to know that for your location and write your code to calculate the altitude offset.
The sensor can't know location -- it only measures pressure. The AdaFruit library provides the altitude conversion, but being generic, it relies on several assumptions.

The baromic pressure is at sea level. Every wheather station compensates the measured value. First of all, you have to know the height of the sensor. Start with a height map: http://www.ahn.nl/index.html and add something for how high the sensor is in your house. The Adafruit library https://github.com/adafruit/Adafruit_BMP280_Library/ does not have a function to correct the height. This is too complex: https://en.wikipedia.org/wiki/Barometric_formula This is simple: http://www.engineeringtoolbox.com/barometers-elevation-compensation-d_1812.html It is +7hPa for 61 meters.

What units is the output given as?

@DavidGlass Again, the Adafruit library example source code has a following line that indicates the unit is Meters.

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


text:
Communicating to arduino as fast as real-time
I'm trying to control some pneumatic cylinders with arduino. I want to do the calculations on pc and then send the command to arduino to control the air flow to pneumatic cylinders. It's very important that arduino receive these commands super fast (in real time if it's possible) so that I can control air flow in millisecond precision.
What is the fastest way to communicate to arduino (Read and write). I tested serial communication and it's very slow in compare to real-time. Is there any specific settings for serial communications that i need to do to increase it's speed? Should I use LAN connection? Or maybe I should use for example Arduino YUN with an OS?

Going over USB will add about a millisecond of jitter to your data in both the sensing and command directions.  Using a part with direct USB rather than then needing to go through a serial link from USB chip to processor could help limit what is added on top of that, but it will still be there.  If you could get a USB high speed solution that would reduce this as the polling interval is shorter, but there are few such solutions for simple microcontrollers.  Ultimately, USB is meant to move a lot of data in a reasonable amount of time - it is not designed to move small messages promptly.
True realtime systems put the processing and the actuation in tightly connected local circuitry. With the increasing isolation of PC processors from external I/O by multiple layers of intermediate architecture on the chip and motherboard, you see very little realtime use of PCs today.  An embedded board with a decent processor and good direct I/O (Beaglebone, maybe the Linux side of a Yun or comparable) would be better, but be aware that multi-tasking operating systems like Linux or Windows are fundamentally in conflict with real-time performance - it takes very complex hacks to make that work, for example running a realtime scheduler directly on the hardware  and having it run an ordinary operating system as a low priority task.
The architecturally cleanest solutions would be to find a way to fit your calculations on a fast single processor - in the realm of Arduino-style solutions perhaps one of the latest in the Teensy series.  Beyond that you are really out of the realm where this could be considered an Arduino question - trying for example to run a realtime scheduler on the Linux half of a Yun is really not related to "Arduino" at all.
One thing that is not clear however is if your system needs to react in real time, or merely to sequence with precise timing.  Mere sequencing is a far easier problem, as you can send the data a bit in advance of need and hold it in a buffer, so that communication latency doesn't delay operations.  A 3d printer could be an example of this - the really complex  calculations are done on a PC, then commands are drip-fed a bit in advance of need to a simpler executive traditionally running on a repackaged Arduino Mega, and that moves the motors with sub-millisecond pulse precision.  Given that there are no realtime inputs to the calculations, their results can also be stored on an SD card for use months later with no PC connection at all.  If your need does reduce to such pure non-reactive sequencing then things are a lot simpler; if it doesn't, then the rest of the explanation here applies.

You forgot to mention the Raspberry Pi. That is a computer running a (almost) normal version of linux with I/O.

@Jot I did not "forget", I quite specifically excluded the Raspberry Pi from this conceptual overview because it is architecturally ugly, with the undocumented proprietary coprocessor complicating things.  You also seem to be overlooking the difference between "Linux with I/O" and "Linux extended for realtime scheduling with low-latency I/O" - that may be possible on the pi with enough effort, but it's not your typical userspace write to /sys/class/gpio

You are right. Maybe EBAG can add more details to his question about a possible sequence and about the calculations.


text:
Getting no such directory file error when compiling
I recently got my wifi module and connected it to my Uno. I am now trying to send a http request. I have the code that comes with the esp8266wifi library in which it demonstrates and gives an example on how to send a http request. This is the code:
CODE.
I am getting the following error
    Arduino: 1.8.4 (Windows 8.1), Board: "Arduino/Genuino Uno"

In file included from C:\Users\Yasmeen\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFi.h:33:0,

                 from C:\Users\Yasmeen\AppData\Local\Temp\arduino_modified_sketch_200757\HTTPSRequest.ino:14:

C:\Users\Yasmeen\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory

 #include <queue.h>

                   ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

Obviously it seems to be an file path error but I'm not sure why. I've imported the library through the Arduino IDE.. But maybe the way I aquired the library was wrong? What I did was download the esp8266wifi folder (here) and zipped the file and imported it.. is that okay to do?

The ESP8266WiFi library is for programming the ESP8266 directly. You are trying to compile source code for the ESP8266 for the Arduino UNO, that obviously won't work.
A Beginner's Guide to the ESP8266


text:
error: espcomm_upload_mem failed when uploading a sketch
I am new to the whole arduino scene. I have connected my wifi module (esp8266 v01) to my arduino Uno like this:
http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/
And have downloaded the arduino ide framework so that I may be able to use the arduino IDE as opposed to sending AT commands through the serial monitor.
When trying to upload an example sketch that sends a http request that I found on github, I get the following error:
    Arduino: 1.8.4 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

Archiving built core (caching) in: C:\Users\Yasmeen\AppData\Local\Temp\arduino_cache_354217\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____9d1d735445f8d7bf19746e2177d24e71.a
Sketch uses 285417 bytes (65%) of program storage space. Maximum is 434160 bytes.
Global variables use 38688 bytes (47%) of dynamic memory, leaving 43232 bytes for local variables. Maximum is 81920 bytes.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

After looking online and researching, I can see that it has something got to do with flashing the firmware or something. I came across this question:
ESP8266 error: espcomm_upload_mem failed while uploading sketch
and the answer did say that he bought a converter.. what does this mean? Does it mean buying this?:
https://www.amazon.co.uk/gp/product/B06Y3FNGJF/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1
I really need help, been stuck on this for the past few days now and seriously contemplating whether to get the arduino wifi shield since it comes prebuilt with wifi.. even though it costs quite a lot!

Did you take note of the paragraph in your first link that reads And since we talked about the CH_PD pin, remember that if you want to flash the ESP8266 you should connect the GPIO0 pin to GND (blue line), which puts the ESP into flash mode.

@Majenko I am able to send AT commands with the module so should I not be in flash mode when trying to send a http request? Also, does flashing mean upgrading the firmware in the esp2866?

To solve the issue,do this
short the pin GPIO 0(D3) to ground using a jumper wire.
press reset button
upload the sketch
remove the jumper wire . Done!!!! Thanks for this note that solved my problem

The ESP8266 has two "modes". "Run" mode and "Flash" mode.  In "Run" mode the firmware installed onto the ESP8266 executes. The default firmware is the AT firmware that allows you to control the device with AT commands through serial.
Note that the site you link to has erroneous information about CH_PD that should be talking about GPIO0.
In "Flash" mode you get to upload new firmware (AKA a "sketch") to make the device do something different.
The basic programming sequence is:

Switch the device to Flash mode (connect GPIO0 to GND)
Upload the sketch using the IDE
Switch the device to Run mode (connect GPIO0 to 3.3V).

Because of these extra steps many people choose to invest in a small USB interface board designed specifically for programming the ESP8266 to make their life easier. These generally have a switch on them to set whether GPIO0 is connected to GND or 3.3V.

Thank you for the clarification. Really helps. I have connected the CH_PD to GND, I try to run the sketch but still pretty much get the same error: warning: espcomm_sync failed error: espcomm_open failed error: espcomm_upload_mem failed error: espcomm_upload_mem failed Not sure whats going wrong

Get an adaptor. It makes everything so much simpler. They're dirt cheap on eBay.

Would this adapter work?: https://www.amazon.co.uk/gp/product/B06Y3FNGJF/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

This is incorrect. CH_PD turns the chip on or off. I think you mean GPIO0

@tttapa I thought it was GPIO0 too, but the site linked to in the question says CH_PD.

@dfqupwndguerrillamailde Errr... no? That's not an ESP8266 USB adaptor. That's a logic level translator. What you are looking for has a USB plug on one end and a header for an ESP8266 on the other, with a switch in the middle.

@dfqupwndguerrillamailde It looks like the one in the picture in the answer you linked to.

@Majenko Am I right in thinking that the by switching the GPIO0 to GND and VCC is equivalent to getting that USB adapter? Also, I just changed the GPIO0 to GND, uploaded a blank sketch and it uploaded fine.. now I'm trying to upload the example code on github but now I'm getting the same error. I'll play around and try and upload it back

CHPD needs hard-wired to VCC, not ground. on ESP-01S modules, it's pre-wired for you.

By default, the ESP8266 runs the program in flash memory.
To upload new firmware over UART, you have to change the boot mode by connecting GPIO0 to ground during reset.
GPIO15 should be low and GPIO2 should be high during boot in both cases. GPIO needs an external pull-down resistor, the internal pull-up resistor for GPIO2 is enabled during boot, so you don't need to add an external one.
To prevent from shorting GPIO0 if it's used as an output in your sketch, it's recommended to add a series resistor to limit the current.

To upload a sketch:
1. press and hold the reset button
2. press and hold the program button
3. release the reset button, the ESP will boot in program mode
4. release the program button
5. upload the sketch
If your USB-to-Serial breaks out the RTS and/or DTR lines, you can automate the reset and programming mode procedures.

I had the same issue while uploading to the NodeMCU.
The issue was that the mode was not selected to program mode even after doing the below steps:

press and hold the reset button
press and hold the program button
release the reset button, the ESP will boot in program mode
release the program button
upload the sketch

To solve the issue, do this:

short the pin GPIO 0(D3) to ground using a jumper wire.
press reset button
upload the sketch
remove the jumper wire

Done!!!!

depending on the USB speed cable that you are using, sometimes this problem often occurs if I use a cable that is not suitable. if your com setting is 9600 then you have to set up upload speed in the tools menu -> upload speed faster than 9600 ... for exp: 57600.
this is should be work!!

at 9600 baud the upload starts but fails in the middle because of problems with the esptool used in Arduino esp8266 package until version 2.4.1 . starting 2.5.0 esptool.py is used

This is one of the simple solutions that worked for me:

Plug out the USB connection with the computer;
Hold the flash button on the nodemcu/esp8266;
Plug in the usb connection and quickly release the flash button;
Now try uploading the sketch.

Thank you.


text:
Arduino <<I2C>> ATtiny85 stops updating variables after a while
I've been working on a project for the last few days and spent a LOT of time googling, reading and testing. I'm kinda running out of ideas now and instead of bumping my head to the wall I thought posting my issue here in the hopes someone might be able to point me towards the right direction
I've got an Arduino UNO programmed as I2C Master and an ATtiny85 as an I2C slave. An single Adafruit Neopixel LED is attached to the slave.
When running the two sketches below everything actually works perfect.....for about a minute or so.
While during correct operations the Neopixel LED is actually changing color correctly and the serial monitor on the Uno shows the correctly updated R-G-B values, things change after about 1 minute of running.
The LED keeps blinking, which tells me the ATtiny is not frozen.
The UNO keeps sending I2C and is receiving I2C data...but the data is constant. The updated RGB that the Uno (master) has been sending to the ATtiny slave are somehow not handled (correctly) by the slave.
Any thoughts are more then appreciated. I'm totally lost and do not know which directions to go from here so any pointers would be more then welcome.
The Master - Arduino Uno -
#include <Wire.h>

#define I2C_MASTER_ADDR 0x04
#define I2C_SLAVE_ADDR 0x05

/*
* Software config
*/
int pollInterval = 700;//Milliseconds

//Demo's
#define demoLedInterval 150//In milliseconds
boolean demoRequest = false;

/*
* Internal variables
*/
unsigned long lastPoll = 0;

int demoLedState = 0;
unsigned long lastDemoLedUpdate = 0;

/*
* Setup function
*/
void setup()
{
 Wire.begin(I2C_MASTER_ADDR);  // join i2c bus (address optional for master)
 Serial.begin(115200);         // start serial for output
 Serial.println("Setup complete");
}

/*
* The main loop
*/
int i =0;
void loop()
{

 /*
  * Poll the slave
  */
 if( (millis()-lastPoll) > pollInterval)
 {
   /*
    *
    */
   int red=0; int green=0; int blue=0;

     if(i==0)
     {
       Serial.println("Write data to slave - set led red");
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC2);//Command
       Wire.write(0x00);
       Wire.write(255);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC3);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC4);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
     }
     if(i==1)
     {
       Serial.println("Write data to slave - set led green");
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC2);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC3);//Command
       Wire.write(0x00);
       Wire.write(255);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC4);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
     }
     if(i==2)
     {
       Serial.println("Write data to slave - set led blue");
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC2);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC3);//Command
       Wire.write(0x00);
       Wire.write(0);//Data
       Wire.endTransmission();
       Wire.beginTransmission(I2C_SLAVE_ADDR);
       Wire.write(0xC4);//Command
       Wire.write(0x00);
       Wire.write(255);//Data
       Wire.endTransmission();
     }

   i++; if(i>2) i =0;

   /*
    * General request (without data). Should return something though
    */
   Serial.println("General request for slave");
   Wire.requestFrom(I2C_SLAVE_ADDR, 7);//Request N bytes, N=byte_len
   delay(10);//Give the slave time to answer
   while (Wire.available())
   {
     uint8_t next_byte = Wire.read();
     Serial.print(next_byte);Serial.print(" ");
   }
   Serial.println("\n");

   lastPoll = millis();
 }//End if time to poll again

}//End loop

The Slave code - ATtiny 85 - Main file
#include <EEPROM.h>
#include <OneWire.h>
#include <TinyWireS.h>
#include <Bounce2.h>
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__ //Which will be true for ATtiny85
  #include <avr/power.h>
#endif

#define I2C_SLAVE_DEFAULT_ADDR 0x05

#include "namespaces.h"//Include at last to make sure all libs are present

//Software config
#define BUTTON_DEBOUNCE 5//Debounce milliseconds

//Hardware config
#define NEOPIXEL_PIN  1
#define BUTTON_PIN    3
#define DS2401_PIN    4

#define NUMPIXELS     1

/*
 * Initialize instances/classes
 */
Bounce button = Bounce();
Adafruit_NeoPixel neopixel = Adafruit_NeoPixel(NUMPIXELS, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800);
OneWire ds(DS2401_PIN);

void setup()
{
  uint32_t _now = millis();

  //Start I2C
  uint8_t _device_addr = EEPROM_DATA::get_device_addr();
  //TinyWireS.begin(_device_id);
  TinyWireS.begin(I2C_SLAVE_DEFAULT_ADDR);
  TinyWireS.onReceive(I2C::receiveEvent);
  TinyWireS.onRequest(I2C::requestEvent);

  //Start NeoPixel
  neopixel.begin();
  neopixel.setPixelColor(NUMPIXELS-1, neopixel.Color(255, 255, 255) );
  neopixel.show();

  //Start Button
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  button.attach(BUTTON_PIN);
  button.interval(BUTTON_DEBOUNCE);

}

unsigned long lastBlink = 0;
boolean lastBlinkState;

void loop()
{

  button.update();

  if(VARS::led_needs_update)
  {
    led_update();
    VARS::led_needs_update = false;
  }

  if(button.fell())
  {
    VARS::button_state = HIGH;
  }
  if(button.rose())
  {
    VARS::button_state = LOW;
  }

  //testblink
  if ( (millis()-lastBlink) > 600)
  {
    if(lastBlinkState)
    {
      neopixel.setPixelColor(NUMPIXELS-1, 0,0,0 );
      neopixel.show();
      lastBlinkState = false;
    }
    else
    {
      led_update();
      lastBlinkState = true;
    }
    lastBlink = millis();
  }

  // This needs to be here for the TinyWireS lib
  TinyWireS_stop_check();
}

/*
 * Helper functions
 */
void led_update()
{
  neopixel.setPixelColor(NUMPIXELS-1,
    VARS::led_red,
    VARS::led_green,
    VARS::led_blue
  );
  neopixel.show();
}

The Slave code - ATtiny 85 - namespaces.h
namespace VARS
{
  //These are available in a I2C response
  volatile boolean button_state = 0;
  volatile int led_red = 0;
  volatile int led_green = 0;
  volatile int led_blue = 0;
  uint8_t sn_family;
  uint8_t sn_bit1;
  //uint64_t serial_number = 0;
  //int I2C_response_max_length = 4;//Count the above

  //These are internal
  volatile boolean led_needs_update = false;
  int update_interval     = 300;
  unsigned long last_update = 0;
}

//===========================================================================

namespace EEPROM_DATA
{
  uint8_t default_device_addr   =     I2C_SLAVE_DEFAULT_ADDR;
  uint8_t this_device_address   =     0x05;

  bool device_addr_valid(uint8_t addr)
  {
    return (addr > 0x04 && addr < 0x7E);
  }
  bool store_device_addr(uint8_t new_device_addr)
  {
    if (!device_addr_valid(new_device_addr)) return false;//cancel if out of bounds. Assume corrupt data.
    EEPROM.write(EEPROM_DATA::this_device_address, new_device_addr);//Set new i2c address into EEPROM
    return true;
  }
  uint8_t get_device_addr()
  {
    uint8_t _addr = EEPROM.read(EEPROM_DATA::this_device_address);
    if (!device_addr_valid(_addr))
    {
      _addr = EEPROM_DATA::default_device_addr;
      store_device_addr(_addr); //update EEPROM with a valid/default device id.
    }
    return _addr;
  }
}

//===========================================================================

namespace COMMANDS
{
  enum {
    assign_new_device_addr  =     0xC1,
    set_led_red             =     0xC2,
    set_led_green           =     0xC3,
    set_led_blue            =     0xC4
  };
  bool do_command(uint8_t cmd, uint16_t cmd_data)
  {
    //interpret command.
    switch (cmd)
    {
      //set new i2c slave adress.
      //ATTENTION: After command is performed, the chip will need a hard reset.
      case COMMANDS::assign_new_device_addr:
        uint8_t new_device_addr;
        new_device_addr = uint8_t(cmd_data & 0x007F);//ensure the address is 7-bit.
        return EEPROM_DATA::store_device_addr(new_device_addr);//return true if saved, false if invalid address.
        break;

      case COMMANDS::set_led_red:
        //if (cmd_data > 0x00FF) break;//ignore out of range data. Assume corrupt packet.
        VARS::led_red = int(cmd_data);
        VARS::led_needs_update = true;
        break;

      case COMMANDS::set_led_green:
        //if (cmd_data > 0x00FF) break;//ignore out of range data. Assume corrupt packet.
        VARS::led_green = int(cmd_data);
        VARS::led_needs_update = true;
        break;

      case COMMANDS::set_led_blue:
        //if (cmd_data > 0x00FF) break;//ignore out of range data. Assume corrupt packet.
        VARS::led_blue = int(cmd_data);
        VARS::led_needs_update = true;
        break;
    }
  }
}

//===========================================================================
int pointer = 0;
namespace I2C{

  //Gets called when the ATtiny receives a general i2c data request.
  //Tx_stop is sent after end of call, so all bytes need to be sent before leaving.
  void requestEvent()
  {

//The number of bytes requested should NOT exceed the number of bytes returned
    TinyWireS.send( VARS::button_state );
    TinyWireS.send( VARS::led_red );
    TinyWireS.send( VARS::led_green );
    TinyWireS.send( VARS::led_blue );

  }

  //Gets called when the ATtiny recieves an i2c message THAT CONTAINS DATA from another device.
  void receiveEvent(uint8_t byte_count)
  {
    //first byte is command, next 2 bytes is data for command. Total must equal 3 bytes.
    if (!TinyWireS.available() || byte_count != 3 ) return;

    //retrieve the command and 16-bit data.
    //Incomming data is ordered CMD,Data-MSB,Data-LSB.
    uint8_t cmd = TinyWireS.receive();
    uint16_t cmd_data = (TinyWireS.receive() << 8);
    cmd_data += TinyWireS.receive();

    COMMANDS::do_command(cmd, cmd_data);
  }

}

Three packets of data are sent over the I2C bus, with no time to breathe for air for the Attiny85 in between. You could add delay(1) between sending the commands after Wire.endTransmission. The delay(10) after the Wire.requestFrom can be removed. The Wire.requestFrom does the waiting itself. The slave uses NeoPixel and OneWire. That is a big problem since both libraries turn off the interrupts for the timing specific protocol. That will always be in the way of interrupts. You could make the Attiny85 the master. How long are the wires ? https://sigrok.org/wiki/Supported_hardware#Logic_analyzers

millis() returns a long, but your pollInterval is an int.  Try pollInterval as a long to avoid an implied casting issue.  You do long to int comparisons in other places as well.

Dennis Hunink, what is happening ? You ask a very specific question. I mentioned a timing/interrupt problem which could be the problem. But then you don't respond anymore.

@Jot real life happend  I did not had time to post the final answer until just now. But I did found a solution thanks to your very specific suggestions. Thanks so much for that. The timing and interrupts proved to be the essential factors here. So basically your comment saved my life
(wires are about 20CM so no issues there; turned out to be purely software)

After diving into interrupts, timing etc I did found the solution.
Thanks for all the suggestions, in particular to @Jot!
In the end I took the following steps:
- adding a 1ms delay after each Wire.endTransmission()
- dropped the Neopixel lib (https://github.com/cpldcpu/light_ws2812)
Below is the final code, for anyone interested.
There is still an issue with this code: requesting multiple bytes from the slave always results in receiving just a single byte. But since that's most likely unrelated to the original question I'm opening a new topic for that (if I really can't find a solution myself, that is).
Master
/*
 *
 */

#include <Wire.h>

#define I2C_MASTER_ADDR 0x04
#define I2C_SLAVE_ADDR 0x05

/*
 * Software config
 */
int pollInterval = 700;//Milliseconds

/*
 * Internal variables
 */
unsigned long lastPoll = 0;

/*
 * Setup function
 */
void setup()
{
  Wire.begin(I2C_MASTER_ADDR);  // join i2c bus (address optional for master)
  Serial.begin(115200);         // start serial for output
  Serial.println("Setup complete");
}

/*
 * The main loop
 */
int i = 0;
void loop()
{

  /*
   *
   */
  if( (millis()-lastPoll) > pollInterval)
  {
    Serial.println("Write data to slave");
    Wire.beginTransmission(I2C_SLAVE_ADDR);
    Wire.write(0x01);//Register to start at
    switch(i)
    {
      case 0:
        Wire.write(255);
        Wire.write(0);
        Wire.write(0);
        i++;
        break;
      case 1:
        Wire.write(0);
        Wire.write(255);
        Wire.write(0);
        i++;
        break;
      case 2:
        Wire.write(0);
        Wire.write(0);
        Wire.write(255);
        i = 0;
        break;
    }
    Wire.endTransmission();
    delay(1);//Dont let the slave panic

    //Set the register pointer back to 0x01
    Wire.beginTransmission(I2C_SLAVE_ADDR);
    Wire.write(0x00);//Register to start at
    Wire.endTransmission();
    delay(1);//Dont let the slave panic

    //Get values from the three registers up form 0x01
    Wire.requestFrom(I2C_SLAVE_ADDR, 6);//Request N bytes
    while (Wire.available())
    {
      uint8_t next_byte = Wire.read();
      Serial.print(next_byte);Serial.print(" ");
    }
    Serial.println("\n");

    lastPoll = millis();
  }//End if time to poll again

}//End loop

Slave
#include <EEPROM.h>
#include <OneWire.h>
#include <TinyWireS.h>
#include <Bounce2.h>
#include <WS2812.h>
#ifdef __AVR__ //Which will be true for ATtiny85
  #include <avr/power.h>
#endif

//Software config
#define I2C_SLAVE_DEFAULT_ADDR 0x05
#define BUTTON_DEBOUNCE 5//Debounce milliseconds

//Hardware config
#define NEOPIXEL_PIN  1
#define BUTTON_PIN    3
#define DS2401_PIN    4

#define NUMPIXELS     1

/*
 * I2C Registers
 *
 * Register map:
 * 0x00 - Button state
 * 0x01 - led value red
 * 0x02 - led value green
 * 0x03 - led value blue
 * 0x04 - SerialNumber - Family (byte 0)
 * 0x05 - SerialNumber - Byte 1
 * 0x06 - SerialNumber - Byte 2
 * 0x07 - SerialNumber - Byte 3
 * 0x08 - SerialNumber - Byte 4
 * 0x09 - SerialNumber - Byte 5
 * 0x10 - SerialNumber - Byte 6
 * 0x11 - SerialNumber - CNC (byte 7)
 *
 * Total size: 12
 */
const byte reg_size = 12;
volatile uint16_t i2c_regs[reg_size];

/*
 * Internal variables
 */
cRGB value;
volatile boolean led_needs_update = false;
volatile byte reg_position;

/*
 * Initialize instances/classes
 */
Bounce button = Bounce();
WS2812 led(NUMPIXELS);

void setup()
{
  //Start I2C
  //uint8_t _device_addr = EEPROM_DATA::get_device_addr();
  TinyWireS.begin(I2C_SLAVE_DEFAULT_ADDR);
  TinyWireS.onReceive(i2cReceiveEvent);
  TinyWireS.onRequest(i2cRequestEvent);

  //Start Led
  led.setOutput(NEOPIXEL_PIN);
  value.b = 255; value.g = 0; value.r = 0;
  led.set_crgb_at(0, value); //Set value at LED found at index 0
  led.sync(); // Sends the value to the LED

  //Start Button
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  button.attach(BUTTON_PIN);
  button.interval(BUTTON_DEBOUNCE);

}

void loop()
{
  button.update();

  if(led_needs_update)
  {
    led_update();
    led_needs_update = false;
  }

  if(button.fell())
  {
    i2c_regs[0x00] = true;
  }
  if(button.rose())
  {
    i2c_regs[0x00] = false;
  }

  // This needs to be here for the TinyWireS lib
  TinyWireS_stop_check();

}

/*
 * I2C Handelers
 */
void i2cReceiveEvent(uint8_t howMany)
{
    if (howMany < 1)
    {
        return;// Sanity-check
    }

    reg_position = TinyWireS.receive();
    howMany--;
    if (!howMany)
    {
        return;// This write was only to set the buffer for next read
    }

    while(howMany--)
    {
        //Store the recieved data in the currently selected register
        i2c_regs[reg_position] = TinyWireS.receive();

        //Proceed to the next register
        reg_position++;
        if (reg_position >= reg_size)
        {
            reg_position = 0;
        }
    }
    led_needs_update = true;
}//End i2cReceiveEvent()

void i2cRequestEvent()
{
    //Send the value on the current register position
    //NOT WORKING when requestin multiple bytes
    //TinyWireS.send(i2c_regs[reg_position]);

    //WORKAROUND
    int n = reg_size - reg_position;//Number of registers to return
    for(int i = reg_position; i < n; i++)
    {//Return all bytes from the reg_position to the end
      TinyWireS.send(i2c_regs[i]);
    }

    // Increment the reg position on each read, and loop back to zero
    reg_position++;
    if (reg_position >= reg_size)
    {
        reg_position = 0;
    }
}//End i2cRequestEvent

/*
 * Helper functions
 */
void led_update()
{
  cRGB val;
  val.r = i2c_regs[0x01];
  val.g = i2c_regs[0x02];
  val.b = i2c_regs[0x03];
  led.set_crgb_at(0, val);
  led.sync(); // Sends the value to the LED
}

I'm glad it is working better. I don't know why only a single byte is received. I can't see that in the code. The WS2812 RGB leds need that specific timing protocol. Looking at the light_ws2812.c source code, it also turnes off interrupts. I have an Arduino Uno as a slave and a DHT22 sensor connected to it. The DHT22 also have a timing protocol and turn off the interrupts. My solution was to remove the disabling of interrupts, and let the DHT22 library run every few seconds and simply ignore the wrong ones. It has a checksum, so that was a lot easier than a RGB led.

Yeah to be perfectly honest I do believe that the primary fix was adding the delay(1) after each write. After switching from Neopixel to WS2812 lib I did found that interrupts were still affected. Looks like that's a requirement for the chips. So I am thinking a lot on how to make the I2C communication more reliable, even when affected due to interruptes. checksum is perfect, but even with RGB values there has to be a way. And it not, we will find a way :0
On the other hand, implementing a checksum should not be that hard...

About the single byte that is received: is that a know limitation of the TineWireS ? That only one byte at a time can be send per request ?

That’s what I’ve been trying to figure out, without luck so far. The source code is just a bit to complicated for me to give a definitive answer. But the inline commands on github suggest there should not be such a limitation...

@Jot after spending a lot more time on reading through the TinyWireS lib over and over again I do think sending multiple bytes should be possible. As I am officially stuck now, I've openend a issue here: https://github.com/rambo/TinyWire/issues/36


text:
Can I control two coreless DC motors using L293DD SMD IC?
I wish to control two 3.7V 6x12mm Coreless DC motors (both direction and speed individually). The only constraint is that the motor driver (circuit) has to be as small as possible.
I've seen couple of driver circuits used in quadcopters where a single FET (such as IRLML2502) is used to control the speed of coreless motors. However, the direction control is not possible with such a circuit.

It requires at least 6 MOSFETs and maybe Schottky diodes to prevent back EMF (similar to half H-bridge like here). Even after this, opposite direction control for two motors at once cannot be achieved. Then I figured all of this will increase the area required and decided to replace it with L293DD IC. Now my question is:

Can the L293DD SMD IC be used to control these motors?
Is there an alternate solution/circuit/IC which can minimize the size and area?
Are ESCs required for these small coreless motors? Can they be controlled directly via the L293DD (like normal motors)?

PS: The controller will be ESP8266 and the entire system will powered by a 3.7V 300mAh LiPo battery.

Hopefully you are not trying to build a miniature aircraft; if you are look at what is actually used - not IC drivers, and not wifi.

Its more like a terrestrial mini bot, thus I need direction control as well for motors.

I'm voting to close this question as off-topic because it is entirely about motor drivers and not an at all about Arduino.

Can the L293DD SMD IC be used to control these motors?

Yes

Is there an alternate solution/circuit/IC which can minimize the size and area?

Any of the more modern MOSFET based H-Bridge drivers that exhibit far less loss than the antiquated l293d

Are ESCs required for these small coreless motors?

No

Can they be controlled directly via the L293DD (like normal motors)?

Yes
The L293 is old and, well, basically crap. For efficient battery based operation you realy need to be looking for something a little more modern and efficient. There's length to choose from - take a look on your favourite electronics supplier (which means not Amazon...)

I just checked the L293DD datasheet and it says the minimum operating voltage is 4.5V, whereas my system is powered by 3.7V battery and 3.3V logic. Could you suggest some MOS based drivers that work at 3.3V logic?

Not off hand, no. Use the parametric search facilities of your favourite electronics supplier.

Thanks! I think I'll go with the DRV8836 dual H-bridge driver. Comes in a nice 2x3mm package!


text:
ESP8266 and Python Communication
I'm new to networking and working with ESP8266. I have successfully setup my ESP8266 and can program it from Arduino IDE (tested a blinky code).
I want to send some data from a Python script running on my PC to ESP8266. Similar to a setup where use PySerial in Python, open a COM port and send my serial data to an Arduino. Arduino will parse my data bytes and will perform some action. Now, I am trying to achieve the same with ESP8266 and UART replaced with wireless communication.
First, I would like to connect my PC to ESP which will have its own SSID and password. Once connected, I would like to send my data bytes from Python script to ESP8266 wirelessly. Now, similarly, ESP will parse this received data and perform some function (like control its GPIOs).
How can I achieve this? It seems like a pretty simple task, but I'm really confused with what mode I've to use (AP? Client? Server?). What protocol for communication is the best (TCP? MQTT?). What do functions like Handle client/root do? I understand I've to use socket programming on Python, how to do that specifically in my case? How do I buffer my incoming data on ESP, so that I don't miss the bytes?
Could anyone please explain using an analogy with wireless communication and UART? Any links to tutorials will be helpful too. There are some tutorials online where they do this using a HTTP server and control the GPIOs from the browser, but no, I don't want this. I just simply want to send my data as I would with COM Port/UART/Arduino!

as a web dev, i find http to be the simplest interaction method: a clear req/res cycle, built-in parsers for GET params, status codes, easy debugging from other devices, etc. with streams, you have to sniff a lot out.

Check my project: "Esp 2 Python"
https://github.com/KebabLord/esp_to_python
The theori is you can create a localhost and get the sensor data or manage the module through arduino requests or urllib modules with a simple local mDNS server. This project allows you to control and read ESP.

I couldn't get your code to work

it was a literal soup, I radically simplified it, it's too easy to use now, try it again :3

The simplest IP equivalent to UART is TCP/IP sockets.  Create a listening socket on the ESP8266 and connect to it from the PC (or do it the other way around if you like). Data fed in one end comes out the other - just like a serial port.
There's examples with the ESP8266 core that do just that.

You must configure the ESP as an AP, if you want it to have its own IP.
You then set up a tcp-server on the ESP (i think there are example functions in the IDE).
Keep in mind, that the communication (server/client you mentioned) has nothing to do with the way PC and ESP are connected with (whether the ESP is providing an Access Point or logged into your WiFi). Those are different protocol layers, which means you will not need to make any changes if you want PC and ESP communicate over your router at all.
Actually the ESP (or at least for the ESP8266-12F I know for sure) is capable of running both ap and wificlient at the same time.
It's not a big difference to serial communication, you will need to poll for incomming messages in your loop if you want to run a server. Sending messages to your PC is like printing to the serial interface.


text:
Arduino IDE loses programmer after installing Visual Micro
I had this added to programmers.txt
mysmartusb.name=mySmartUSB light
mysmartusb.communication=serial
mysmartusb.protocol=stk500v2
mysmartusb.program.protocol=stk500v2
mysmartusb.program.tool=avrdude
mysmartusb.program.extra_params=-P{serial.port}

And was getting so annoyed with the loading time of Arduino IDE 1.8.5 so I tried Visual Micro but that didn't go well either. Now, Arduino IDE can no longer see my programmer. Tried rebooting, did a search for all programmer.txt files on the C: and deleted/updated as I thought appropriate. Has anyone else ever had that issue and if so, how did they solve it?

Uninstalled and installed 1.9.0 as I heard that fixes the launch time (it does). I'm aware it's beta but it fixed my issue. I assume reinstalling 1.8.5 would've also gotten me my programmer back.


text:
Trying to show g++ (linter-gcc for Atom) where to find Arduino libs
I'm trying to use Atom as an IDE for arduino and arduino-based boards.
I'm using arduino-cli for compilation and avrdude for upload, and now I'm trying to use linter-gcc for linting.
g++ is running and the linter seems to be working ok, but it's can't find built in libs.  I've added:
"C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\*"

to my GCC include paths, I've also tried copying the lib sources to my working directory, but I'm still getting (e.g.):
SPI.h: No such file or directory

Any ideas why gcc isn't seeing SPI.h?

If you are using Atom, why not just download Platform.io running on Atom as your Arduino IDE? It saves you all the trouble of using arduino-cli

TBH I don't want all the weight of Platform.io - I have my toolchain well established with avrdude etc and to my knowledge the platform.io environment is really set up for serial programming of prototype boards like Arduinos rather than my ICSP programming and fuse-setting of mostly custom short-run boards.


text:
Arduinos using I2C reading integers wrong
I have two Arduino unos, and I am using I2C to have them communicate with each other. The A4, A5, and GND of each Arduino is connected to the other. These are my functions:
On the sending Arduino:
void playNote(int pitch, int len, int location){
  Serial.println(String(String(location) + ":" + String(pitch) + "," + String(len) + "\n"));
  Wire.beginTransmission(location);
  Wire.write(pitch);
  Wire.write(len);
  Wire.endTransmission();
}

On the receiving Arduino:
void receiveEvent(int howMany){
  int pitch = Wire.read();
  int len = Wire.read();
  Serial.println("Pitch: " + String(pitch) + ", Length: " + String(len));
  playNote(pitch,len);
}

pitch always sends fine. When I send len as 150, it works and is received as 150. However, when len is sent as 300, it is received as 44. I cannot figure out why this is. Any help is appreciated.

wire.write(n) sends a single byte of value n
150 decimal = 96 Hex
300 decimal = 012C Hex ...so is 2 bytes, and is truncated to one byte of value 2C Hex.
2C Hex = 44 decimal
Send a single byte! Maximum value of a byte is 255 decimal
If you need to send multiple Len bytes, then you need to ascertain the number of bytes and send them individually.
In your code you send multiple bytes concatenated one after the other already ...you send Pitch followed by Len.
All you need to do is split Len into L1, L2 bytes first.
L1 = Len and xFF
Shift Len left or do other logical math to derive high byte, L2
Then send L1 and L2

You simply need to split Len into discrete bytes, send sequentially and reassemble at the Rx.

https://www.arduino.cc/en/Reference/WireWrite

it is not really true that you need to send them individually, there is also a form of write() which takes a pointer and count.  Since both receiver and transmitter have the same means of encoding an int, you can do this directly using a pointer to it, and of course the applicable size of an int which under avr-gcc is 2 bytes.

@ChrisStratton....of course that's true but I wanted to keep it simple for the OP using wire.write() as I assumed the OP was new to this. Had he/she looked up the documentation it would have been clear.


text:
Minimum number of Pins to use for multiplexing LEDs
whats the minimum number of pins to use when multiplexing 6 LEDs?
is there some kind of formula that can be applied to n LEDs?
Or in other words, how many LEDs can an Arduino Uno control without the help of a separate IC?

It depends on the style of multiplexing.
For basic Row-Column multiplexing you have N=RC - the number of LEDs is the number of rows multiplied by the number of columns. The LEDs, of course, don't have to be arranged physically in rows and columns, those are purely logical wiring concepts.
For Charlieplexing (used by the LOL shield) it's slightly more complex. The formula is: N = n² - n, where n is the number of pins, and N is the number of LEDs they can drive.
Charlieplexing can multiplex far more LEDs than traditional R/C multiplexing, but is harder to program for and wire up.

So concretely (to answer precisely OP), 5 pins (3+2) are needed with multiplexing (not a big gain, given extra code complexity), and 3 pins for charlieplexing.


text:
SendCommand(Key) function is not working properly using digitalWrite()
I finally figured out to get the unique value from the Car's Head panel input and send the command to the JVC radio as per the input.
Everything seems to be working fine, just the problem is the SendCommand(Key) function is not working properly as expected. It works sometimes, like sometimes I have to click the button twice or thrice to make it work, sometimes it works in the first time and some times it works twice even if i pressed it once...
But every times it shows that the key is there using Serial.println(Key) function... and it has been sent to the function SendCommand(Key) but still it doesn't works every time...
So just want to know that is there anything wrong in the code...
#include <SoftwareSerial.h>

SoftwareSerial mySerial(7, 5); // RX, TX
String readString;

//JVC Controls
#define VOLUP       0x04
#define VOLDOWN     0x05
#define SOURCE      0x08
#define EQUALIZER   0x0D
#define MUTE        0x0E
#define TRACKFORW   0x12
#define TRACKBACK   0x13
#define FOLDERFORW  0x14
#define FOLDERBACK  0x15
#define UNKNOWN1    0x37
#define UNKNOWN2    0x58

// Connect optocoupler input through a 1k resistor to this pin
#define OUTPUTPIN   8 // D8
// On-board LED, useful for debugging
#define LEDPIN     13 // D13
// Pulse width in µs
#define PULSEWIDTH 527
// Address that the radio responds to
#define ADDRESS 0x47
void setup()
{
  Serial.begin(57600);
  //Serial.setTimeout(2000);
  mySerial.begin(9600);
  pinMode(OUTPUTPIN, OUTPUT);    // Set the proper pin as output
}

unsigned char GetInput(int number, int prevNumber)
{
  if(number == 143)
    return TRACKBACK;
    else if(number == 140)
    return TRACKFORW;
    else if(number == 142)
    return FOLDERBACK;
    else if(number == 139)
    return FOLDERFORW;
    else if(number == 1)
    return VOLUP;
    else if(number == 255)
    return VOLDOWN;
    else if(number == 60)
    return MUTE;
    else if(prevNumber == 52 && (number == 32 || number == 37 || number == 38))
    return SOURCE;

    return 0;
}

 int prevNumber=0;
void loop() {

  while (mySerial.available()) {
    delay(10);
    int number = mySerial.read();
    mySerial.flush();
      unsigned char Key = GetInput(number, prevNumber);  // If any buttons are being pressed the GetInput() function will return the appropriate command code
      if (Key) {  // If no buttons are being pressed the function will have returned 0 and no command will be sent
        Serial.println(Key);
        SendCommand(Key);
    }
    prevNumber = number;

}
}

// Send a value (7 bits, LSB is sent first, value can be an address or command)
void SendValue(unsigned char value) {
  unsigned char i, tmp = 1;
  for (i = 0; i < sizeof(value) * 8 - 1; i++) {
    if (value & tmp)  // Do a bitwise AND on the value and tmp
      SendOne();
    else
      SendZero();
    tmp = tmp << 1; // Bitshift left by 1
  }
}
// Send a command to the radio, including the header, start bit, address and stop bits
void SendCommand(unsigned char value) {
  unsigned char i;
  Preamble();                         // Send signals to precede a command to the radio
  for (i = 0; i < 3; i++) {           // Repeat address, command and stop bits three times so radio will pick them up properly
    SendValue(ADDRESS);               // Send the address
    SendValue((unsigned char)value);  // Send the command
    Postamble();                      // Send signals to follow a command to the radio
  }
}
// Signals to transmit a '0' bit
void SendZero() {
  digitalWrite(OUTPUTPIN, HIGH);      // Output HIGH for 1 pulse width
  digitalWrite(LEDPIN, HIGH);         // Turn on on-board LED
  delayMicroseconds(PULSEWIDTH);
  digitalWrite(OUTPUTPIN, LOW);       // Output LOW for 1 pulse width
  digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
  delayMicroseconds(PULSEWIDTH);
}
// Signals to transmit a '1' bit
void SendOne() {
  digitalWrite(OUTPUTPIN, HIGH);      // Output HIGH for 1 pulse width
  digitalWrite(LEDPIN, HIGH);         // Turn on on-board LED
  delayMicroseconds(PULSEWIDTH);
  digitalWrite(OUTPUTPIN, LOW);       // Output LOW for 3 pulse widths
  digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
  delayMicroseconds(PULSEWIDTH * 3);
}
// Signals to precede a command to the radio
void Preamble() {
  // HEADER: always LOW (1 pulse width), HIGH (16 pulse widths), LOW (8 pulse widths)
  digitalWrite(OUTPUTPIN, LOW);       // Make sure output is LOW for 1 pulse width, so the header starts with a rising edge
  digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
  delayMicroseconds(PULSEWIDTH * 1);
  digitalWrite(OUTPUTPIN, HIGH);      // Start of header, output HIGH for 16 pulse widths
  digitalWrite(LEDPIN, HIGH);         // Turn on on-board LED
  delayMicroseconds(PULSEWIDTH * 16);
  digitalWrite(OUTPUTPIN, LOW);       // Second part of header, output LOW 8 pulse widths
  digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
  delayMicroseconds(PULSEWIDTH * 8);
  // START BIT: always 1
  SendOne();
}
// Signals to follow a command to the radio
void Postamble() {
  // STOP BITS: always 1
  SendOne();
  SendOne();
}

Won't you timings be off because you are doing two digtalWrite before delaying for the number of pulse widths.  Does that matter?

Hi... thanks for helping... but the thing is I dont understand this coding.. I am using it for my car... so it will be helpful if you can help me with the exact code... then I will run it and then let you know...

If you want to use the code you are going to need to understand it.  You are calling delayMicroseconds(PULSEWIDTH * 16); which means you are waiting for a very specific amount of time eg 8432 microseconds.  I assume your receiver will need a delay of 8432us not 8479us because you have called the function digitalWrite() twice before delaying.  So the question is do you need to reduce the delay by X microseconds because of the calls to digitalWrite()?  (I don't know what X is)

Then what should i do... ? Should i remove the function delayMicroseconds or reduce the value in that or add delayMicroseconds after each digitalWrite function... ?

You need to read the requirements of the receiver and see what you should do.


text:
Arduino Nano, Uno and Mega - XBee connection difference
I have a simple sketch working on arduino Uno and Nano sending data using an XBee.
However, if I run the project on an Arduino Mega it does not work.
What differences between Uno/Nano and the Mega could be causing issues?
Connection:  I just connect 3.3V->3.3V, Gnd->Gnd, and have tried various ports for DIN and DOUT (normally pins 2/4, but have tried A0/A1, 22/23 etc..).
Sketch: pastebin
Have brought a second Mega in case of hardware faults, but the problem persists.  Have stripped anything which might be tying up a timer.  Am choosing the right board type in the arduino IDE.

Update: changing the sketch to use HardwareSerial works, but I'd like to understand what's different between the devices here.

Not all arduino Mega pins support 'change interrupts', which is needed for Software Serial.  Only the following can be used for RX:
10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

Mega has 4 hardware serial ports, no excuse to be using software serial.


text:
functions not running
I have the following code as part of my efforts to clean this all up into more neatly organised functions.
I'm trying to run GetTemperatures and RunSerial as part of the main loop, however neither are being called.
If I uncomment the two code blocks I've tried to migrate into the functions in the main loop and comment out the calling of those two new functions, everything works ok.
I've looked through the arduino documentation and other places online but I'm unable to see where I've gone wrong.
#include <OneWire.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

//#include <DallasTemperature.h>

const char* ssid = "ssid";
const char* password = "password";

//This sketch is for Wemos R1 not Arduino
//Pin Assignment
OneWire  ds(D6);

//Digital Pin 4 Fan PWM pins)
int FanPin = D7; //Pin 4
int FanPWM = 0; //Start fans at max speed
int FanPercent = 100; // PWM power %

//Temperature thresholds

int Set0PCTemp = 26;   // Temp for 0% fan speed
//int MidTemp = 30;   // Max Temp for Min & Min Temp for Max
int Set100PCTemp = 36;   // Temp for 100% fan speed

// Temperature measurements

float MeasTemp;       //Measured temperature value
float DStemp;         //Value extracted from DS18B20 Sensor

// Serial port input values
int In0PCTemp;
int In100PCTemp;

ESP8266WebServer server(80);

void setup(void)
  {
  //analogWriteFreq(25000);
  pinMode(FanPin, OUTPUT);
  analogWrite(FanPin, 128);
  delay(1000);
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED)
    {
    delay(500);
    Serial.print(".");
    }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if (MDNS.begin("esp8266"))
    {
    Serial.println("MDNS responder started");
    }
    server.on("/", handleRoot);
    server.on("/inline", []()
      {
      server.send(200, "text/plain", "this works as well");
      }
              );
    server.onNotFound(handleNotFound);
    server.begin();
    Serial.println("HTTP server started");
    //wifi end
    }

void handleRoot()
  {
  //declare CSV variables
  String CSVHeaders = "Set0PCTemp,Set100PCTemp,MeasTemp,FanPercent,FanPWM";
  String CSVMessage = "";
  String CSVPayload = "";
  //  Compile CSV variables
  //CSVMessage = Set0PCTemp + "," + Set100PCTemp + "," + MeasTemp + "," + FanPercent + "," + FanPWM;
  CSVMessage += Set0PCTemp;
  CSVMessage += ",";
  CSVMessage += Set100PCTemp;
  CSVMessage += ",";
  CSVMessage += MeasTemp;
  CSVMessage += ",";
  CSVMessage += FanPercent;
  CSVMessage += ",";
  CSVMessage += FanPWM;
  CSVPayload = CSVHeaders;
  CSVPayload += "\n";
  CSVPayload += CSVMessage;
  //  char CSV_Payload[] = CSVPayload;
  //notify serial port of HTTP request
  Serial.println( "Sending Readings");
  Serial.println(CSVPayload);
  server.send(200, "text/plain", CSVPayload);
  }

void handleNotFound()
  {
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++)
    {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }
  server.send(404, "text/plain", message);
  }

void GetTemperature ()
  {
    Serial.println("step1");
  //original
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float DStemp;
  //////
  if ( !ds.search(addr))
    {
    Serial.println("step2");
    ds.reset_search();
    delay(250);
    return;
    }
  if (OneWire::crc8(addr, 7) != addr[7])
    {
    Serial.println("CRC is not valid!");
    return;
    }
    // the first ROM byte indicates which chip
    switch (addr[0])
      {
      case 0x10:
      type_s = 1;
      break;
      case 0x28:
      type_s = 0;
      break;
      case 0x22:
      type_s = 0;
      break;
      default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
      }
    Serial.println("step3");
    ds.reset();
    ds.select(addr);
    ds.write(0x44, 1);        // start conversion, with parasite power on at the end
    delay(1000);
    present = ds.reset();
    ds.select(addr);
    ds.write(0xBE);         // Read Scratchpad
    for ( i = 0; i < 9; i++)
      {
      data[i] = ds.read();
      }
    // Convert the data to actual temperature
    int16_t raw = (data[1] << 8) | data[0];
    if (type_s)
      {
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10)
        {
        raw = (raw & 0xFFF0) + 12 - data[6];
        }
      }
    else
      {
      byte cfg = (data[4] & 0x60);
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      }
  DStemp = (float)raw / 16.0;
  }

void RunSerial()
  {
        Serial.print(Set0PCTemp);
    Serial.print(",");
    Serial.print(Set100PCTemp);
    Serial.print(",");
    Serial.print(DStemp);
    Serial.print(",");
    MeasTemp = DStemp;
    //control fan speed
    //if(MeasTemp < Set0PCTemp)
     //{
     // if temp is lower than minimum temp
       //FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 255, 0); // the actual speed of fan
       FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 1023, 0); // the actual speed of fan
       //FanPWM = constrain(FanPWM, 0, 255);
       FanPWM = constrain(FanPWM, 0, 1023);
       analogWrite(FanPin, FanPWM);  // spin the fan at the fanSpeed speed
       //FanPercent = map(FanPWM,0,255,100,0);
       FanPercent = map(FanPWM,0,1023,100,0);
       Serial.print(FanPercent);
       Serial.print(",");
       Serial.println(FanPWM);
       //Serial.println(CSVMessage);
       //}
       //take temperature threshold input
      while (Serial.available() > 0)
        {
        int In0PCTemp = Serial.parseInt();
        int In100PCTemp = Serial.parseInt();
        if (Serial.read() == '\n')
          {
          In0PCTemp = constrain(In0PCTemp, 20, 35);
          In100PCTemp = constrain(In100PCTemp, 35, 50);
          Serial.print("Min=");
          Serial.print(In0PCTemp);
          Serial.print(",");
          Serial.print("Max=");
          Serial.print(In100PCTemp);
          Serial.println();
          Set0PCTemp = In0PCTemp;
          Set100PCTemp = In100PCTemp;
          }
      }
  }

void loop(void)
  {
    GetTemperature;
  //start of GetTemperature content
  /*
  Serial.println("step1");
  //original
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float DStemp;
  //////
  if ( !ds.search(addr))
    {
    Serial.println("step2");
    ds.reset_search();
    delay(250);
    return;
    }
  if (OneWire::crc8(addr, 7) != addr[7])
    {
    Serial.println("CRC is not valid!");
    return;
    }
    // the first ROM byte indicates which chip
    switch (addr[0])
      {
      case 0x10:
      type_s = 1;
      break;
      case 0x28:
      type_s = 0;
      break;
      case 0x22:
      type_s = 0;
      break;
      default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
      }
    Serial.println("step3");
    ds.reset();
    ds.select(addr);
    ds.write(0x44, 1);        // start conversion, with parasite power on at the end
    delay(1000);
    present = ds.reset();
    ds.select(addr);
    ds.write(0xBE);         // Read Scratchpad
    for ( i = 0; i < 9; i++)
      {
      data[i] = ds.read();
      }
    // Convert the data to actual temperature
    int16_t raw = (data[1] << 8) | data[0];
    if (type_s)
      {
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10)
        {
        raw = (raw & 0xFFF0) + 12 - data[6];
        }
      }
    else
      {
      byte cfg = (data[4] & 0x60);
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      }

    //Display current values
    DStemp = (float)raw / 16.0;
    */
    //end of GetTemperature content
    RunSerial;
    //start of RunSerial content
    /*
    Serial.print(Set0PCTemp);
    Serial.print(",");
    Serial.print(Set100PCTemp);
    Serial.print(",");
    Serial.print(DStemp);
    Serial.print(",");
    MeasTemp = DStemp;
    //control fan speed
    //if(MeasTemp < Set0PCTemp)
     //{
     // if temp is lower than minimum temp
       //FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 255, 0); // the actual speed of fan
       FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 1023, 0); // the actual speed of fan
       //FanPWM = constrain(FanPWM, 0, 255);
       FanPWM = constrain(FanPWM, 0, 1023);
       analogWrite(FanPin, FanPWM);  // spin the fan at the fanSpeed speed
       //FanPercent = map(FanPWM,0,255,100,0);
       FanPercent = map(FanPWM,0,1023,100,0);
       Serial.print(FanPercent);
       Serial.print(",");
       Serial.println(FanPWM);
       //Serial.println(CSVMessage);
       //}
       //take temperature threshold input
      while (Serial.available() > 0)
        {
        int In0PCTemp = Serial.parseInt();
        int In100PCTemp = Serial.parseInt();
        if (Serial.read() == '\n')
          {
          In0PCTemp = constrain(In0PCTemp, 20, 35);
          In100PCTemp = constrain(In100PCTemp, 35, 50);
          Serial.print("Min=");
          Serial.print(In0PCTemp);
          Serial.print(",");
          Serial.print("Max=");
          Serial.print(In100PCTemp);
          Serial.println();
          Set0PCTemp = In0PCTemp;
          Set100PCTemp = In100PCTemp;
          }
      }
      */
      //end of RunSerial content
      //wifi
      server.handleClient();
  }

RunSerial;

that does not call the function. Instead you should do
RunSerial();

same with GetTemperature

Depends on the compiler warning level, of course ... warning: statement is a reference, not call, to function 'getTemperature' [-Waddress]

What does that have to do with the code in the question?

Anything you write in C++ is happily accepted by the compiler, even when it make no sense at all. - anything? I doubt it. C++ compilers have been tightening up code validation for a while now.

@LookAlterno simplification of the grammar & semantics, but you can use the identifier of the function on it own to assign to a function pointer: fooPtr = RunSerial;

@LookAlterno it's a nop. you can use (void) var; to silence a unused local variable warning though.