title: Help with arduino car project

text:
# Question
Title: Help with arduino car project
So in computer engineering I've got to make a arduino based car, I've added a whole bunch of features such as IR tracking, obstacle avoidance(proximity sensor), optical tracking(follow a black line), and remote control through an android based phone.

Since I'm a total newbie to technology I'm having trouble. I would appreciate it if You guys can point me towards resources and arduino libraries(for coding) that will work for me. Right now for coding I've only got basic pseudo-code setup since I do not know what libraries to use. I have searched up many sketches online and looked at them but didn't really understand any of the code.

Here's the basic pseudo-code I got setup on the things that I've got to work on:

***DC Motor*** *(4 of em for the wheels) (I also plan to add a stepper motor for turning right and left so if you could direct me on that as well)*

//Import necessary library //Setup the motors and pins

//If signal for forward received //Code for moving forward //Set speed

//Else If signal for backward received //Code for moving backward //Set speed

//Else If signal for right received (keep turning right till stop signal received) //Code for moving right //Set speed

//Else If signal for left received (keep turning left till stop signal received) //Code for moving left //Set speed

//Else If signal for stop is received (Should we slow down to a stop or just stop?) //Code for stop //Set speed

***IR*** *(I've got transmitting and recording diodes)*

//Import Library

//Declare Pin for the IR Sensor

//While loop: Move Right //If IR signal is received //move forward //Else //Jump back to top of loop

***Proximity Sensor*** *(obstacle avoidance mode) (I might either use the one from Lego kit or buy a separate one )*

//Import Library

//Declare Pin for proximity sensor

//While Loop: Send out sonar(echolocation or whatever) every second //Is there any obstacle? //Yes, turn right so many degrees, and go back to while loop //No, move on forward at set speed

//If you’re surrounded and cannot exit send out a message through flashing LED's

---

I'm not asking for the code or for any of you to do all my stuff for me, I'm just asking for direction and resources.

Thank You

# Answer
> 1 votes
1) start simple - adding extra features will not help you, especially if you have a deadline

2) implement and test code for each low level function separately - however, in case you use libraries and or snippets, make sure that if a library/snippet requires exclusive use of a certain feature (ex: a timer), others do not need it.

3) test the overall logic elsewhere, where it easier to debug (ex: on a PC), by replacing the actual function calls to low level actuators/sensors with mockup functions that do I/O through either a file or a console.

Said this, what do you mean that you didn't understand the examples you found? To understand most of them, you need at least to read the API/interface of the libraries they use. And also reading the reference manual of the ATMega328P for the HW blocks referred by each library will help getting an overall feeling of what the library does.

About the basic physical model: once you have 4 DC motors (but 2 plus a caster would be enough), why do you want to add a stepper? Youc could do all of it with just 2 stepper motors , which will give you a simpler way to control precisely the orientation of the robot.

I'd suggest you to get the basic movement sorted out, before worrying about the rest. Just make sure that it doesn't make exclusive use of the microcontroller.

---
Tags: arduino-uno, programming, sensors, motor, robotics
---


# Question
Title: Where do I get motion detector for ardruino that can actually be installed in ceiling?
This might be a bit of off topic but I have nowhere else to go. :-) I have programmed motion detection with ardruino and would like to integrate it with my home automation system.

Would like to install the PIR in the ceiling of the entrance.

The problem is that all low voltage PIRs for ardruino are sold without any case (just a board).

Does it mean I have to buy a regular PIR (with relay integrated) and modify it?

# Answer
> 1 votes
This might not be quite the answer you were looking for, but...

3D print your case.

I expect you haven't got a 3D printer but you can find someone on 3D hubs to print it for you, and you might not even have to design the case because thingiverse has a few already...

# Answer
> 0 votes
Try looking at Alarm PID units, they typically will operate on 12VDC and have a relay output contact and a tamper contact. They are not that expensive and come with a case.

Gil

---
Tags: arduino-yun
---


# Question
Title: How to read 6 RC remote channels using Attachinterupt for every channel
How can i use the attach interupt command and read rc channels in background. I am in doubt that attach interupt is only applied to 2 pins just and cant be used to get data from other pins.

# Answer
I am not sure what you are asking but you can have as many interrupt sources on a single interrupt pin as you want. When the interrupt happens in your ISR (Interrupt Service Routine) you simply check each one and process the ones that are valid. Be sure to do one final check before exiting as another could happen while servicing the first one.

Gil
> 0 votes

---
Tags: arduino-uno, pwm, remote-control
---


# Question
Title: NRF24L01+ how much supply ripple is acceptable?
I'm trying to get a simple TX/RX pair to work. I've got identical Nanos and I'm using the example from: http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo

I followed the advice about adding a cap across the Vcc GND on the nrf board, and added a 10uF electrolytic to both.

I still haven't received a packet yet, and I wondering how to eliminate the power supply as a cause. I scoped the power pins, and even without a cap I got about 250mV of ripple. With the cap it goes down to about 100mV. Is this within tolerance? What kind of caps does anyone else use, and has anyone scoped the result to see where the threshold lies?

Aside form that, are there any other clever ways to debug this issue?

Update 20160122. I finally tested using those cheap piggyback 3.3v regulator boards that plug straight into the nrf board. Works perfectly, not one lost packet over 5000 packets sent. Interestingly, the RX side appears to be the fussy one. Thanks to everyones' suggestions. For a total combined cost of about 4$ per node, I have a great wireless TX/RX solution.

# Answer
I would suggest using a different power supply, that appears to be your problem. 250mV is 1/4 of a volt, that is a lot of noise/ripple. I am assuming it is ripple from the AC mains. The series resister is way to large, try something about 0.1 ohm. Also put a filter cap on the load side of the resister. If you have high frequency noise add a 0.01 cap that will help. Be sure the grounds between the units are solid.

Gil

I have a feeling it is narrow fast rising spikes. If so the odds are very high it is the power supply. Can you try an analog one and see if the problem goes away? Try adding more bulk capacitance, at the rate of at least 1000uF per amp.
> 1 votes

---
Tags: nrf24l01+
---


# Question
Title: Is it possible to create an interface between Teensy 3.2 and a DSP?
I realize that this is a forum for Arduino but since the Teensy 3.2 is compatible with the Arduino IDE I thought it would be appropriate to ask the question here.

Anyway, can I create an interface between the Teensy 3.2 and a DSP, more specifically the TMS320C5534-Fixed-Point Digital Signal Processor and how could I go about it?

What I am trying to do do is capture an EEG and EoG (electrooculogram) signal, amplify it, filter the signal, use the DSP for ADC and signal processing and finally get this information from the DSP to the Teensy 3.2, which will then make a decision based on the signal obtained from the DSP.

Maybe this is a simple question but I couldn't find any answers online. I am pretty new to the world of microcontrollers.

Thank you guys!

# Answer
> 1 votes
I would use one of the serial interfaces and connect them together that way. If Asyinc run as fast as reliable.

---
Tags: arduino-uno, programming, signal-processing, teensy
---


title: What wrong with that code?

text:
# Question
Title: What wrong with that code?
Hi i have made this code its so simple its should receive data from the computer and send it back via the serial but the problem is he do not what it is suppose to do when its run its keep sending -1 to the computer and if i send something to the arduini like 55 i receive and answer 53 i have no idea were is the problem in this code

```
long number = 0;

void setup() {
  Serial.begin(9600);
}
   void loop() {
   number = Serial.read();
   delay(1000);
   Serial.println(number);
}

```

# Answer
You need to include `DEC` as the second argument to the `Serial.println()` call to get the correct numbers out. Read up on this here: Arduino Serial Print.

In other words, make change below:

```
Serial.println(number, DEC); // DEC is needed to get the correct values

```
> 2 votes

# Answer
`Serial.read()` returns one character from the input. `Serial.println` will try to convert a variable into ASCII characters, and print that. Your variable, `number` gets the ASCII code of the first typed character in its first byte. The `Serial.println` call will interpret that and the next 3 bytes (whatever they happen to be...?) as a value to be printed.

Your problem is in not understanding the conversion of digit strings into values and vice-versa, and of how the Serial.xxx functions work.

You'll need to collect the terminal input character-by-character into an array, then convert it to a numeric value (assuming you're eventually going to do more with it than print it back out). Then you could `Serial.println()` that (or another) value out to the terminal.
> 1 votes

---
Tags: c
---


# Question
Title: SoftwareSerial returns garbage when powered externally
I'm currently working on a project with the ESP8266 and Arduino Nano, and when I power the device via USB they talk to each other via SoftwareSerial just fine. I use the Arduino IDE Serial Monitor to monitor this communication. But when I power it with a 15 V wall wart to Vin it returns mostly garbage, again I can tell this with the Arduino IDE Serial Monitor (I know I shouldn't connect two power supplies at a time). When powered over 5 V USB everything is great. Why would I have a problem only when connected to an external power supply?

# Answer
> 1 votes
If you check the specifications they stat 12VDC is the max. Your on board regulator is probably very hot and either shutting down or allowing the voltage to sag. You can get a 9V wall Wart for under $5. the 9V will keep the on-board regulator much cooler and add reliability.

---
Tags: arduino-nano, softwareserial, esp8266
---


# Question
Title: Why should I put a 10K resistor with an LDR?
I am wondering why should I put a 10K resistor with an LDR.

If I put a "stronger" resistor with another resistor (in this case the LDR), I'd get a lower voltage, and then I'd, too, get a lower value in the `analogRead()`. I'd like to know in what I'm doing wrong. Can someone help me?

# Answer
LDRs themselves come in a considerable range of resistances. Search LDR specs and you will see what I mean. For example, from eBay I found one:

> Bright Resistance(10Lux)(KΩ):20-230
>
> Dark Resistance: 2 MΩ

This particular one, for example, seems to range from around 20k to 2M ohms. A reasonable series resistor would then seem to be somewhere in the middle of that range, otherwise all your readings would be skewed at one end of the scale.

For example, in this case if you used 10k and the LDR had 20 k resistance in very bright light, then the voltage would be 3.33 V

```
20000 / (20000 + 10000) * 5 = 3.33 V

```

Then if it got slightly darker and the LDR was 230 k, you would get:

```
230000 / (230000 + 10000) * 5 = 4.79 V

```

And if it was really dark you would get:

```
2000000 / (2000000 + 10000) * 5 = 4.98 V

```

You can see from those figures that you will never get a reading less than 3.33 V with this particular LDR and a 10k resistor. Thus a higher value resistor would give you a better range of readings.

However this totally depends on what resistance your particular LDR has.
> 1 votes

# Answer
After you check the LDR specification you can use an online Ohm's Law calculator and calculate the resistance you need. Be sure the power rating of the resistor is greater then what is shown. Less it will smoke more is good but size is also important.

Gil
> 0 votes

---
Tags: sensors
---


title: two 7HC595 and only 12 outputs

text:
# Question
Title: two 7HC595 and only 12 outputs
im new to arduino and thinking to create a LED project.

im creating a LED project and i want to control 12 LED's. so i use two 7HC595 but problem i face is how can i only control 12 outputs ?

and i want to create multiple blink patterns with 12 LED, please be kind enough to provide blink patterns that i can modify and create different partners.

i have found many shift-out programs but i do not understand how to limit it to 12 outputs and create multiple blink patterns.

thanks

# Answer
Do not worry about limiting it to 12 bits, send all 16 and use just the twelve you need. You never know you may expand the project. Whatever is on the unused bits is irrelevant. they do nothing.
> 1 votes

# Answer
If you use 74HC595, you have to send data to all the bits no matter what. Even if you only want to change 1 bit, you have to resend the whole bit sequence.
> 1 votes

---
Tags: led
---


# Question
Title: How to Store the Value of A Sr04 Ultrasonic distance sensor (ping)?
I am using a Sr04 Ultrasonic distance sensor with Uno clone for making a Alarm. The basic idea behind this project is that In Setup, Read the distance And store it in a varibale as Threshold. And in Loop, Check the distance readings regularly and if the Reading anytime is not equal to The threshold (that means someone interrupted in front of ultrasonic sensor), then a led flashes. I Know that is system is not enough good because the real world is a bit noisy. My problem is I am storing the theshold distance in "int" variable. The compiling error is "Cant convert Long Unsigned char to Int" something like this. Please tell me how can I store the reading of my sr04 sensor in a variable. I am using NewPing Library.

# Answer
> 0 votes
1. First you must verify that storing the value as int is even possible: long int can represent much larger values than int. Are you 100% sure that the maximum reading you will ever get can be represented as int?
2. In case the answer to the previous question is "yes", then you can just cast it on the fly: `int int_val = (int)function_returning_longint();`
3. In case the answer is "no", you can either give up the idea of using int and stick with long, which is not necessarily bad, or you can scale down the value, at the price of loosing some resolution: `int int_val = function_returning_longint() >> 8;` This assumes that long is 16 bit and int is 8 bit, but it would be preferable to use explicit types, like `int8_t` and `int16_t`. And in your case you might have to shift by a different value than 8.

Either way, do not make casts of from big type to small type without being 100% sure that the max value you will ever deal with can fit in the small type.

# Answer
> -1 votes
If you want to store it as int, you have to firstly store it in a long type then convert it into int.

For instance:

```
long i;
int j;
i = getReading();
j = (int) i;

```

There are many ways to do it, for example you can also use rounding to convert it into integer variable.

---
Tags: arduino-uno
---


title: Sensing horizontal tilt

text:
# Question
Title: Sensing horizontal tilt
I'm building a digital gear shift knob, which would display current gear (1-5, R) and based on readings from OBD-II change color when gear shifting is required, to save on fuel consumption.

I need a way to detect the current gear - PID 0D (current gear) is not availiable in this car. I was thinking about doing it based on the horizontal tilt of the gear stick, since there are 6 positions plus a neutral gear:

```
    1   3   5
     \  |  /
      --0--
    /   |  \
   2    4   R

```

Is there a sensor I could use? Or perhaps it'd be possible to build one, e.g. using 6 of these ball switches: https://www.adafruit.com/products/173 There is however a space constraint since everything needs to fit inside a gear knob, therefore I'd prefer a nice single package.

# Answer
> 1 votes
You could also sense the position of the stick where it enters the floor with hall sensors... 1-5 and reverse would have sensors, neutral would be when none of the other gears are detected.

# Answer
> 1 votes
Many vehicles with manual transmission use two push rods or cables to transmit gear selection to the gearbox. It may be easier to detect the position of those rods/cables than to attempt to filter out the g-forces involved in a moving vehicle.

Alternatively, you could use the ratio of vehicle speed to engine revs (if you can retrieve these from OBDII in your vehicle). Given that these two are directly related when a specific gear is selected and the clutch is engaged, a simple division should give you a ratio you could use to decide which gear is selected.

# Answer
> 1 votes
Your stick goes into the chassis at some point. Why not detect the position down there? But to be sure to save fuel, you'd need to know the rpm/speed and especially the load of the engine. If you are going at a high gear and low speed you won't save fuel either, so the knob is not the right place to detect the gear in question. Go for OBD, get the ratio of speed and rpm and get the load or injection quantities. If you go up the hill and select too high a gear, you won't be happy either.

---
Tags: sensors, hardware, accelerometer
---


title: How to program an offbrand arduino uno?

text:
# Question
Title: How to program an offbrand arduino uno?
So I recently bought this off brand arduino uno from betemcu.cn. it says its r3 compatible.

Can I program this thing with the arduino coder or do I need to use something else? whenever I try uploading the code it says "problem uploading to board"

what settings or program should I use to code this?

# Answer
**The issue is probably that you need a driver for the onboard CH340G USB-to-serial bridge.**

The Baite Electronics Arduino clones are generally of good quality and work well.
There are some differences between them and Arduino-brand Arduinos. Two notable ones are a different voltage regulator and (probably the issue here) a different USB-to-serial bridge IC. The Arduino brand products use an FTDI IC and Baite uses, in this case, the CH340 USB bridge IC.

The product is described **on this webpage** and you will see that they say

> UNO MEGA328P **CH340G** for Arduino Compatible

The CH340G relates to the USB interface IC.
Until about a year ago the USB driver in windows worked with most common USB ICs as well as with FTDI ICs. However, FTDI changed their system so that the Windows driver will now only work with FTDI brand ICs. So it is now necessary to load a driver into the PC (whether Windows, Linux or other O/S) to suit the CH340.

If you email them Baite will provide a link to the CH340 driver, but they do not usually provide it on their website (reason unknown to me.)

Or, you can obtain a driver from numerous websites.
**A web search on eg: driver ch340 baite arduino**
turns up many pages. How good or how safe any of these is is TBD.

**This page** claims to provide a Windows 7 CH340G driver and install instructions

This YouTube video describes how to install a driver and provides a link to this page which lists a number of drivers.

**This page discusses the issue**
> 3 votes

# Answer
Just install your driver. Some might install automatically. Then try to upload the sketch using arduino IDE.
> 0 votes

---
Tags: sketch
---


title: Change UART pin

text:
# Question
Title: Change UART pin
I am developing GPRS HTTP send request code using a GSM/GPRS module. I found the following code via google:

```
/*************************************************************************
* SIM800 GPRS/HTTP Library
* Distributed under GPL v2.0
* Written by Stanley Huang <stanleyhuangyc@gmail.com>
* For more information, please visit http://arduinodev.com
*************************************************************************/

#include <Arduino.h>

// change this to the pin connect with SIM800 reset pin
#define SIM800_RESET_PIN 7

// change this to the serial UART which SIM800 is attached to
#define SIM_SERIAL Serial

// define DEBUG to one serial UART to enable debug information output
//#define DEBUG Serial

typedef enum {
    HTTP_DISABLED = 0,
    HTTP_READY,
    HTTP_CONNECTING,
    HTTP_READING,
    HTTP_ERROR,
} HTTP_STATES;

typedef struct {
  float lat;
  float lon;
  uint8_t year; /* year past 2000, e.g. 15 for 2015 */
  uint8_t month;
  uint8_t day;
  uint8_t hour;
  uint8_t minute;
  uint8_t second;
} GSM_LOCATION;

class CGPRS_SIM800 {
public:
    CGPRS_SIM800():httpState(HTTP_DISABLED) {}
    // initialize the module
    bool init();
    // setup network
    byte setup(const char* apn);
    // get network operator name
    bool getOperatorName();
    // check for incoming SMS
    bool checkSMS();
    // get signal quality level (in dB)
    int getSignalQuality();
    // get GSM location and network time
    bool getLocation(GSM_LOCATION* loc);
    // initialize HTTP connection
    bool httpInit();
    // terminate HTTP connection
    void httpUninit();
    // connect to HTTP server
    bool httpConnect(const char* url, const char* args = 0);
    // check if HTTP connection is established
    // return 0 for in progress, 1 for success, 2 for error
    byte httpIsConnected();
    // read data from HTTP connection
    void httpRead();
    // check if HTTP connection is established
    // return 0 for in progress, -1 for error, bytes of http payload on success
    int httpIsRead();
    // send AT command and check for expected response
    byte sendCommand(const char* cmd, unsigned int timeout = 2000, const char* expected = 0);
    // send AT command and check for two possible responses
    byte sendCommand(const char* cmd, const char* expected1, const char* expected2, unsigned int timeout = 2000);
    // toggle low-power mode
    bool sleep(bool enabled)
    {
      return sendCommand(enabled ? "AT+CFUN=0" : "AT+CFUN=1");
    }
    // check if there is available serial data
    bool available()
    {
      return SIM_SERIAL.available();
    }
    char buffer[256];
    byte httpState;
private:
    byte checkbuffer(const char* expected1, const char* expected2 = 0, unsigned int timeout = 2000);
    void purgeSerial();
    byte m_bytesRecv;
    uint32_t m_checkTimer;
};

```

The problem is I have no idea how to change or define Rx and Tx Pin. If I define SIM\_SERIAL serial1 it's showing me error. I want to change it to pins 10 and 11.

Here is other code whenever I try to compile it shows me error on "serial1" online. above code is sim800.h file

here is program code of send data through http

```
"SIM800.h"

#define APN "connect"
#define con Serial
static const char* url = "http://arduinodev.com/datetime.php";

CGPRS_SIM800 gprs;
uint32_t count = 0;
uint32_t errors = 0;

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

  con.println("SIM800 TEST");

  for (;;) {
    con.print("Resetting...");
    while (!gprs.init()) {
      con.write('.');
    }
    con.println("OK");

    con.print("Setting up network...");
    byte ret = gprs.setup(APN);
    if (ret == 0)
      break;
    con.print("Error code:");
    con.println(ret);
    con.println(gprs.buffer);
  }
  con.println("OK");
  delay(3000);

  if (gprs.getOperatorName()) {
    con.print("Operator:");
    con.println(gprs.buffer);
  }
  int ret = gprs.getSignalQuality();
  if (ret) {
     con.print("Signal:");
     con.print(ret);
     con.println("dB");
  }
  for (;;) {
    if (gprs.httpInit()) break;
    con.println(gprs.buffer);
    gprs.httpUninit();
    delay(1000);
  }
  delay(3000);
}

void loop()
{

  char mydata[16];
  sprintf(mydata, "t=%lu", millis());
  con.print("Requesting ");
  con.print(url);
  con.print('?');
  con.println(mydata);
  gprs.httpConnect(url, mydata);
  count++;
  while (gprs.httpIsConnected() == 0) {
    // can do something here while waiting
    con.write('.');
    for (byte n = 0; n < 25 && !gprs.available(); n++) {
      delay(10);
    }
  }
  if (gprs.httpState == HTTP_ERROR) {
    con.println("Connect error");
    errors++;
    delay(3000);
    return;
  }
  con.println();
  gprs.httpRead();
  int ret;
  while ((ret = gprs.httpIsRead()) == 0) {
    // can do something here while waiting
  }
  if (gprs.httpState == HTTP_ERROR) {
    con.println("Read error");
    errors++;
    delay(3000);
    return;
  }

  // now we have received payload
  con.print("[Payload]");
  con.println(gprs.buffer);

  // show position
  GSM_LOCATION loc;
  if (gprs.getLocation(&loc)) {
    con.print("LAT:");
    con.print(loc.lat, 6);
    con.print(" LON:");
    con.print(loc.lon, 6);
    con.print(" TIME:");
    con.print(loc.hour);
    con.print(':');
    con.print(loc.minute);
    con.print(':');
    con.println(loc.second);
  }

  // show stats
  con.print("Total Requests:");
  con.print(count);
  if (errors) {
    con.print(" Errors:");
    con.print(errors);
  }
  con.println();
}

```

i already know how to send data through http using AT command and software serial library here is my code

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.write("AT\n");
  delay(1000);
  mySerial.write("AT+CSQ\n");
  delay(1000);
  mySerial.write("AT+SAPBR=3,1,\"APN\",\"internet\"\n");
  delay(2000);
  mySerial.write("\nAT+SAPBR=1,1\n");
  delay(1000);
  mySerial.write("AT+HTTPINIT\n");
  delay(1000);

}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
    delay(1000)
    serial.print(enter key)
  }
  if (Serial.available()) {
    delay(2000);
     mySerial.write("AT+HTTPPARA=\"URL\",\"http://www.mydomain.in/index.php?dt=testdata\"\n");
     delay(2000);
     mySerial.write("AT+HTTPACTION=0\n");
      delay(2000);
      mySerial.write("\n");
    mySerial.write(Serial.read());
  }

```

In this code I define Rx Tx (UART)pin. Can you please suggest me any idea how can i define RX Tx pin in sim800.h file. because serial1 give me error on compiling time

# Answer
> ```
> SoftwareSerial mySerial(10, 11); // RX, TX
>
> ```

Well there you are.

```
#define SIM_SERIAL mySerial

```
> 1 votes

# Answer
I think Serial1 has to do with the Hardware serial Port(tx1,rx1) on Arduino mega . But since you are not using Serial.print i suggest you try "Serial/Serial0" if you are using UNO. If you want (10,11) like you said then i think you should use Softwareserial
#include SoftwareSerial.h //check spelling online not sure SoftwareSerial allex(10,11);
#define SIM\_SERIAL allex
try it and see if it works.
> 0 votes

---
Tags: softwareserial, uart
---


# Question
Title: Help choosing servo motor for Arduino crane
I'm building an automated Arduino crane where the base material is PVC pipes. The arm consists of the picking mechanism and other sensors, so the total arm might come to about 2-3 Kg (I haven't built it yet).

Can you please suggest to me an appropriate make/model of servo motor which I can purchase (preferably from India only)?

# Answer
> 1 votes
It really depends on where you are placing the servo, how much peak load & at what kind if distance from the servo.

These Corona servos are capable of lifting 2-3Kg at a distance of 2cm from the servo centre. (look at the torque entry on the specification sheet)

---
Tags: arduino-uno, servo
---


# Question
Title: Arduino IDE says fcould not convert 'pinMode(buttons[((inti)], 0u)' from 'void' to 'bool'. How do I fix
Alright, so this code is for a game that is a power source connected to 6 buttons at ports 1, 2, 9, 11, 12, and 13. These are consequently supposed to light up 6 LEDs, each connected to 1. If you press the buttons in the right order, all the LEDs blink at once. Does it work?

```
#define DEBOUNCE 10  // button debouncer, how many ms to debounce, 5+ ms is usually plenty

// here is where we define the buttons that we'll use. button "1" is the first, button "6" is the 6th, etc
byte buttons[] = {1, 2, 9, 11, 12, 13}; // the analog 0-5 pins are also known as 14-19
// This handy macro lets us determine how big the array up above is, by checking the size
#define NUMBUTTONS sizeof(buttons)
// we will track if a button is just pressed, just released, or 'currently pressed'
volatile byte pressed[NUMBUTTONS], justpressed[NUMBUTTONS], justreleased[NUMBUTTONS];

void setup() {
byte i;

// set up serial port
Serial.begin(9600);
Serial.print("Button checker with ");
Serial.print(NUMBUTTONS, DEC);
Serial.println(" buttons");

// pin1 LED
pinMode(1, OUTPUT);

 // Make input & enable pull-up resistors on switch pins
 for (i=0; ipinMode(buttons[i], INPUT);
 digitalWrite(buttons[i], HIGH);
  }

 // Run timer2 interrupt every 15 ms
 TCCR2A = 0;
 TCCR2B = 1<<CS22 | 1<<CS21 | 1<<CS20;

 //Timer2 Overflow Interrupt Enable
  TIMSK2 |= 1<<TOIE2;

 }

SIGNAL(TIMER2_OVF_vect) {
check_switches();
}

void check_switches()
{
  static byte previousstate[NUMBUTTONS];
static byte currentstate[NUMBUTTONS];
 static long lasttime;
 byte index;

  if (millis() // we wrapped around, lets just try again
     lasttime = millis();
  }

  if ((lasttime + DEBOUNCE) > millis()) {
    // not enough time has passed to debounce
return;
  }
  // ok we have waited DEBOUNCE milliseconds, lets reset the timer
  lasttime = millis();

  for (index = 0; index digitalRead(buttons[index]);   // read the button

    /*
    Serial.print(index, DEC);
    Serial.print(": cstate=");
    Serial.print(currentstate[index], DEC);
    Serial.print(", pstate=");
    Serial.print(previousstate[index], DEC);
    Serial.print(", press=");
    */

    if (currentstate[index] == previousstate[index]) {
      if ((pressed[index] == LOW) && (currentstate[index] == LOW)) {
          // just pressed
          justpressed[index] = 1;
      }
      else if ((pressed[index] == HIGH) && (currentstate[index] == HIGH))        {
          // just released
          justreleased[index] = 1;
      }
      pressed[index] = !currentstate[index];  // remember, digital HIGH     means NOT pressed
    }
    //Serial.println(pressed[index], DEC);
    previousstate[index] = currentstate[index];   // keep a running tally  of the buttons
  }
}

void loop() {
  for (byte i = 0; i if (justpressed[i]) {
      justpressed[i] = 0;
      Serial.print(i, DEC);
      Serial.println(" Just pressed");
      // remember, check_switches() will CLEAR the 'just pressed' flag
    }
    if (justreleased[i]) {
      justreleased[i] = 0;
      Serial.print(i, DEC);
      Serial.println(" Just released");
      // remember, check_switches() will CLEAR the 'just pressed' flag
    }
    if (pressed[i]) {
      Serial.print(i, DEC);
      Serial.println(" pressed");
      // is the button pressed down at this moment
    }
  }
}

int questionNumberArray[] = {1, 2, 9, 11, 12, 13};//the array itself
const size_t n = sizeof(questionNumberArray) / //the array used
sizeof(questionNumberArray[0]);//the base of the array

for (size_t i = 0; i < n - 1; i++) //the loop itself
{
size_t j = random(1, n - i);
int t = questionNumberArray[i]; //integer output for increase
questionNumberArray[i] = questionNumberArray[j];//the value definition
questionNumberArray[j] = t;
pinMode(questionNumberArray, INPUT);
if (digitalRead(questionNumberArray) == HIGH) {
  then(digitalRead(1, 2, 9, 11, 12, 13 == High(3))
  break;
}
}

```

Also, how do I make it so that people have infinite times to try

# Answer
There is very little about the code you are producing at the moment that could be classified as "right".

You are like a child who has been playing with LEGO® being let loose on the workings of a nuclear reactor. You're sticking things together without a) knowing what they do and b) knowing how they are supposed to work, and it's all going to end in tears.

I suggest that, for the time being, you forget this game project of yours and go back to the basics. Start by learning how to make an LED light up when you press a button. That will teach you both how to read the state of a button and how to control an LED. Then move on to doing it with multiple LEDs and multiple buttons.

As it stands you are just going to end up getting frustrated and annoyed. You're asking questions without either knowing just what it is you are asking or how to understand the answers when you are given them. And that is going to end up reflecting badly on the rating of your various users (hint: if you ask reasonable questions you get reasonable answers, and that means upvotes and reputation, which then means you can ask more questions so you don't have to keep creating new users to ask more questions where you don't actually understand what you're asking).
> 1 votes

---
Tags: arduino-uno, arduino-ide
---


title: Issue with leOS2 for one-time tasks

text:
# Question
Title: Issue with leOS2 for one-time tasks
I'm trying to use the last version of **leOS2 scheduler from Leonardo Miliani** ( https://github.com/leomil72/leOS2 ) but I have a strange behavior with a very simplistic ONETIME task.

Platform : Arduino Uno clone, so Atmel Atmega 328P CPU.

My code is very straightforward :

```
#include "leOS2.h"
leOS2 myOS; //create a new istance of the class leOS

bool test = true;

void setup()
{
    myOS.begin(); //initialize the scheduler
}
void loop()
{
    // Do some stuff ...

    if(test)
    {
       DoAndUndo(3000);
       test = false;
    }
}

void DoAndUndo(unsigned long duration)
{
    doSomething();

    myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME);
}

void doSomething()
{
    Serial.println("thing on");
}

void cancelTheThing()
{
    Serial.println("thing is off");
}

```

In case it can be some kind of conflict, my code also relies on the following :

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <IRremote.h>

```

The problem is : myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME); is supposed to call asynchronously the "cancelTheThing" method 3 seconds later, and for only one time, and then forget it. But for an unknown reason, it's called after the expected delay, **but it loops infinitely on this method** ! In the example case above, my serial stream is filled with a lot of "thing is off" messages, and the µc is unresponsive to anything apart a reset.

The call to DoAndUndo() will produce a such like output :

```
 thing on

```

And 3s later, in a very fast infinite loop :

```
 thing is off
 thing is off
 thing is off
 thing is off

```

If I remove the "ONETIME" flag, the task is called every three seconds (exactly as it's suppose to do, so the scheduler works, but it's not what I want in my use case).

note : As a try of workaround, I've tried some tricks like calling haltScheduler() inside my cancelTheThing() and reenable it with restartScheduler() in DoAndUndo(), and also tried to call removeTask once it has ran, but it didn't help.

Thank you for your help

# Answer
> 1 votes
There appears to be a fault with the library whereby if the only registered task is a one-shot task it doesn't get cancelled when it has executed.

Adding another periodic task in `setup()` (say to blink an LED every 500ms) so there are now 2 tasks instead of one works around the problem.

The way the system is written it will always try an execute task number 0 even when there are 0 tasks registered because they erroneously used a "do {...} while" construct instead of a "while { ...}" construct.

---

I have filed a bug report, corrected the error, and raised a pull request with the fix in it. Until it gets accepted you can obtain the fixed version here: https://github.com/majenkotech/leOS2

---
Tags: arduino-uno, programming, c, interrupt
---


# Question
Title: Arduino: Error: 'PubNub' was not declared in this scope
I'm new to Arduino. When Arduino verifies this sketch https://github.com/MediaTek-Labs/Real-Time-Bicycle-Tracking-Map-using-PubNub throws the following:

```
Build options changed, rebuilding all
BikeTracker.ino: In function 'void setup()':
BikeTracker.ino:45:5: error: 'PubNub' was not declared in this scope
BikeTracker.ino: In function 'void loop()':
BikeTracker.ino:91:14: error: 'PubNub' was not declared in this scope

```

I've read most answers are pointing out to www.arduino.cc/en/Guide/Libraries some people say it's common Arduino linking issue (easy to fix) after tried out multiple approaches with no dice.

I've also followed PubNub customer support advice (with list of steps below) but no avail:

> OCT 12, 2015 | 10:23AM PDT PubNub replied: Eduardo,
>
> I got this from our hardware/IoT/embedded engineer:
>
> You are probably not including all the libraries, or has the wrong path for them.
>
> * When you download the source at MediaTek-Labs/Real-Time-Bicycle-Tracking-Map-using-PubNub on GitHub:
>     + Click .ino file and a pop up will ask if you need a new folder for the sketch – click Yes.
>     + Then copy the rest of the files from the source to this new folder.
>     + Compile it and see if you get any library path errors that you need to provide. Let me know if you require further assistance.

BTW this is my PubNub.h https://gist.github.com/egomez99/fb1d738ec39913629e9a

Hope someone can shed some lights.

# Answer
> 1 votes
It turns out my Arduino IDE could not find PubNub.\* files until I manually added them as a Library.

---
Tags: arduino-ide
---


title: Error while compiling

text:
# Question
Title: Error while compiling
I made a code which can send the message to the entered phone number while it receieves a specific message or when the push button is pressed. but it is showing the error that 'smsReceivingFunction' was not declared in this scope. I'm a beginner and don't know what i'm doing wrong.

to know the working of functions of library-- http://1sheeld.com/docs/sms/#example

here is the code--

```
#include <OneSheeld.h>
float lat ;
float lon ;
char charlat [30];
char charlon [30];
char readings [150];
int buttonPin=11;
int ledPin=12;

void setup() {
  // put your setup code here, to run once:
  OneSheeld.begin();
    /* Set the button pin as input. */
  pinMode(buttonPin,INPUT);
  /* Set the LED pin as output. */
  pinMode(ledPin,OUTPUT);
  SMS.setOnSmsReceive(&smsReceivingFunction);
}

void loop()

{
    charlat[0] = 0;
  charlon[0] = 0;
  readings [0] = 0;
if(digitalRead(buttonPin) == HIGH)
  {
    /* Turn on the LED. */
    digitalWrite(ledPin,HIGH);
    delay( 1000);
    digitalWrite(ledPin,HIGH);
    delay( 500);

      lat = GPS.getLatitude();
      lon = GPS.getLongitude();
      dtostrf(lat, 3, 7, charlat);
      dtostrf(lon, 3, 7, charlon);
      strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
      strcat(readings, "http://maps.google.com/maps?q=");
      strcat (readings, charlat);
      strcat(readings, ",");
      strcat (readings, charlon);
      SMS.send("+917771914436", readings);

      void smsReceivingFunction(const char * number,const char * text);

       if(!strcmp(number,"+7771914436"))               /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */
      {
        if(!strcmp(text,"?"))
        lat = GPS.getLatitude();
      lon = GPS.getLongitude();
      dtostrf(lat, 3, 7, charlat);
      dtostrf(lon, 3, 7, charlon);
      strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
      strcat(readings, "http://maps.google.com/maps?q=");
      strcat (readings, charlat);
      strcat(readings, ",");
      strcat (readings, charlon);
      SMS.send("+917771914436", readings);
      }
  }

  }
}

```

# Answer
Basically the formatting and layout of your program is completely wrong. You haven't actually defined this `smsReceivingFunction` anywhere. You have created a *prototype* to it part way through your `loop()` function, but not created the actual function.

You should learn to strictly indent your program properly. It is important, since by doing so you can follow the flow and structure of your program much easier.

For instance, if I pass your program through Artistic Style to attempt to automatically correct your indenting it results in this:

```
#include <OneSheeld.h>
float lat ;
float lon ;
char charlat [30];
char charlon [30];
char readings [150];
int buttonPin = 11;
int ledPin = 12;

void setup() {
    // put your setup code here, to run once:
    OneSheeld.begin();
    /* Set the button pin as input. */
    pinMode(buttonPin, INPUT);
    /* Set the LED pin as output. */
    pinMode(ledPin, OUTPUT);
    SMS.setOnSmsReceive(&smsReceivingFunction);
}

void loop()
{
    charlat[0] = 0;
    charlon[0] = 0;
    readings [0] = 0;
    if (digitalRead(buttonPin) == HIGH) {
        /* Turn on the LED. */
        digitalWrite(ledPin, HIGH);
        delay( 1000);
        digitalWrite(ledPin, HIGH);
        delay( 500);
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        dtostrf(lat, 3, 7, charlat);
        dtostrf(lon, 3, 7, charlon);
        strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
        strcat(readings, "http://maps.google.com/maps?q=");
        strcat (readings, charlat);
        strcat(readings, ",");
        strcat (readings, charlon);
        SMS.send("+917771914436", readings);
        void smsReceivingFunction(const char * number, const char * text);

        if (!strcmp(number, "+7771914436")) {           /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */
            if (!strcmp(text, "?")) {
                lat = GPS.getLatitude();
            }

            lon = GPS.getLongitude();
            dtostrf(lat, 3, 7, charlat);
            dtostrf(lon, 3, 7, charlon);
            strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
            strcat(readings, "http://maps.google.com/maps?q=");
            strcat (readings, charlat);
            strcat(readings, ",");
            strcat (readings, charlon);
            SMS.send("+917771914436", readings);
        }
    }
}
}

```

As you can now see you have an extra `}` at the end of your sketch, so your brackets are not balanced. That in itself is a syntax error. Also you can see your function prototype slap bang in the middle of your loop() function:

```
...
        SMS.send("+917771914436", readings);
        void smsReceivingFunction(const char * number, const char * text);

        if (!strcmp(number, "+7771914436")) {           /* phone number
...

```

I think, though of course I can't actually test this since I don't have your hardware, that you really meant to start a new function at that point in your program, and of course that would mean finishing the previous function first: you *cannot* nest functions inside each other. So I would guess your program *should* have looked something more like this:

```
#include <OneSheeld.h>
float lat ;
float lon ;
char charlat [30];
char charlon [30];
char readings [150];
int buttonPin = 11;
int ledPin = 12;

void setup() {
    // put your setup code here, to run once:
    OneSheeld.begin();
    /* Set the button pin as input. */
    pinMode(buttonPin, INPUT);
    /* Set the LED pin as output. */
    pinMode(ledPin, OUTPUT);
    SMS.setOnSmsReceive(&smsReceivingFunction);
}

void loop()
{
    charlat[0] = 0;
    charlon[0] = 0;
    readings [0] = 0;
    if (digitalRead(buttonPin) == HIGH) {
        /* Turn on the LED. */
        digitalWrite(ledPin, HIGH);
        delay( 1000);
        digitalWrite(ledPin, HIGH);
        delay( 500);
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        dtostrf(lat, 3, 7, charlat);
        dtostrf(lon, 3, 7, charlon);
        strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
        strcat(readings, "http://maps.google.com/maps?q=");
        strcat (readings, charlat);
        strcat(readings, ",");
        strcat (readings, charlon);
        SMS.send("+917771914436", readings);
    }
}

void smsReceivingFunction(const char * number, const char * text) {
    if (!strcmp(number, "+7771914436")) {           /* phone number from which you will send the sms "PUT YOURS IN PLACE OF +1234567890" */
        if (!strcmp(text, "?")) {
            lat = GPS.getLatitude();
        }
        lon = GPS.getLongitude();
        dtostrf(lat, 3, 7, charlat);
        dtostrf(lon, 3, 7, charlon);
        strcat(readings, "please call me I i do not pick up the call please reach to my location:\n");
        strcat(readings, "http://maps.google.com/maps?q=");
        strcat (readings, charlat);
        strcat(readings, ",");
        strcat (readings, charlon);
        SMS.send("+917771914436", readings);
    }
}

```
> 3 votes

---
Tags: arduino-uno, gsm
---


title: Using random() in a header file

text:
# Question
Title: Using random() in a header file
```
#ifndef FOO_H
#define FOO_H

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

#endif

```

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

`'random' was not declared in this scope`

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

# Answer
Add `#include <Arduino.h>` like this

```
#ifndef FOO_H
#define FOO_H

#include <Arduino.h>

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

#endif

```
> 2 votes

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

In foo.h:

```
#ifndef FOO_H
#define FOO_H

struct Foo{
  int randInt;
};

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

```

In foo.c:

```
#include "foo.h"

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

```

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

---
Tags: programming, c++
---


title: A whole basic game project Arduino

text:
# Question
Title: A whole basic game project Arduino
Firstly, I know that I have already posted this. I do not think anyone here is stupid so: The game is: a power source connected to 6 buttons connected to 6 LEDs. you press them all in the randomly generated order, and they blink in the order pressed after completion, then randomize and reset.

I have an array shuffler code 1)Does the array shuffler work 2)How do I configure ports and attach them to values in the array, 3) How do I use an if-then statement to say if all buttons pressed in order, then LEDs blink 3 times? I have a picture but not the actual Arduino, so, upon request, I can post the picture. Thank you. code:

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

void loop() {
    // put your main code here, to run repeatedly:
    int questionNumberArray[] = {0,1,2,3,4,5,6};//the array itself
    const size_t n = sizeof(questionNumberArray) / //the array used
    sizeof(questionNumberArray[0]);//the base of the array

    for (size_t i = 0; i < n - 1; i++) //the loop itself
    {
        size_t j = random(1, n - i);
        int t = questionNumberArray[i]; //integer output for increase
        questionNumberArray[i] = questionNumberArray[j];//the value definition
        questionNumberArray[j] = t;
    }

}

```

The six buttons are connected to digital pins (1, 2, 9, 11, 12, 13)

# Answer
So you leds are connected to "pins" not "ports." Since each of the buttons will turn on only 1 led we need to keep track of which button pairs with which led. To do this we can use a `struct` like this one:

```
struct ButtonLed{
        int buttonPin;
        int ledPin;
};

```

You declare a `ButtonLed` like this: `ButtonLed button1 = {1, 0}` where the first parameter is the button's pin and the second is the led's pin. **(All of the led pins are set to 0 since I don't know which pins you have them connected to.)**

And the array will hold the button/led pin pair like this:

`ButtonLed questionNumberArray[] = {button1, button2, button3, button4, button5, button6};`

Since there are 6 leds you know that your array is size 6 so use this declaration instead

`const int n = 6;`

I fixed you range for the random number generation. Look at the documentation for `random()` here https://www.arduino.cc/en/Reference/Random. We can use this function for shuffling the array.

```
void shuffleArray (ButtonLed arr [], const int size){
    for (int i = 0; i < size - 1; i++){ // iterates through array except last element
        int j = random(0, size); // generates a random index from (0 to n-1) inclusive

        // swap current index with random index
        ButtonLed t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }
}

```

We will use this function to wait until the user enters a sequence of button presses:

```
ButtonLed getButtonPress (ButtonLed arr [], const int size){
    bool pressed = false;
    ButtonLed  pressedButton;
    while (!pressed){ // loops until a button was pressed
        for (int i = 0; i < size && !pressed; i++){ // !pressed allows early out
            if (digitalRead(arr[i].buttonPin)){ // one of the six buttons was pressed
                pressed = true; // exit both loops
                pressedButton = arr[i]; // stores which button was pressed
            }
        }
    }
    return pressedButton; // return the pressed button
}

```

Essentially it gets stuck in a loop and reads each of the 6 buttons until one of them is pressed and then records which one was pressed.

Try using the code below and read the comments the only thing you need to do is change all the zeros in the `ButtonLed` declarations to whatever pin the leds are connected to. Also the `struct` above needs to go into it's only file called "ButtonLed.h" It **must** be called that.

```
#include "ButtonLed.h"

// These are ButtonLeds our newly created data type
// they hold both an led's pin and the pin for the button
// that turns it on
ButtonLed button1 = {1, 10};
ButtonLed button2 = {2,  8};
ButtonLed button3 = {9,  7};
ButtonLed button4 = {11, 6};
ButtonLed button5 = {12, 5};
ButtonLed button6 = {13, 4};

// This function will randomly shuffle an array of ButtonLeds
void shuffleArray (ButtonLed arr [], const int size){
    for (int i = 0; i < size - 1; i++){ // iterates through array except last element
        int j = random(0, size); // generates a random index from (0 to size-1) inclusive

        // swap current index with random index
        ButtonLed t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }
}

ButtonLed getButtonPress (ButtonLed arr [], const int size){
    bool pressed = false;
    ButtonLed  pressedButton;
    while (!pressed){ // loops until a button was pressed
        for (int i = 0; i < size && !pressed; i++){ // !pressed allows early out
            if (digitalRead(arr[i].buttonPin)){ // one of the six buttons was pressed
                digitalWrite(digitalRead(arr[i].ledPin, HIGH); // turns on the led the user chose
                delay(200);
                digitalWrite(digitalRead(arr[i].ledPin, LOW); // turns it back off
                pressed = true; // exit both loops
                pressedButton = arr[i]; // stores which button was pressed
            }
        }
    }
    return pressedButton; // return the pressed button
}

void setup() {
    randomSeed(analogRead(A0));
    // This is how you set up the leds for output
    pinMode(button1.ledPin, OUTPUT);
    pinMode(button2.ledPin, OUTPUT);
    pinMode(button3.ledPin, OUTPUT);
    pinMode(button4.ledPin, OUTPUT);
    pinMode(button5.ledPin, OUTPUT);
    pinMode(button6.ledPin, OUTPUT);

    // This is how you set up the buttons for input
    pinMode(button1.buttonPin, INPUT);
    pinMode(button2.buttonPin, INPUT);
    pinMode(button3.buttonPin, INPUT);
    pinMode(button4.buttonPin, INPUT);
    pinMode(button5.buttonPin, INPUT);
    pinMode(button6.buttonPin, INPUT);
}

void loop() {

    // This array is of type ButtonLed our newly created data type
    ButtonLed questionNumberArray[] = {button1, button2, button3,
                                       button4, button5, button6};
    const size_t n = 6; // array's size

    shuffleArray(questionNumberArray, n);

    numLeds = 1;
    bool guessCorrectly = false;

    // this while loop allows the user to keep trying until they get it right
    while (!guessCorrectly){

        // This loop displays the correct sequence to the user
        for (int i = 0; i < numLeds; i++){
            digitalWrite(questionNumberArray[i].ledPin, HIGH); // turn on the led

            delay(500); // decrease this number to flash faster; increase to flash slower

            digitalWrite(questionNumberArray[i].ledPin, LOW); // turn off the led
        }

        bool correctButton = true; // the user has pressed the correct button
        ButtonLed userSequence [6];      // stores the sequence the user entered
        // lets the user push 6 buttons
        for (int i = 0; i < numLeds; i++){
            userSequence[i] = getButtonPress(questionNumberArray, numLeds);
            delay(500); // delay between button presses
        }

        // check if the user entered the correct sequence
        for (int i = 0; i < numLeds && correctButton; i++){
            if (userSequence[i].buttonPin != questionNumberArray[i].buttonPin)
                correctButton = false;
        }

        if (correctButton){ // user entered the correct sequence
            guessCorrectly = true;
            // This will turn on the leds in the correct sequence
            for (int i = 0; i < numLeds; i++){
                digitalWrite(questionNumberArray[i].ledPin, HIGH); // turn on the led
                delay(500); // delay half a second
                digitalWrite(questionNumberArray[i].ledPin, LOW); // turn off the led
            }
            numLeds++;
            if (numLeds > 6)
                --numLeds;
        }
    }
}

```

After you are finished typing the code above it `ctrl+shift+n` and open a new tab called "ButtonLed.h" and add this to it:

```
#ifndef BUTTONLED_H
#define BUTTONLED_H
#include <Arduino.h>

// We create new data type called ButtonLed which stores the button's pin
    // and the led's pin; this allows us to keep both an led and it's
    // corresponding button together without have to manage 2 arrays
    struct ButtonLed{
        int buttonPin;
        int ledPin;
    };

#endif

```

Make sure you open a new tab and not a new project. Also as others have said you should really learn how to program. Be aware this code compiles however, I haven't tested it. I will update the code when you tell me what pins the leds are connected to.

**Edit 1**

I added a while loop that allows the user to keep trying until they guess correctly.

**Edit 2**

I also updated the code for which pins the leds are connected to. Remember they're connected to "pins" **Not** "ports.
> 3 votes

---
Tags: arduino-uno, programming, c++, arduino-ide
---


title: USB detect on Arduino DUE

text:
# Question
Title: USB detect on Arduino DUE
I want to know when something is connected to USB port by blinking an LED.

I suppose have to check PB10 UOTGVBOF, but how to do this ?

# Answer
What I'm going to say is probably not the most efficient way to do it, but it should work: if your DUE is used as gadget and you wnat to detect the presence of a master, connect a GPIO to the +Vcc line of the usb port and either poll or program an edge triggered interrupt to detect when the line goes high.
> 1 votes

---
Tags: arduino-due
---


# Question
Title: Uploading Temperature data (DHT22) to Thingspeak with an ENC28J60
So, I've gotten my module working pretty well. It logs data from the DHT22 and sends it to a 192 address on my LAN. However, I'd like to log and graph the data.

I figured thingspeak is a decent platform for that. However, I have no experience doing so, and I'm not sure where to start. All the examples use the "official" arduino shield. I've only found ONE example bit of code, but it uses the Dallas One Wire temp module. Link

I'm in over my head, and have no idea how to switch from the One wire to the DHT22. Thanks for the help!

I'm using a clone arduino pro mini, 5V 16mhz, 328.

If there's a better platform than thingspeak, I'm open. All I want to do is graph and visualize the DHT22 sensor readings.

# Answer
> 1 votes
Try this:

```
/*
| Post temp. values from a DS18B20 to ThingSpeak using the Ethercard interface based on the
| ENC28J60 chip.
| Based on the Ethercard example from www.jeelabs.org
| Phil Grant Jan 2014
*/
#include <EtherCard.h>
// change these settings to match your own setup
#define APIKEY  "xxxxxxxxxxxxxxxx"

//DHT Setup
#include "DHT.h"
#define DHTPIN 2     // what pin we're connected to
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE);

// ethernet interface mac address, must be unique on the LAN
byte mymac[] = { 0xXX,0xXX,0xXX,0xXX,0xXX,0xXX };

char website[] PROGMEM = "api.thingspeak.com";

byte Ethernet::buffer[700];
uint32_t timer;
Stash stash;

void setup () {
  Serial.begin(57600);
    dht.begin(); //Initializate DHT
  Serial.println("\n[webClient]");

  if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
    Serial.println( "Failed to access Ethernet controller");
  if (!ether.dhcpSetup())
    Serial.println("DHCP failed");

  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);

  if (!ether.dnsLookup(website))
    Serial.println("DNS failed");

  ether.printIp("SRV: ", ether.hisip);
}

void loop () {
  ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 60000; //Transmit every minute
    delay(2000);  // Wait a few seconds between measurements.
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity(); // Read temperature as Celsius (the default)
  char h_buffer[10];
  String Hstring = dtostrf(h,0,5,h_buffer); //Convert Humidity value to String

  float t = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true)
  //float f = dht.readTemperature(true);
  char t_buffer[10];
  String Tstring = dtostrf(t,0,5,t_buffer); //Convert Temperature value to String

    byte sd = stash.create();
    stash.print("field1=");
    stash.println(Hstring);
    stash.print("&field2=");
    stash.println(Tstring);
    stash.save();

    // generate the header with payload - note that the stash size is used,
    // and that a "stash descriptor" is passed in as argument using "$H"
    Stash::prepare(PSTR("POST /update HTTP/1.1" "\r\n"
                        "Host: $F" "\r\n"
                        "Connection: close" "\r\n"
                        "X-THINGSPEAKAPIKEY: $F" "\r\n"
                        "Content-Type: application/x-www-form-urlencoded" "\r\n"
                        "Content-Length: $D" "\r\n"
                        "\r\n"
                        "$H"),
            website, PSTR(APIKEY), stash.size(), sd);

    // send the packet - this also releases all stash buffers once done
    ether.tcpSend();
  }
}

```

---
Tags: sensors, arduino-pro-mini, ethernet, web-server
---


# Question
Title: Unable to tell if error is from receiving or transmitting end
so I am having trouble sending data using software serial's write function.

TX Code:

```
#include <SoftwareSerial.h>

SoftwareSerial TX(2,3);

void setup() {
  // put your setup code here, to run once:
  TX.begin(1200);
}

void loop() {
    TX.write(60);
}

```

**Is the delay necessary?**

RX Code:

```
#include <SoftwareSerial.h>
SoftwareSerial RX(2,3); //(rx pin, tx pin)
const unsigned int bufferSize = 100;

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

}

void printBuffer(const uint8_t *serialBuffer)
{
  //print contents of buffer
  for (int i = 0; i<100; i++)
    Serial.println(serialBuffer[i], BIN);
}

void processBytes(const uint8_t value)
{
  static uint8_t serialBuffer[bufferSize]; //buffer to hold values
  static unsigned int startPosition=0;

  if(startPosition < bufferSize)
    serialBuffer[startPosition++] = value;

  else
  {
    printBuffer(serialBuffer);
    startPosition = 0;
  }

}//end of processBytes
void loop() {

  //check if data is available in serial buffer
  while(RX.available())
  {
    //process data
    processBytes(RX.read());
  }
}

```

If i transmit the number 60, it prints 226 constantly for 2-3 seconds, then prints 60 for a short while, then goes back to printing 226. Am I doing something wrong with my code?

**FIRST QUESTION:** In the case when startPosition (in the process function) equals 100, it will call print. Print will then print 100 integers. Now, when doing that, there could still be data being transmitted from the transmitter. But the read function won't be executed until printBuffer returns, process returns, and the while loop iterates again. So during that time, couldn't some transmitted values potentially not be read?

**SECOND QUESTION** How come Software serial doesn't synchronize incorrectly more often? How is it being so accurate if the start bit is just a single bit and it's a 0. So for instance, if payload has some 0s, how come one of those 0s aren't being assumed to be the startbit? How does this get resolved? I looked at the software serial library, but I am not able to find out why. Any guidance here?

**THIRD QUESTION** Other than getting the startbit syncing right, are there other ways to sync the data? I was reading of NRZ encoding, manchester encoding, etc. Can any of these be implemented here? Also, would it be wise to alter the softwareSerial library to have more than one startbit?

Any guidance would be very appreciated! Thank you so much! This is all being done with wireless RF modules.

# Answer
```
void loop() {
  Serial.println("NEW-------------");
  int x;
  int y[100];
  for(int i = 0; i<100; i++){
    x=RX.read();
    y[i] = x;
  }
...
}

```

You are reading data without checking if there is any data there. That's like watching the TV without checking if it is turned on. Of course you get weird data.

---

```
SoftwareSerial RX(0,1); //(rx pin, tx pin)

```

Pins 0 and 1 are used by HardwareSerial. Why are you using them for SoftwareSerial?

---

```
SoftwareSerial RX(0,1); //(rx pin, tx pin)
...

  Serial.begin(9600);
  RX.begin(1200);

```

So you initialized HardwareSerial, which now controls pins 0 and 1.

Then you try to initialize SoftwareSerial on those **same** pins! Would you mind explaining why?

Whatever your explanation is, it won't work.

---

> I've added in the changes you mentioned, but the data still seems to be skewed.

You've changed things, for sure:

```
 for(int i = 0; i<100; i++){
    if(RX.available())
      x=RX.read();

    y[i] = x;
    }

```

Let's see. In a loop of 100 iterations you see if anything is available (and if so, put it into `x`).

Then, regardless of **whether or not you got anything** you now assign `x` to `y[i]`. So, most of the time, `y[i]` will have garbage in it.

> the data still seems to be skewed

Not surprised. Do it differently. Only write to the array if you have data. In fact you may want a complete rework. Read this:

How to read serial without blocking

---

> I have posted the amended code. Change: Only add to the array is data is being read from buffer.

```
  int y[100];
  for(int i = 0; i<100; i++){
    if(RX.available())
    {
      x=RX.read();
      y[i] = x;
    }
  }

 for (int j = 1; j<=64; j++){
    Serial.println(y[j]);
  }

```

You still have not fixed it. Let me talk you through what it is doing now.

You are making 100 attempts to read some data. One or two may succeed, and they will be put into the buffer `y` (funny name for a buffer, right?).

So imagine `.` is garbage and `X` is good data, after doing that loop of 100 the buffer will look like this:

```
........X...........X...........X...X......................X.............................................

```

So your buffer is still 80% unchanged garbage. Then you print the first 64 elements (why 64 and not 100?) and you get a lot of garbage out. Exactly as expected.

---

You need to think about what you are doing. Draw it out on a bit of paper, perhaps.

Here is some example code from the page I linked for you, more than once. Please compare:

```
// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

```
> 2 votes

---
Tags: arduino-uno, c++, communication, softwareserial, rf
---


title: Passing a static array to a function

text:
# Question
Title: Passing a static array to a function
I have a functon that creates a instance of `KeyReport` and I want to fill statically the `KeyReport.keys` array. I'm new in the Arduino world so I'll put a example to explain it better:

```
void sendKey(byte keys[6], byte modifiers)
{
  KeyReport report = {0};

  report.keys = keys; // This is my main trouble
  report.modifiers = modifiers;
  report.reserved = 1;
  Keyboard.sendReport(&report);
}

void setup(){
delay(3000);
sendKey( {0x17,0,0,0,0,0}, 0x5); // I want to send hardcoded reports like this
}

void loop(){}

```

# Answer
> 1 votes
```
report.keys = keys; // This is my main trouble

```

You can't assign the contents of one array to the contents of another array. You can only copy the contents manually from one to the other.

The simplest way is with a loop:

```
for (int i = 0; i < 6; i++) {
    report.keys[i] = keys[i];
}

```

There is a helper function - `memcpy()` \- which can do it for you if you prefer:

```
memcpy(report.keys, keys, 6);

```

It effectively does exactly the same thing - copy 6 bytes starting from the address of `keys` into the addresses starting at `report.keys`.

As for the "hard coded" reports I suggest you create some `const` arrays in the global context - and even use `PROGMEM` to ensure they consume no RAM. That, of course, requires an entirely different way of passing and accessing the data. It may be simpler to split the report into 6 individual variables and pass each byte separately:

```
void sendKey(byte k0, byte k1, byte k2, byte k3,
             byte k4, byte k5, byte modifiers)
{
  KeyReport report = {0};

  report.keys[0] = k0;
  report.keys[1] = k1;
  report.keys[2] = k2;
  report.keys[3] = k3;
  report.keys[4] = k4;
  report.keys[5] = k5;
  report.modifiers = modifiers;
  report.reserved = 1;
  Keyboard.sendReport(&report);
}

sendKey(0x17, 0, 0, 0, 0, 0, 0x05);

```

Yes, it's a little more long winded in the function, but calling the function is somewhat more simplified over the other options.

---
Tags: programming, c++
---


title: LED cube and 200 mA limitation

text:
# Question
Title: LED cube and 200 mA limitation
I'm new to electronics and have been getting rather into my Arduino. But I don't just like following an instructable to do something. I like to know the math behind it and how it works inside. Now from my understanding the Arduino (Uno R3 for me), has a 200 mA max current. The LEDs I used have a 20 mA current. Now with 64 LEDs, wouldn't this fry my Arduino? This also applies to my LCD screen with a 160 mA current. Am I missing a key secret to going over amperage?

# Answer
The current limit you quote is the maximum current that the main chip on the Arduino can tolerate through its 5V or GND pins.

As the chip itself consumes (round numbers demonstrate the theory) say 50mA that leaves 150mA in total that can be sourced or sunk through IO pins.

If you want to supply 20mA per LED (that is actually overkill - you can use considerably less and have very little difference in brightness) that means you can have, illuminated at any one time, (150 / 20 = ) 7.5 LEDs.

To increase the number of LEDs you can drive at once you can:

* Reduce the current by increasing the resistor values.
* Use multiplexing so that, although it looks like all LEDs are on at once, only a few are actually on at once.
* Use external LED driving circuitry (transistors, LED driver shift registers, etc).

All this pertains purely to the current that passes through the main chip itself. It does not pertain to any current you draw from the 5V or 3.3V pins. The maximum current through those pins is limited by the voltage regulator they are attached to, and also by the voltage that you are supplying the board with (the higher the voltage, the more voltage has to be dropped, and so the more heat is generated per mA drawn).

The 5V regulator has around 800mA limit when supplied with 6.5V. If supplied with 12V the limit is considerably less (since it will get too hot and go into *thermal shutdown*). You subtract what you are drawing through the chip (maximum 200mA) and that is how much current you have available.

The 3.3V regulator is driven from the 5V regulator, so any current drawn from the 3.3V pin must also be subtracted from what is available on the 5V pin.
> 1 votes

# Answer
I'm assuming you're talking about an 8x8x8 cube.

The 200mA is for all IO. The regular 5v line can supply 500mA. Since you don't have 64 pins available, you are not supplying the leds via the Arduino directly. Probably using some shift register, or led driver chips for the 64 (cathode) columns. For the 8 levels you'd use some PNP transistors or P-channel mosfets.

So the Arduino won't drive any led directly, so it will only use a few tens of milli-amps. Since you'll draw around 1.3A when all leds are lid, you should power the external components directly from the power supply, instead of via the Arduino. Or you'll hit the 500mA limit.

So the Arduino is just pushing the levers, and not doing any of the hard work (crane analogy).
> 1 votes

---
Tags: arduino-uno, led, lcd
---


# Question
Title: Powering Arduino with 110v and controlling relay
I've found a lot of tutorials about how to use an Arduino to control power supplies to lamps and things like that using a relay. However, I also need to power the Arduino with the same power that is going through the relay.

In other words, I'd like to be able to plug my device into the wall. The device would use the 110VAC to power the Arduino. My device would also have some outlets that I could plug something into. The Arduino would be connected to a relay and would decide when to enable electricity to the outlet. The important part being that I would like everything to be on one power source.

Do I need to have a step down converter to transform the power, in addition to the relay? Is there some sort of break out board that has both of these functionalities in one board? What is the best way to do this?

# Answer
In these cases where power must come from mains, my preferred solution is to buy a cheap phone charger+usb cable from ebay. They are sealed and safer than do-it-yourself solutions. The power adapter is barely larger than a normal plug for mains.

If you absolutely need to reach the arduino with only one cable, you can still use the solution i gave, only use a power cord to reach the contraption, then use a socket expander for mains and very short usb cable.
> 4 votes

---
Tags: arduino-uno
---


# Question
Title: WebCam Face detection and tracking tutorial with Arduino Uno R3 and OpenCV 3.0 RC1 in Ubuntu 14.04
I try to make this Arduino Open CV tutorial for webcams. OpenCV 3.0 RC1 is compiled and installed. I also use Code::Blocks 13.12 as IDE. I am a newbie what comes to OpenCV and I do not know too much about Arduino either but here I am learning. Arduino IDE is 1.7.2. The tutorial is made for Windows 7 and software for this OS but I bet it is possible to repeat this in Ubuntu Linux 14.04 also.

So the tutorial is here:

**http://duino4projects.com/face-detection-and-tracking-with-arduino-and-opencv/**

When I try to compile and run the techbitarFaceDetection.cpp

the Code::Block IDE gives me following error:

> fatal error: Tserial.h: No such file or directory

So please tell me what to do next and how to fix this error.

# Answer
`TSerial.h` is part of the Serial C++ Library that is used by the project that you are trying to build (see the section "Software Required" on the tutorial page you linked).

Make sure you have that library installed correctly.
> 1 votes

# Answer
Forget Tserial.h lib. To solve your problem (for serial communication) I sugest you to use "read/write from/to a file" programming method. The serial ports may be written to just like you are writing in a file. In the facedetect.cpp (OpenCV's example), in the detectAndDraw() function (I'm using OpenCV 3.0) add: `unsigned char MSB[1] = {0}; //
 unsigned char LSB[1] = {0}; //
 char serialPortFilename[]="/dev/ttyACM0";
 FILE *serPort = fopen(serialPortFilename, "w"); //`

than add:

```
LSB[0]=r->x & 0xff;//
    MSB[0]=(r->x >>8) & 0xff;//

    fwrite((const void*)MSB,sizeof(unsigned char),sizeof(MSB),serPort);//
fwrite((const void*)LSB,sizeof(unsigned char),sizeof(LSB),serPort);//

LSB[0]=r->y & 0xff;//
    MSB[0]=(r->y >>8) & 0xff;//

    fwrite((const void*)MSB,sizeof(unsigned char),sizeof(MSB),serPort);//
    fwrite((const void*)LSB,sizeof(unsigned char),sizeof(LSB),serPort);//

```

into the if (0.75 \< aspect\_ratio && aspect\_ratio \< 1.3) statement.

Finally don't forget to close the file

```
fclose(serPort);

```

Hope this will work for you!
> 1 votes

---
Tags: arduino-uno, programming, compile
---


title: Grove sensors without a Grove shield

text:
# Question
Title: Grove sensors without a Grove shield
There exists a large variety of sensors in the Grove System. Usually these are accessed via a special shield (Grove base shield).

Can I access these sensor directly without a shield. In particular I am interested in using them with an Arduino Pro Mini. My guess is that one definitely needs the 5V version of the Mini, but other than this? How fiddly is it to use these sensors directly?

I am interested in using the Grove dust sensor, but I am also would like to operate a Grove 4 digit display.

# Answer
*From the wiki*.

Above is a schematic of a Groove shield. You can see that each of the connectors has two digital pins connected to it and then V (5V) and G (GND). The last two you can connect normally to an Arduino. The first two you connect to the pins that are used in your sketch.

Say it says to connect the connector to the top left DIGITAL pin on the board (D6/D7). You'll 7want to connect the pins as followed: Black → GND, Red → 5V, White → D7, and Yellow → D6.

---

Notes:

* The shield overlaps the pins (i.e. 3-4, 4-5), so that might make things confusing. I think that is a design flaw. If it needs two pins, *it should have two connectors*. In the current state, you can connect two things together. **I don't really know how to figure out if it uses all of the ports attached or not. If you don't have to, I would try not to overlap any two grooves.** You would do this by using two digital ports for every groove "module."
* **You'll also need to have a adapter cable (Link from *TheDoctor's* Answer.)**
* For analog connections, it applies the same way as digital. G is ground, V is 5v, and A# is an analog pin.

---

## Inferencing it:

There's no real cookie cutter way to connect to them. However, the wiki seems to be a decent resource once you figure out how to navigate it. The dust sensor you mentioned seems to ONLY use digital pin 8. It was connected to the D7/D8 connector on the Groove shield, so the yellow wire could be ignored since it was never used in the sketch.

It's hard to do much with this system: it's poorly documented and not uniform at all. Plus, some boards could cause problems that could even lead to damaging components. I would say look at something else.

> Sharp pin 1 (V-LED) =\> 5V (connected to 150ohm resister) Sharp pin 2
>
> (LED-GND) =\> Arduino GND pin Sharp pin 3 (LED) =\> Arduino pin 2
>
> Sharp pin 4 (S-GND) =\> Arduino GND pin Sharp pin 5 (Vo) =\>
>
> Arduino A0 pin Sharp pin 6 (Vcc) =\> 5V

I can't seem to find the cord for it, but I'm sure there are many others like this online. (It lists the cable needed: a 6-pin, 1.5mm pitch connector. That doesn't seem too hard to find).

* Here is a 4x7 segment display for much cheaper. It does use a lot of pins and need resistors, but multiplexing and resistors aren't that hard to figure out. That's outside of the scope of this question. There might be some other board with a built in IC for controlling a display like that, but I can't seem to find one now.
> 5 votes

# Answer
Grove sensors use a special socket, a 4 pin JST with two power lines and two data. you would have to make your own board/terminal to get them to connect to a mini.

What you could do is use a Grove proto board, which converts the JST terminals onto .1" pins suitable for connecting to the Mini. There is also a litle proto area if you want it.

You could also use an adapter cable, which would not have a bulky protoboard along with it. The terminals could be soldered directly to the Mini.
> 3 votes

# Answer
I'm pretty sure you could just take the signal cable from the dust sensor and plug it directly into your mcu digital pin of choice and then wire the Vcc and Gnd as well. I'm working with a CO2 sensor and don't really want the shield overhead.
> 1 votes

---
Tags: sensors
---


title: Arduino WIFI compiler error

text:
# Question
Title: Arduino WIFI compiler error
Just bought an ESP8266 module to try it using my arduino uno R3. I have connected my WIFI module correctly, anyways evenb if i disconnect it, the error occur.

While trying to upload the WIFI (connect with wpa) sketch i get several errors.

First i tried uploading the hole sketch, i got those errors:

```
/usr/share/arduino/libraries/WiFi/WiFi.cpp: In member function ‘uint8_t* WiFiClass::macAddress(uint8_t*)’:
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: unable to find a register to spill in class ‘POINTER_REGS’
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: this is the insn:
(insn 35 25 26 2 (set (reg:QI 23 r23)
    (mem/c:QI (plus:HI (reg/f:HI 28 r28)
            (const_int 2 [0x2])) [3 S1 A8])) /usr/share/arduino/libraries/WiFi/WiFi.cpp:110 28 {movqi_insn}
     (nil))
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112: confused by earlier errors, bailing out

```

After that i tried to only import just the libraries and try to compile it. Even with this method i get errors

Code

```
#include <WiFiServer.h>
#include <WiFiClient.h>
#include <WiFi.h>

```

error:

```
In file included from /usr/share/arduino/libraries/WiFi/WiFiServer.h:8:0,
                 from sketch_oct20b.ino:1:
/usr/share/arduino/hardware/arduino/cores/arduino/Server.h:4:29: error: expected class-name before ‘{’ token
In file included from sketch_oct20b.ino:1:0:
/usr/share/arduino/libraries/WiFi/WiFiServer.h:14:3: error: ‘uint16_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:17:22: error: field ‘uint16_t’ has incomplete type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:18:24: error: ‘uint8_t’ has not been declared
/usr/share/arduino/libraries/WiFi/WiFiServer.h:20:11: error: ‘size_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:21:11: error: ‘size_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:22:3: error: ‘uint8_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:24:9: error: ‘Print’ has not been declared
/usr/share/arduino/libraries/WiFi/WiFiServer.h:18:42: error: ‘NULL’ was not declared in this scope

```

I can just figure out some syntax errors, but my c is not good enough to understand much of it.

Can anyone tell me what am i doing wrong and show me how it will be done?

# Answer
> 0 votes
The WiFi libraries (such as `Wifi.h`, `WifiClient.h`, and `WiFiServer.h`) are used for interfacing with the official Arduino WiFi shield. Interfacing with an ESP8266 module is typically done by issuing AT commands via UART (i.e. `Serial.write()`, etc.)

---
Tags: arduino-uno, esp8266
---


# Question
Title: Can I place bootloader directly onto Atmega2560 and have USB?
I am working on a prototype device which I am now on my 2nd board iteration and moving away from it being a shield and wired to an arduino mega2560 board.

I have used the freely available Arduino mega 2560 schematic and incorporated this into my project.

I notice that there are 2 µcontrollers on this schematic, (Atmega2560 & Atmega16U2)

I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.

On the searching I have done I'm getting myself terribly confused. Someone suggested to me that I could in fact do away with the Atmega16u2 all together (this would drastically reduce my component count and free up valuable board space)

However, I was intending to flash a boot loader that would make the device appear to a computer (over usb) as a midi controller device.

I am unclear if I can indeed interface a usb port directly to the ATmega2560, and upload my sketch code AND a midi-over-usb boot loader.. I doubt the advice because the ATmega16U2 (i think) has a built in UART to communicate via usb and that the 2560 does not...

Sorry If this all sounds vague, I'm searched out and confused...

thanks.

# Answer
> I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.

That is a misunderstanding.

The bootloader is on the 2560. The 16U2 contains its own custom firmware which acts as a USB CDC/ACM interface to connect the USB to the 2560 as a TTL UART connection.

The same can be done using any number of other similar devices, such as the FT232R etc.

You cannot directly connect the USB to the 2560 since the 2560 has no concept of what USB is. The 16U2 has that knowledge, but doesn't have as many IO pins as the 2560, so combining the two gives you a total system that both understands USB and has lots of IO.
> 2 votes

# Answer
> Someone suggested to me that I could in fact do away with the Atmega16u2 all together (this would drastically reduce my component count and free up valuable board space)

I recommend that you keep the '16U2 and ditch the '2560. Since the '16U2 is both native USB capable *and* has sufficient I/O for a MIDI controller then you should use *that* one for your project.

Of course, since there's no Arduino core for the '16U2 you may want to consider either learning AVR programming without Arduino (when will there be a better time to do so?), or switching to the (overpowered) 'U4, which uses the Leonardo core.
> 1 votes

# Answer
> if I can indeed interface a usb port directly to the ATmega2560

You cannot interface USB directly to the ATMega2560, because that µC has no USB support build into (and VUSB is probably no solution either).

If your program is simple enough, then it could fit onto the ATMega16U2 on its own, eliminating the 2560.
> 0 votes

---
Tags: bootloader
---


# Question
Title: Shift register 1's and 0's array to 4 int's function not working
I'm not sure if i should post this here or on StackOverflow but I am coding for an LED cube controlled with 4 shift registers. I have a function in a .h file that is supposed to take an array of 1s and 0s (to represent each LED) and then use the shiftOut function to shift the data into the shift registers. This is complicated that the shiftOut function has to take a int which it shifts out in binary and only goes 8 bits at a time. This means I have to separate my array into 4 groups of 8 and then convert each group into an int. I have tried to make my function do that but it is compiling fine and then not lighting up any LEDs. I believe the problem has to do with the way I'm separating the array into 4 smaller arrays althoughI can not figure out exactly what is going wrong, here is my code.

Main program:

```
#include <LEDcube.h>

int data = 2;
int clock = 3;
int latch = 4;

void setup()
{
  pinMode(data, OUTPUT);
  pinMode(clock, OUTPUT);
  pinMode(latch, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  int layer[32] = {0,

                  1,1,1,1,1,
                  0,0,0,0,0,
                  1,1,1,1,1,
                  0,0,0,0,0,
                  1,1,1,1,1,

                  0,0,0,0,0,0};
  write(data, clock, latch, layer);
}

```

LEDcube.h:

```
#include "Arduino.h"

int binToNum(int bin[])
{
  int j = 1;
  int num = 0;
  for(int i = 0; i < 8; i++, j = j * 2)
  {
    if(bin[i] == 1)
    {
      num = num + j;
    }
  }
  return num;
}
void write(int data, int clock, int latch, int layer[])
{
  int reg1[8];
  int reg2[8];
  int reg3[8];
  int reg4[8];
  for(int i = 0; 1 < 8; i++)
  {
    reg1[i] = layer[i];
  }
    for(int i = 0; 1 < 8; i++)
  {
    int q = i + 8;
    reg2[i] = layer[q];
  }
  for(int i = 0; 1 < 8; i++)
  {
    int q = i + 16;
    reg3[i] = layer[q];
  }
  for(int i = 0; 1 < 8; i++)
  {
    int q = i + 24;
    reg4[i] = layer[q];
  }
  int regnum1 = binToNum(reg1);
  int regnum2 = binToNum(reg2);
  int regnum3 = binToNum(reg3);
  int regnum4 = binToNum(reg4);
  digitalWrite(latch, LOW);
  shiftOut(data, clock, MSBFIRST, regnum4);
  shiftOut(data, clock, MSBFIRST, regnum3);
  shiftOut(data, clock, MSBFIRST, regnum2);
  shiftOut(data, clock, MSBFIRST, regnum1);
  digitalWrite(latch, HIGH);
}

```

# Answer
> 1 votes
The problem is you need to write your data with all of your bits consolidated into a single integer instead of as an array of integers. For example, if you were to `shiftOut(data, clock, MSBFIRST, 1)` that would send `00000001`, not `1`. So for example, if you want to send out 1,0,1,0,1,0,1,0 you need to send `shiftOut(data, clock, MSBFIRST, 170)`, because 170 in binary is 10101010. So you will need to figure out how to represent your data as an integer rather than array of integers of which you are only using the first bit.

**EDIT**:

I see that you are attempting to do a binary conversion, but your for loop is a little off. Try this instead:

```
for(int i = 0; i < 8; i++)
{
  if(bin[i] == 1)
  {
    num = num + j;
  }
  j = j * 2;
}

```

Even if that fixes it, you will probably still need to some major refactoring to get decent speed, currently you are using 128 bytes of memory to represent 4 bytes worth of data. and there are plenty of other little inefficiencies here and there.

**EDIT 2**:

The simplest version of the above functionality is this:

```
int data = 2;
int clock = 3;
int latch = 4;

void setup()
{
  pinMode(data, OUTPUT);
  pinMode(clock, OUTPUT);
  pinMode(latch, OUTPUT);
}

void loop()
{
  int data1 = 0b1111100000111110; //Set a variable using a binary constant
  int data2 = 0b0000111110000000;
  digitalWrite(latch, LOW);
  shiftOut(data, clock, MSBFIRST, data1);
  shiftOut(data, clock, MSBFIRST, data2);
  digitalWrite(latch, HIGH);
}

```

If you are going to be doing more bit level manipulation, you should probably learn various bit wise operators such as \<\<, \>\> &, ^, |, ~, &=, and |=. The Arduino documentation goes over them and what they do (scroll down, on the left under Bitwise Operators).

# Answer
> 1 votes
As noted in Stu's answer, the question's code does not pack bits properly into the bytes that `shiftOut()` will unpack them from.

If you merely want to make things work, as opposed to packing stuff up one place so it can be unpacked another, just write the bits to your SR yourself. For example:

```
for (int i=0; i<32; ++i) {
  digitalWrite(data, layer[i]); // Put a bit on the data pin
  digitalWrite(clock, HIGH); // Pulse the clock
  digitalWrite(clock, LOW);
}
digitalWrite(latch, HIGH); // Pulse the latch
digitalWrite(latch, LOW);

```

If the clock or latch need low-going instead of high-going pulses, reverse the order of writing `HIGH` and `LOW`.

---
Tags: c++, shift-register
---


# Question
Title: What Driver IC to use for 40v 2amp DC motor?
I am using a 40v 2amp 3300rpm DC motor for my motor control project via arduino. But i don't know what driver ic to use for driving the motor.any help would be appreciated..

# Answer
> 1 votes
I am assuming since you did not state anything differently you simply want to turn it on or off and possibly PWM to control speed of the motor. By far the easiest way is to simply use a N-Channel logic level MOSFET. Connect the Arduino pin of your choice through a 51 (1) ohm resistor to the gate of the MOSFET, also Connect a 10K (2) resistor from the same microprocessor (Arduino) pin to ground. The "Ground" low side of the 40V power supply needs to be connected to the low side of the Arduino. The low side of the 40V power supply must be connected to the source of the MOSFET.

Connect the motor from the plus side of the 40V power supply (this will be removed for testing) to the Drain of the N-Channel MOSFET. Last and very important place a diode rated at least 2 amps at 60 volts from the positive side of the poser supply (cathode of the diode, with the band) to the Drain of the MOSFET (anode, no band).

Carefully check your wiring; if it is ok you are ready to test it. The safest way is to use a led with a 510 ohm in series with the cathode on the Arduino +5 with the positive side of the 40v power supply disconnected. The anode side connects to the drain of the MOSFET. When the motor is turned on the LED will light, if it does not reverse polarity of the LED. As tempting as it might be do not leave the LED connected to the Arduino when the motor is connected. Up the value of the resistor to about 5.6K and connect it across the motor, it will light when the motor is on.

1. This helps dampen oscillations
2. Since the Arduino initializes with all pins as inputs this can drift high, this solves that potential problem which would cause the MOSFET to turn on.
3. For the MOSFET you need at least 60V with a 10A rating. This should work with a small heat sink. If you go to a higher amp rating on the MOSFET it will operate cooler.

Output of Arduino goes to 10K to ground and to a 51 ohm resistor (1/8 W or larger) The other side of the resistor goes to the gate of the MOSFET. Ground of the motor power supply, the Arduino and the Source of the MOSFET are connected together. The 2A diode is connected with the cathode (no band) to the drain of the MOSFET, the cathode (band) is connected to the +40V. The motor connects from the +40 to the Drain of the MOSFET, reversing the leads will probably reverse motor direction.

Good Luck, Gil

---
Tags: motor
---


title: ACS712 inacurrate reading. Wild jumping

text:
# Question
Title: ACS712 inacurrate reading. Wild jumping
I'm trying to use my 30A ACS712 on my OSD (it has ATMEGA16L).

But it is very unstable, 0 amps goes from 450 to 445, but that isn't that bad, but when I put 10A of current through it jumps from 440 to 380.

I already searched on google and tried to add filter cap between acc and gnd, but it didn't help and acs712 and osd have different power supply than the load.

Any help is welcome.

# Answer
This is not a simple chip to use. These parts of the data sheet may help you understand what is happening. It is internally an analog device and needs clean power. I would highly recommend you download the Allegro data sheet, it has a lot of information that will help you. Below is a short section of the data sheet, The first paragraph should give you a hint that the output voltage will be about 2.5V with a 5V unipolar power supply.

"Quiescent output voltage (VIOUT(Q)). The output of the device when the primary current is zero. For a unipolar supply voltage, it nominally remains at VCC⁄ 2. Thus, VCC = 5 V translates into VIOUT(Q) = 2.5 V. Variation in VIOUT(Q) can be attributed to the resolution of the Allegro linear IC quiescent voltage trim and thermal drift.

Electrical offset voltage (VOE). The deviation of the device output from its ideal quiescent value of VCC / 2 due to nonmagnetic causes. To convert this voltage to amperes, divide by the device sensitivity, Sens.

Accuracy (ETOT). The accuracy represents the maximum deviation of the actual output from its ideal value. This is also known as the total output error. The accuracy is illustrated graphically in the output voltage versus current chart at right."

I realize this does not answer your question but it does give you a good starting point to resolve your problem. Hopefully you or a buddy has some analog experience, that will help a lot. Oh Yes clean power supplies are imperative for this to work.
> 2 votes

---
Tags: current, adc
---


# Question
Title: Using digital weighing scales with INA125p
Complete electronics beginner here. I'm attempting to build a weighing scale with an Arduino.

I'm attempting to follow this tutorial, with the shield that they use.

I've arranged my load cells on the scale into a Wheatstone Bridge, and I can get some readings just by taking a voltage reading from the two cells marked V+ and V-. The board has terminals that are linked to a INA125p, and the pins should give an amplified reading.

```
Pin A1:0.96
Pin A2:1.42
Pin A3:5.00
Pin A4:5.00
Pin A5:5.00

```

Regardless of whether I have the scale wired in or not, I get these readings from the individual pins. The scales seem to be able to take power from the Arduino shield.

The scales that I have are different from the ones in the example. From what I can figure out, the yellow cables that they reference turn their particular scale on when weight is put on it.

I've put the wires where I take the reading into the 2 and 4 terminals on the circuit board that they have (where the tutorial references a differential signal), but again, it makes no change.

> unsolder or cut the white wire that is referred to as G3 (Wheatstone bridge mass) on the original printed circuit, extend take it to terminal 1 on the new printed circuit;
>
> unsolder or cut the white wire that is referred to as G2 (Wheatstone bridge positive) on the original printed circuit, extend take it to terminal 3 on the new printed circuit;
>
> unsolder or cut the white wire that is referred to as G1 and G4 on the original printed circuit, extend take it to terminal 4 and 2 on the new printed circuit (differential signal on the Wheatstone bridge)

I've attempted lots of different combinations of cables and terminals on the new circuit, but it appears to make no difference to the readings.

My question is: Based on the tutorial and the drawing above, am I taking the readings from the correct place? Are there any things I'm obviously doing wrong with the circuit itself? If the circuit is correct, how would I go about trying to get correct readings from the scale when I add weight to it?

I apologise for the vague nature of this question, but I am a complete beginner trying to figure this out, and I am struggling to follow the tutorial. I'll try and provide any additional information that you need.

EDIT - I have a Salter SAL-3003 SSSVDR08 scale.

Each load cell has 3 cables, Red, Black and White. The red ones are the ones marked with the V+, V- etc. On the original board, they were wired in threes.

# Answer
> 2 votes
Fixed (to some extent)! Faulty connection between the INA125p and the plint it was sitting in. I refitted it and i'm now getting varied readings with the scales, but that's to be expected with the noise the INA125p generates.

---
Tags: arduino-uno, shields, analogread
---