text:
Potentiometer on motor for position control
I am using a wiper motor as a rotor. I am trying to get it to at least point in different azimuths (compass azimuths eg. 180 degrees) In order to do this, I am thinking about attaching a potentiometer on the axle inside the motor housing to see where the motor is pointing.
So lets say the pot gives me a range of 0-1023. If I divide 1023 by 360 i get 2.84. So lets say the pot gives the Arduino a 1, I can relate that to 2.84 degrees?
Also, what if the motor is pointing at 350 degrees, and I want it to point at 2 degrees. Instead of it turning around 348 degrees, it just cross pass 360 and go to 2 degrees.  How would a pot handle going over a single step? If the motor passed a single step would it consistently give me a 1023 reading?
I am trying to get a wiper motor to have a known position 360 degrees around.

Most pots have a interrupted circle, made of something like carbon, with a wiper moving along it. Moving from one side of the circle to the other side of the interrupted circle, means the wiper will be disconnected for a few degrees, giving you some random analog value (unless you have a pull-down). You won't be able to measure the angle around this point. You could use two pots with there "0-point" opposite of each other. Or go with a rotary encoder, combined with a home-position sensor.

I am trying to get a wiper motor to have a known position 360 degrees around.

There might be a few possibilities.
First there are continuous rotation potentiometers on the market. They seem expensive though and I can't comment on how accurate they are.
Second, if your device is only ever going to turn through say ten revolutions then go back, you could just get a multiturn pot that will handle that range of turns. (Depends what you're building of course - for example I've heard of servo winches for model sailboats that use this method.)
Thirdly, and I accept this may not be a good answer to your question, but have you thought about using incremental encoders instead? In theory they could be more accurate too. The hardware is quite easy but a bit more programming is required to make these work...

The device in theory should only rotate once. No more than 5 times if need be. So I guess a mulit turn pot would be in order!

So lets say the pot gives the Ardunio a 1, I can relate that to 2.84
  degrees?

Yes, if the pot goes from 0 to 1023 in 360 degrees of rotation, and it can rotate continuously. That sounds unlikely - f/ex, thinking about how a pot is made, how will it get from its maximum resistance to its minimum resistance in 2.8 degrees?

Instead of it turning around 348 degrees, it just cross pass 360

Smart software. :) You would need to read the pot, decide which direction of rotation will get from the current position to the new position, and select that direction in the motor drive circuit.
Update:
A pot doesn't really "output" anything; it is a variable-resistor, whose resistance can be measured by placing it in a known electric circuit and using an Arduino A2D input to measure a voltage in that circuit which depends on the resistance of the pot. The reading you get is a 10-bit integer. If you divided that by 1024, you'd have a pure fraction representing the measured voltage as a fraction of the A2D's full-scale voltage, which you select as INTERNAL (1.1v internal reference voltage), or EXTERNAL and apply a reference voltage to the chip's Aref pin. Usually that is the power-supply voltage, and in any case must not exceed the power-supply voltage.
So, back to reality, if you use the EXTERNAL reference with Aref connected to +5v, then the A2D readings would mean:

 A2D  Volts  Mag.Azimuth
   0   0       0
 256   1.25   90
 512   2.5   180
 768   3.57  270
1023   4.99+ 359.6

In this case you probably don't care about the measured voltage, only it's relationship to 5v, which the A2D already gives you. That relationship equals the pot's relationship to 1 full rotation. So the azimuth, Az, you're seeking:
Az/360 = A2D / 1024, and
Az = (A2D * 360)/1024

I am thinking more along the lines of, if the pots reading at 511.5, then the motor is facing 180 degrees (half of the 360 magnetic degrees) I am referencing the position of the pot, to magnetic azimuth.also, how would i say the pot is reading at 511.5. What unit does the pot output? Ohms?


text:
HM-10 discovery issue
i am not able to detect any android device on my bluetooth HM-10 module which is connected to arduino. i am able to see my bluetooth module on my android phone. but i want to see android phones on arduino serial monitor for that i used AT+DISC? command. it shows AT+DISCS and than AT+DISCE with a 2 second interval. help me to solve the issue
thanks in advance

The HM-10 is a BLE-only device.
Android phones do not normally transmit BLE advertisements, so there is normally nothing about an Android phone for it to discover.
The exception would be if you have software on a late Android version with the capability, which you have set up to intentionally transmit BLE advertisements, or else if software you put on your Android phone is actively responding to advertisements you had the HM-10 transmit.
Essentially, you are expecting something that his not normal behavior, but will only be achieved by adding your software on both devices.

Good answer, it's like my laptop seeing all wifi connections. But my accesspoint not seeing all (unconnected) devices. It depends on which device is the "searcher" and which is "advertising itself". In practice, most devices don't do both.

Detecting the physical Bluetooth layer is likely different from detecting the underlying protocol.  So it might be that the Arduino code is waiting until it sees a specific Bluetooth protocol.  I am guessing that it wants to use a serial Bluetooth protocol (as oppose to music or some other protocol).  You have not given enough details to determine if this is the problem.  However, I would next test your devices / hardware by loading up what is assumed to be working code on both your Android and your Arduino to test the connection.  The code in this project looks promising:

is there any way such that i can make the protocol compatible since my hm-10 is getting detected on various mobile devices. my project requirement is such that i have to detect the mac id of other phones near the range of hm-10.

MAC is a feature of the phone's WIFI. I wouldn't expect the MAC information to be available on the Bluetooth port without an application on each phone specifically written to do tHis.

@st2000 MAC addresses are not confined to wifi, Bluetooth has its own as well.

source: Stack Exchange

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

sort: votes


text:
Not getting data from GPS
When I run FullExample program from TinyGPS++, I get following types of entries,
Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum
          (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail
---------------------------------------------------------------------------------------------------------------------------------------

0    9999 ********** *********** **** 07/01/2016 07:32:50 689  ****** ****** ***** ***   ******** ****** ***   75128 0         0
0    9999 ********** *********** **** 07/01/2016 07:32:51 857  ****** ****** ***** ***   ******** ****** ***   75389 0         0
0    9999 ********** *********** **** 07/01/2016 07:32:52 864  ****** ****** ***** ***   ******** ****** ***   75642 0         0
0    9999 ********** *********** **** 07/01/2016 07:32:53 870  ****** ****** ***** ***   ******** ****** ***   75895 0         0
0    9999 ********** *********** **** 07/01/2016 07:32:54 878  ****** ****** ***** ***   ******** ****** ***   76148 0         0

Other details:
GPSBaud = 9600;
RXPin = 11;
TXPin = 10
Module: GY-NEO6MV2

you've failed to mention which GPS module

@JaromandaX: I have updated he module name.

That is a perfect printout of a GPS system that can see zero satellites.
The fact that the timestamps are one second apart shows that you have correctly interfaced with the GPS device. Now, the GPS device has to 'interface' with the satellites!
Many people don't realise two things:

The GPS antenna really does need a clear view of the sky. A tiny view through a window may show one or two satellites, but you need a minimum of three, and preferaby four or more at a number of points around the sky to get a fix.
If the GPS unit has been completely powered off (called 'cold'), when it first powers on it has NO idea where anything is. It simply listens for any signal anywhere until it "hears" the current time. It can then guess where satellites might be, and listens for updates on satellite positions.

All of this listening, guessing and waiting takes time before it can start to actually lock on to satellites and start to get a fix. This time could easily be 90 seconds or more - you need to be patient. Check your GPS device specifications for "cold start" times.
Edit
I'm impressed! The GY-NEO6MV2 that you list has a cold-start of 27 seconds - but that assumes it has a clear view of the sky.

Yes, putting it outside, I get 6 sats. Thanks.

The GPS actually seems to be getting some data: the date and time.
Which means it can be used to set the time (and date) in a clock if the timezone is known without needing a fix (useful inside).

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

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


text:
Arduino i2c communication between another arduino and a sensor
Can the following scenario exist?

Microcontroller 1 sends a code to microcontroller 2 to start reading sensor data. Then Microcontroller 2 reads sensor data from sensor and sends it back to microcontroller 1.
If such a scenario is possible, then how would the pseudo code for microcontroller 2 receive-event be?
Need help with this badly!!

Can the following scenario exist?
  Yes. Such a scenario is called Multi-Master.
If such a scenario is possible, then how would the pseudo code for microcontroller 2 receive-event be?

MCU 2 would just be set up as any other slave. It waits, as normal, for an instruction in whatever for you like. Once it receives that instruction in then switches into master mode and makes a normal request exactly as you would from MCU 1 if you wanted it to read the sensor.

On receive:

Set "run as master flag"
Disable slave mode

In loop:

If "run as master flag" is set:

Perform request to get data from sensor
Clear "run as master flag"
Enable slave mode

Running a multi-master system does have its own set of caveats and things you have to watch out for. You can read more about it here:

https://www.hackster.io/chipmc/arduino-i2c-multi-master-approach-why-and-how-93f638

Thanks for the heads up regarding Bus arbiteration. Will try this out and hopefully, it works!

Hi again, wanted to try out your soultion, but had this question -How do you enable or disable slave mode on the arduino?


text:
Unusual behaviour over serial communication
I am sending data over serial connection from a python script to my Arduino UNO. Now initially whenever I tried to send data to the arduino, it would reset. The fix was to put a 10 microFarad capacitor between the 5V and RESET pins. I did that and everything started working.
Now after while,  mistakenly today I ran the same script without the capacitor between the 5V and RESET pins and for some reason it was working perfectly well. No more resetting when a value was received over serial communication.
Is something wrong with my Arduino?

The reset only occurs if you create a connection. So as long as the python script keeps the connection open, not further resets will occur.

Which OS are you using?

@Majenko Win 10 Home Premium

This reset on connection behavior is ultimately under software control of the host operating system and is usually configurable.  If you can still program the board through this connection (without your modification installed), the hardware is fine.

Knowing the entire setup would help.  For instance, knowing if the RS232 source will drive the Arduino input's dangerously past the Arduino's power rails.
If you have connected a real RS232 signal to the Arduino, the +12 to -12 volt swings could adversely affect the processor.  Causing unexpected behavior.  In such a case you would need a converter like this one.
Over driving inputs is discussed in this Stack Exchange question where the highest scoring answer says:

If you violate the spec sheet normal operating conditions requirements
  you can expect to experience abnormal operating conditions. These may
  range fro perfectly normal opration through complete maloperation...

That answer also links to this tutorial about logic level conversion.
Finally, there is this tutorial which specifically addresses converting RS232 to safe TTL level signals appropriate for a micro processor.

I am connected to a motor driver, which is connected in turn to a motor.

We would need the specifications of the serrial interface. Maybe that could be foubd from the modle number of the motor driver? It is starting to sound like you need the proper interface.

No its not like I'm having a problem here. In fact not having to connect a capacitor between the 5v and RESET pins saves me the hassle of connecting a mini breadboard. Thing is that how can all of a sudden the absolute need of a capacitor between 5V & RESET disappeared?

When driving digital integrated circut inputs beyond the power supply rails, the state of the integrated circuit is indeterminate.

There is no reason to believe the poster is using RS232 signalling at all, especially as if they were they would have had to explicitly hook up a connection between a modem control line and the reset to trigger this, rather than what they did do which was add components to defeat such an apparently forced connection.   All evidence suggests they are using the Arduino's build in USB serial converter, which has such a modem line to reset connection as part of it.


text:
I want to play a sound based on my ultrason sensor reading
The idea is to play the tone that is given by the center value read it by the center ultrasound sensor.
The code that is in Arduino is this one:
#include NewPing.h

#define PING_CENTER  2  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
#define PING_RIGHT  3
#define PING_LEFT  4
#define PING_MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define buzzerPin = 10

long buzzerFreq1; // The frequency to buzz the buzzer
unsigned int BUZZ_FREQ_MAX = 2500; // Maximum frequency for the buzzer
unsigned int US_MAX = 2023; // Maximum value for ultrason sensor
int c1;

NewPing sonar2(PING_CENTER, PING_CENTER, PING_MAX_DISTANCE); // NewPing setup of pin and maximum distance.
NewPing sonar3(PING_RIGHT, PING_RIGHT, PING_MAX_DISTANCE);
NewPing sonar4(PING_LEFT, PING_LEFT, PING_MAX_DISTANCE);

void setup() {
  Serial.begin(9600);
  pinMode(buzzerPin, OUTPUT); // set pin for buzzer output
}

void loop() {
  buzzerFreq1 = (center * BUZZ_FREQ_MAX) / US_MAX;
  buzz(buzzerPin,buzzerFreq1,10);
  // tone(buzzerPin, center);
  delay(500);  // Wait 500ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int center = sonar2.ping() / US_ROUNDTRIP_CM; // Send ping, get ping time in microseconds (uS) and convert it to centimeters (cm)
  unsigned int right = sonar3.ping() / US_ROUNDTRIP_CM;
  unsigned int left = sonar4.ping() / US_ROUNDTRIP_CM;
  // Serial.println("Distance: " + String(distanceInCms) + "cm");

  Serial.println(center);
  Serial.println(right);
  Serial.println(left);

}

 // buzz(buzzerPin, buzzerFreq1, 10);
 void buzz(int targetPin, long frequency, long length) {
 // int c1 = center;
  buzzerFreq1 = (center * BUZZ_FREQ_MAX) / US_MAX;
  long delayValue = 1000000/frequency/2;

  int numCycles = frequency * length/1000;

  for (int i=0; i < numCycles; i++){
    digitalWrite(targetPin,HIGH);
    delayMicroseconds(delayValue);
    digitalWrite(targetPin,LOW);
    delayMicroseconds(delayValue);
  }
}

And I receive the following error that I have no idea how to solve it.
ultrason_onewire_sound.cpp: In function ‘void setup()’:
ultrason_onewire_sound.cpp:26:11: error: expected primary-expression before ‘=’ token
ultrason_onewire_sound.cpp: In function ‘void loop()’:
ultrason_onewire_sound.cpp:38:8: error: expected primary-expression before ‘=’ token
ultrason_onewire_sound.cpp: In function ‘void buzz(int, long int, long int)’:
ultrason_onewire_sound.cpp:48:18: error: ‘center’ was not declared in this scope

#define buzzerPin = 10 shouldn't have an = in it.
With the = pinMode(buzzerPin, OUTPUT); will turn into pinMode(= 10, OUTPUT); by the pre-processor. Which would give the error, complaining about an = token, you got.

You should use arduino built in tone command to play sounds with a buzzer, it will simplify your code and your errors.


text:
Append to .h file through arduino code
I'm at the stage where I can #include headerFiles.h into my arduino sketches.
I'm just beginning to wonder whether it's possible to append strings that are concatenated from integers which are analogRead from sensors to a .h file?
It'd make the arduino a lot more portable and would negate having to buy an SD card module.
How would the data be extracted? EEPROM is too small for datalogging past what you'd rack up in text over a reading every minute for a few hours.
Any clever clogs got ideas for this?

open the .h file with an editor and write stuff into it, easy as that.

Header files only exist on your development machine, not on the Arduino, so can only be modified with the involvement of the former, and the changes only take effect when you rebuild and reflash the sketch.

There are external serial EEPROM/flash memory chips which may be easier to deal with than an SD card (from the Arduino side); search for "spi flash". And then there's also OpenLog.

How much memory do you need? Kilobytes? Megabytes? Gigabytes?

Header files are part of your source code. The result of a build is a set of ones and zeros which are sent to your arduino and written in its Flash memory (the program space). The way you put these zeroes and ones together is completely up to you. You could write C and/or C++ code (where you have header files), you could write assembly code or you could write the zeroes and one directly on the disk, if you are crazy enough.
Header and Source files live only in the world of the developer and its toolchain, Arduino doesn't know they exist at all.
That being said, if you want to store log data you could use a SD card like you said, or send it over the network, or you could use a serial connection. But I'm sure there are plenty of other options.

Header files are used to "encapsulate" functionality of your code. When you #include a header file, what you are actually doing is, as perhaps an oversimplification, "pasting" the code from that header file into your sketch above where the main code you've written in that file resides. You can then call on functions defined in the header file. Usually, at this level, you are using header files to include useful code that other programmers have contributed to a "library" that has some functionality that makes your life easier -- UART or Wire for communication, or perhaps being able to write to one of Adafruit's LCD displays with a single function call.
Programmers will also write their own header files to improve readability of their code -- for example, by encapsulating all code related to a particular functionality, perhaps troubleshooting, in one file. Another header file in the same program might, a bit ironically, be dedicated to input/output functions (but in the sense that it handles the reading and writing of data on some storage medium, such as an SD card). Header files can also #include other header files (if you're careful about how you do so).
However, header files are not usable "input/output." The compiler will read it all as one program and flash it to the Arduino just like any other code you have written.
http://www.learncpp.com/cpp-tutorial/19-header-files/

I'm just beginning to wonder whether it's possible to append strings that are concatenated from integers which are analogRead from sensors to a .h file?

No, you have the wrong end of the stick here. You can't write to a .h file, certainly not on the Arduino, because it is running independently of the development environment.

It'd make the arduino a lot more portable and would negate having to buy an SD card module.

An SD module, like the one below, only costs about $US 15, and then you can write gigabytes of data to it, and then easily move the SD card to your PC to process it.


text:
Driving single-character alphanumeric (16-segment) displays
I would like to drive three sixteen-segment displays (https://www.sparkfun.com/products/retired/9934) using an Arduino Micro. These displays would output an alphabetic character that a user would scroll through using rotary encoders, and constitute a subsystem of a larger project where the user enters a "combination" made from the three letters to "unlock" functionality in the larger device.
The best option, if it could be called that, is this retired product from SparkFun: https://www.sparkfun.com/products/retired/10103 that would allow me to drive the displays without a huge wiring mess, and spares me a lot of pins on the Micro to use on the rotary encoder. Unfortunately, the product is retired because the A6282 IC it was based on reached end of life, so even the schematics available on the product page aren't much use to me.
I am aware that four-character 16-segment displays are available, but for "aesthetic" reasons I am constraining myself to using single-character 16-segment displays. I do wonder how possible it would be to run three or four individual 16-seg displays from one of those LCD backpacks, but I don't think that would be trivial to do (I'd need to, probably, fabricate some sort of printed circuit board that spaced each display as far out as I need them to be, hook the pins of each display into a key matrix, and then at that point it'd be substantially easier to just get a MAX6954 (https://www.maximintegrated.com/en/app-notes/index.mvp/id/3212) and try to figure that out). It would be very clumsy to prototype.
So, I'm looking for a solid method of prototyping this "combination entry" subsystem and its 16 segment displays without needing to put each dial and alphanumeric display on its own AVR or something.

You mean like with a shift register or LED driver IC?

I sell these. Could be what you want - wire it direct to a common-anode display and communicate with it over I2C. UP to 14 of them can be chained together.

I'd prefer to use some sort of driver IC like the discontinued model I refer to as being formerly available from SparkFun. I feel like if I have to go to shift registers, then what will inevitably happen is that I either have to assign a small AVR to each character display and rotary encoder, then feed all of these into another microcontroller that will assemble all of that into a coherent combination. I'm willing to do that, but it will mean that this little subassembly will cost over $60, which hurts the larger project's reproducability.

@Majenko That actually looks like it would be perfectly suitable. Thank you.

If you need additional IO lines, a typical “LCD backpack” supplies at most eight additional lines of IO; 16-channel TLC59116 LED Driver Board as mentioned by Majenko would be more elegant than using several backpacks.
You might try an approach like the following to see if it works well enough.
Use 16 IO lines to pull down 16 segment lines.  Use three IO lines to drive three digit-select PNP or PFET transistors for digit multiplexing.  Use pin-change interrupts on two IO lines to read rotary encoder (RE) data.  Use one input to read the RE pushbutton.  Use one IO line to notify the bigger unit of success.  Total 23 IO lines.
In operation, your code will need to implement a state machine that frequently refreshes the multiplexed digits while keeping track of digit values, selected digit, etc.  Each time you click the RE have your sketch go on to the next digit.  To tell the user which digit is working, blink the selected digit a couple of times after the RE press.  Each time that selection wraps around to the first digit, check if the combination is correct.
If you feel it's necessary to have three different digit-setting knobs, vs clicking through to each digit, you could use one less IO line by using three pots instead of one RE.  The pots would be read in analog.  A6 and A7, IIRC not usable for output lines, could be used as analog inputs for two of the pots.

The other answers give great suggestions, but to add to them you could consider the MAX7219 driver chip. I have a page about using it. It can drive a 8x8 pixel display (like one alphanumeric character) or 8 x 7-segments displays (a 7-segment display usually has a decimal place so that is really an 8-LED display).
Example of 64-pixel display:

Example of 8 x 7-segment displays:

Those displays come as a unit (2 x 4 digits) but there is nothing stopping you running wires to individual 1-digit displays if you want to.
Here is a possible schematic:

If you are running to individual displays you just parallel-up the anodes (A to G, plus DP) and run a "digit" line to the cathode of each display.

That will only take 3 signals from your processor (MOSI, SCK, SS) plus power and ground.

I notice you are talking about 16-segment displays and not 8-segment displays, but the chip allows any bit patterns to be sent out, so you could consider a 16-segment display to be the same as 2 x 8-segment displays. You would just have to make up a suitable bit-pattern to show each digit.
The MAX7219 also handles the requirement for constant-current driving of the LEDs.


text:
Can you output to D+ and D- so that Arduino Uno can be used as a USB device?
My project is basically a set of 5 audio signals (analog) that get altered slightly by Arduino Uno. I convert to MIDI and would then output it to USB, so that it can be used in a program of my choice on the computer. I found a vaguely similar project online with a guide. In that project they write a serial to a MIDI out, and then plug that into a computer. I'm fairly sure I can't just use the TX and run that into the USB, that wouldn't work. So I'm looking for an alternative method.

Not directly, and not in the way you're thinking of.

Would it be better to use the digital output to connect to a midi connection, or do you need it to connect to USB?

Look into V-USB.

Andy, I can not figure out what you are trying to do.  Are you going from an Arduino to a computer using the computer's USB port?  If so, why are you converting to MIDI?  Also, USB is really complex.  Most people do not realize there are many protocols inside a USB signal.   Simply having a USB device is in no way a guarantee that any given program will even work with that device.

Why not just use the Uno's USB port?  The same one used for programming.  I use them all the time to communicate measured values back to Raspberry Pis and to receive commands that trigger output pins...  And the best part is that I can WiFi into the Rpi with RDP and run the IDE to preprogram them out in the field.  In other words, why reinvent the wheel?  That USB-to-serial port works fine bidirectionally already using the Serial functions.

Not with an Uno, no. You can only use USB Serial (CDC/ACM) through the on-board USB chip[1].
Your best bet is probably with a Teensy 3 (or 3.1 or whatever they are up to now) which has built-in support for USB MIDI emulation.

1: I believe there is MIDI firmware for the USB chip on the Uno, but installing that requires a hardware programmer and then breaks the normal sketch upload.

Actually, you can come "close enough" with an Uno by using a V-USB.

@ChrisStratton If you are masochistic enough, sure. Personally I wouldn't touch it even with someone else's barge pole.

It's not without concerns, but it seems to be rather exactly what the question is asking about.

I refuse to endorse it or ever tell anyone to use it.

As noted in Majenko's answer, an Uno would require some non-trivial modifications before it would be usable as you want.
Some Arduino models – Leonardo and early Pro Micros – were based on ATmega32U4 chips instead of ATmega168 or ATmega328 chips.  The 32U4 has USB support built in.  The Mouse and Keyboard libraries allow interacting with a host computer such that from the host the Arduino looks like a mouse or keyboard.

Its rather odd for you to call these "old" as they were all released after the Uno.  Also the Due did not use an ATmega/AVR but rather an Atmel ARM Cortex-M3 while the Zero has a Cortex M0+.

The simpler thing would be to output the MIDI through the serial port, and then convert that into MIDI voltage levels like this:

Then plug that into a suitable MIDI-to-USB adapter. However I would have thought that that extra step (converting to MIDI voltage and back again) would be unnecessary. Can't your computer read MIDI directly from serial? I mean, the Uno has a USB interface. If you send MIDI data at 31250 baud, how is the program on the PC going to know it isn't a real MIDI device on the USB port?

Operating systems expect midi-over-USB devices to identify themselves as such, not as serial or modem devices.

@ChrisStratton  Yes but a MIDI to USB adapter would surely do exactly that? I wasn't talking about putting serial straight into the computer. I mean, that's what they are made to do.

"Can't your computer read MIDI directly from serial?" does rather imply getting it to treat an everyday serial stream as midi data - something that is possible, but outside of typical software configuration, ie, it probably needs a custom or obscure driver, or to skip any operating system MIDI support entirely and just take the data into the application that wants to use it.

@ChrisStratton Oh, OK. My suggestion of the MIDI to USB adapter would not have that issue. You are probably right about the drivers. I see such adapters are available on eBay for around $US 7 to $15.

Yes, something that's USB information presents itself as a MIDI device should work for the host meaning the challenge is electrical.  While something that presents as a serial device (and has a TTL inteface) is Arduino-friendly electrically, but would require atypical host drivers or software to be treated as a source of midi data.


text:
Connect 2 Arduino UNOs via Bluetooth? (HC-05 and HC-06)?
So I've researched this topic a lot online, but haven't found what I'm looking for. Before I tell you this, I'll give you guys an idea of what I'm trying to accomplish. Please understand that I'm an extreme beginner to Arduino, and that I've only been at this for a month or so, but plan on doing so much more.
My friend and I are building an RC car. We have an Android phone that has a downloadable application which connects to the Bluetooth HC-06 module that is on the Arduino UNO. We have configured our circuit, and it works fine! I want to go a step above and beyond, though.
My goal is to build a physical, handheld controller or remote (literally plopping everything on a breadboard), and connect that controller or remote to our car using Bluetooth. We have an HC-05 and HC-06 module, and the HC-06 is on the car. Now comes the doubt.
I understand how the android application sends characters through to the RC Car via Bluetooth; that's pretty straightforward as the two pieces are paired (using Android's Bluetooth Settings). What I don't understand is how to pair the two HC-05 and HC-06 Bluetooth modules. There isn't too much help online, I feel. I've looked and people have shown that they connect, but they don't explain the theory, so to speak.
What I want to understand is:

How the two HC-05 and HC-06 modules pair, and
How can I read input from one (remote controller) and execute an action on the other (RC car). From the app-to-Arduino, I was using Serial.available() to see if the Serial had any characters sent over from the application. I can't see how I can do that with HC-05 to HC-06 pairing, however. This concept is hard for me to grasp.

Any help is greatly appreciated. Thank you!

You need to set HC-05 to master, and this done by soldering pin 34 of BT and connecting it to digital pin on Arduino to enter AT command. Then after powering the Arduino, you need to put pin 34 high. This way it will enter AT command. In serial monitor, follow these AT commands:
AT+cmode=0
AT+ROLE=1 // THIS WILL SET THE BT AS MASTER
AT+INIT
AT+LINK= ????,??,??????  // REPLACE ?... WITH HC-06 MAC ADDR

Have a look at this for how to pair them http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link basically you need to use the AT mode.
As far as I know you will be using the serial connection to communicate, but if you are using UNOs debugging becomes a bit more difficult, because you can't use serial for debugging.

For this you just have to pair the both bluetooth modules with each other.!
For this use AT commands.
You can find those here:
https://www.rcscomponents.kiev.ua/datasheets/hc_hc-05-user-instructions-bluetooth.pdf.
For pairing use MAC address of one module and hardcode it in second module using AT commands.
Now from theory point of view for pairing between any two bluetooth modules,there are some handshaking signals which are processed and if they are correctly processed then the device gets paired.
Its very hard to debug. But for that purpose use software serial


text:
rs485 and serial ISP
I made a couple of arduino mini pro and esp8266 pcbs with an rs485 transceiver just to find out that I forgot to think about in-system-programming:
Assuming that I don't need to disable the transceiver i tied *RE/DE to gnd/vcc. It turned out that id do need disable the transceiver (at least the receiving part) in order to be able to program the mcu because otherwise the transceiver disrupts the serial data.
But I don't want to lose one pin for this (which in case of an esp8266 are rare) and I don't want to use jumpers because I really like the workflow without.
Is this even possible?
EDIT: The transceiver is an SP3485.
Currently it is connected like:
Mini Pro     SP3485
A-rx ------  RO
GND  --1k-- *RE   A  ---- somwhere else
Vcc  --1k--  DE   B  ----        "
A-tx ------  DI

Which blocks serial programming because of a) the "echo" and b) holding A-rx line high.
If I connect *RE --1k-- Vcc and DE --1k-- GND I can ISP the Arduino, but now I obviously can't use the transceiver anymore.

I'm not sure why you used an RS-485 transceiver if you were only going to permanently enable the two halves? You've basically turned the RS-485 multi-drop into an RS-422 balanced pair-of-pairs. Ah well!
So you wired the transceiver to TX and RX on the ESP8266? And you want to still use those pins to reprogram it, by going "behind" the transceiver and temporarily connect them to your FTDI/whatever? Yeah, sorry: that's not going to work.
The *RE pin and DE pin only affect the balanced side of the transceiver. The RX and TX pins on the logic side are still an output and input respectively, regardless of the state of the two Enable pins.
That means that to reprogram, you're going to have to connect your development machine to the balanced side of the transceiver, and you won't have to worry about the Enable pins. Look for RS-422 USB cable adapters - they're out there!

Hi John, thanks for your answer. Perhaps my question is not worded so well. I've got one transceiver like the sp3485. So on the balanced side I don't have rx/tx anymore. Only A/B. Connecting on that side will definitely not work. If I disable the transceiver the hard way (connect DE/*RE to gnd/vcc via 1k) I'm able to programm the mini. What I'm looking for is some magic (which I can't think of) which does this for me while programming.

I can't understand the purpose of connecting *RE/DE to GND/Vcc. With
this setup, the driver inside the transceiver is always enabled, and
it's always driving the A/B pair. Meaning the device at the other end of
the link cannot drive the pair itself without making a collision.
Basically you have a simplex link, where the Pro Mini is always the
sender.
The normal way to connect an RS-485 transceiver is to have DE driven by
a GPIO pin of the MCU. You pull this pin HIGH when you want to talk, and
leave it LOW the rest of the time so you can hear other devices talking.
The *RE pin is connected either to GND (if you want to hear the echo of
what you say) or to DE (if you don't).
That being said, you are correct in that the transceiver may cause
problems when uploading the firmware on the Pro Mini. One possible
solution is to put a resistor between RO and A-RX. The TX of the FTDI
cable should have a low output impedance and be able to overpower that
resistor. Another option is to use ICSP (in-circuit serial programming)
instead of going through the bootloader. It would be easier if you can
put an ICSP header on your board.

Hi Edgar. Thanks for your answer. Above all for pointing out the working of the transceiver. Now I understand what John was trying to tell me :) I think I misunderstood it because I have been working with can transceivers which have dominant / recessive state and I somehow implied that this is so for rs485, too, and re/de only have the purpose of enable. Interestingly enough I have alredy built some usb/rs485 transceivers which I did wire in this way and they did work ...


text:
Problem with DHT11 and DS18B20 temperature sensors
I am trying to connect to my Arduino Uno board two temperature sensors: DHT11 and DS18B20. The problem is with the DHT11 sensor: apparently there's an error with reading the temperature every two measurements.
Here's what I get on the serial monitor (temperature 1 is from the DHT sensor):

As I am new to this, I was wondering what the problem may be. I have read about the one wire interface used by the DS18B20, but I noticed that the DHT is not using the same protocol.
If I use the DHT11 alone, it works perfectly fine.
Also, I am using 4k7 pull-up resistors for both sensors.
Here's the code:
#include <DallasTemperature.h>
#include <OneWire.h>
#include <dht.h>

dht DHT;

#define ONE_WIRE_BUS 8
#define DHT11_PIN 7

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(void) {
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");
  sensors.begin();
}

void loop(void) {
  int chk = DHT.read11(DHT11_PIN);
  sensors.requestTemperatures();
  Serial.print("Temperature1: ");
  Serial.print(DHT.temperature);
  Serial.print(" Temperature 2 : ");
  Serial.println(sensors.getTempCByIndex(0));
}

Are the OneWire and dht libraries compatible?  They may be using the same resources (for example, the same processor timer).  An easy way to tell is if they work independently.  And you have already proved that the DHT will work if you are not using the DS chip.  Now, if you can explain exactly what you did ... we would have a better idea if there really is a conflict between the two libraries.   Or, you could review the code from both libraries and see if there is a conflict.

I am not really able to understand the code behind those libraries, but as far as I looked I can't really find any conflicts. Here's the link for the OneWire library:
https://github.com/ntruchsess/arduino-OneWire and the link for the DHT library https://github.com/adafruit/DHT-sensor-library

Linked DHT library looks differently then one you use. There is no method read11 for instance. Are you sure you use that one?

My bad, you can download the one I'm using  from here: https://arduino-info.wikispaces.com/DHT11-Humidity-TempSensor

@Darko, you're right, elena is using this project's libraries: https://github.com/RobTillaart/Arduino/blob/master/libraries/DHTlib/dht.h

The latest version has a delay change:  " 0.1.21 replace delay with delayMicroseconds() + small fix ".  You might want to check if you are using this newest version of DHTlib.

If using the latest DHT library doesn't work, you might try printing out your "chk" variable.  There are about 5 defines one for each detected error.  Also you might try to sample the DHT sensor twice in a row then the other.  If the 2nd DHT sample always worked it would point to a comparability problem.

@st2000 I tried sampling the dht sensor twice and I still get the error. http://imgur.com/TaUEjbi . Where did you find the latest version of the library?I couldn't find the one with the update you mentioned

Also, I printed the chk variabile and its value is 0, which means everything is ok..

That is really odd, every 3 samples of the DHT sensor is good.  Did you notice that?

@st2000: the dht11 sensors are pretty slow, i've read they can only deliver data every other second, or so.

@jogco, Wow, now that I know what I'm looking for, there is evidence for this all over.  And in the Adafruit version of the DHT11 Arduino library there is this: "...Check if sensor was read less than two seconds ago and return early to use last reading."

There appears to be several DHT sensor Arduino libraries available:

niesteszeck/idDHT11
adafruit/TinyDHT
adafruit/DHT-sensor-library

You might try an alternate library to see if that solves your current problem.  Note, some if not all of these libraries need to know which DHT model you are using.
Before going through the DHT and OneWire source code line by line looking for conflicts, try to narrow down what is causing the problem:

Try only instantiating the OneWire class and skip calling the read method within the class.

If this works, then the conflict likely resides in the OneWire read method and not in the OneWire initialization code (that is, the OneWire's Constructor).

Calling the DHT read method multiple times consecutively to see if the problem resolves it self.

Actually, you have done this and exposed a curious patter of good-bad-bad-good-bad-bad... which is worth looking into.  The point here is that if only the 1st call to the DHT read method after a call the the OneWire read method was bad, then there might be a setup problem in the DHT read method.

Call the DHT Destructor, the DHT Constuctor then make the call to the DHT read method every time you read the DHT sensor.

This is a test case only and an extreme measure.  What you are doing here is re-initializing the DHT library (driver) every time you use it.  If this works it points to an initialization problem where the DHT library is initialization something which should probably be re-initialized again inside the DHT read method.  As the OneWire library is using the same "something" (resource).
One last thing, the OneWire example I looked at here:
PaulStoffregen/OneWire
...did not use the DallasTemperature library.  I doubt this will make a difference, but it is usually best to keep your code simple and avoid unnecessary complexities.
Added later...
As pointed out in the comments, it turns out the DHT11 only takes new readings every few seconds.  Guessing, the DHT11 library you are using either knowingly returns an unreasonable value of -999.0 until this time passes.  Or is returning exactly what the DHT11 reports which, again, is an unreasonable value of -999.0.
In this DHT11 library, there is code:
boolean DHT::read(bool force) {
  // Check if sensor was read less than two seconds ago and return early
  // to use last reading.
  uint32_t currenttime = millis();
  if (!force && ((currenttime - _lastreadtime) < 2000)) {
    return _lastresult; // return last correct measurement
}

...which returns the last good value for 2 seconds after a DHT11 "real reading" should the library user call upon it faster then the DHT11 can respond.

DHT11 can only be read every 1 second. See manual.

Would you mind linking to the manual you're mentioning and provide exact reference within it for the "1 second" you mention?

According to Adafruit "No more than 1 Hz sampling rate (once every second)" (https://www.adafruit.com/product/386). Search for "DHT11 Datasheet"

To confirm the answers above, in my case https://github.com/adafruit/TinyDHT library worked fine with Arduino Uno, while http://playground.arduino.cc/Main/DHTLib refused to work. Same setup with DHT11 and DS1820.


text:
Using two digits to display a number using TM1637 and a 4-digit display
I decided to build a digital clock using a 4-Digit Display (TM1637) from Grove.
For that, I have been using the DigitalTube library by Grove for the TM1637 controller.
My idea is to use the two first digits of the display (left to right) to display the hour and the two last digits to display the minutes. However, managing displays is difficult and all the libraries I have found for the previously mentioned controlled can only display one number per digit.
Here you have an example:
Using tm1637.display(1,2);, lets you display a "2" in the second digit (L to R), using tm1637.display(0,3); lets you display a 3 on the firt digit and etc.
As I said, I want to display the hour on the first two digits and the minutes in the two last digits.
I've have readed all the examples coming with the DigitalTube library but nothing was useful.
Note: I'm using the DS3231 for managing the time with a RTC.
I don't know if you undestand my question. If not, let me know please.
Arduino UNO R3.

Using tm1637.display(digit#, value); calls, you can display a two-digit number using division to isolate the tens digit and mod to isolate the units digit.  For example, if hour and mins have hour and minute values, respectively, consider code like:
tm1637.display(0, hour/10);
tm1637.display(1, hour%10);
tm1637.display(2, mins/10);
tm1637.display(3, mins%10);

Code like the above is suitable in cases where values don't exceed 99, and where displaying a leading zero is ok.
If you don't want to display the leading zero when hour is less than 10, add an if test and blank the first digit in that case.


text:
Bluetooth module as MCU?
Can I use Bluetooth Low energy devices as micro controllers directly instead of communicating to Arduino e.g. HM-10/11 or even HC-05/06 ? If so what are limitations e.g. can  I hook sensors or control other stuff like LEDs or transistors with PWM ?

I have built a motion sensor, which consists of Arduino, Bluetooth Low energy HM-11, battery and sensor itself. It worked just fine, but one guy told me that Arduino may be completely unnecessary and that Bluetooth module could replace its functionality !
I then started digging for information, and either it's impossible or I am terrible at googling. Everything I found was info about some kind of development kits for HM-10/11, also pin outs of those boards. They do have some IO pins, which can mean it's possible, but I found no tutorials nor examples on how to program those boards and use with other components.

What do the datasheets say?

Funny how one letter 's' can change everything, the keyword here is datasheet(S). it turns out that there are multiple datasheets, and one i checked had no detailed information and so i gave up easily. However after your reply I checked datasheet once again , coincidently it was another datasheet, and this time it was MUCH more detailed, I even found keywords in it which i pasted in Google, and found some neat material. Going to read further and see if those modules can work the way I want.

im searchin for a long time how can i program it in the aim of building alarme watch or thermometer without arduino becaus there is same input can be used as analog input and PWM please if you have some idea about this help me

All bluetooth modules will need some sort of mcu to handle the requirements of the protocol stack, and it seems common that there will be at least a couple of GPIO which can be used directly if your sensor requirements are simple. At the other end of the spectrum, you will find there are also mcus with a full set of peripherals - enough to support a couple of sensors and a small display for example. Remember, the wearables market is likely bigger than the hobby electronics market.
Limitations are most likely to be in the area of ease of use (as you hint at with your question), and possibly the toolchain which you would need to use (unlikely to be arduino compatible). Also, the bluetooth stack typically takes a reasonable proportion of these wearables focused devices, so there is not a big amount of ram/flash or CPU cycles to spare even if you opt for a part which is more than 'just' a serial-to-bluetooth bridge.

Actually, while most bluetooth modules have an internal MCU, there are some that do not.  Also, while there are now some with an internal MCU on the market where tools are provided that allow just about anyone to reprogram them, for others the intent is that only the manufacturer or their industrial partners are able to do that, with the device being fixed-function when used by anyone else.

authors: Светодиодные решения


text:
How to read and write EEPROM in ESP8266
I need to know how I can write integer values in EEPROM and retain the value on power on.
char *Red = strstr(myTestUrl, "/R");
if (Red) {
  int RedValue  = atoi(Red + 2);
  analogWrite(12, RedValue);
  Serial.println("Red :");
  Serial.println(RedValue);
}

I want to write RedValue in EEPROM. How can it be done?

Have a look in the EEPROM sample sketches that are installed when you add ESP8266 support to the arduino ide

having a question if there are any flash dependencies using the EEPROM. Can I flash with 1 MB (no SPIFFS) and have access to EEPROM? Thanks T

While EEPROM.read and EEPROM.write are valid methods, it's like mopping the floor with a toothbrush. Use EEPROM.put and EEPROM.get instead.
For example:
#include <EEPROM.h>

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

  uint addr = 0;

  // fake data
  struct {
    uint val = 0;
    char str[20] = "";
  } data;

  // commit 512 bytes of ESP8266 flash (for "EEPROM" emulation)
  // this step actually loads the content (512 bytes) of flash into
  // a 512-byte-array cache in RAM
  EEPROM.begin(512);

  // read bytes (i.e. sizeof(data) from "EEPROM"),
  // in reality, reads from byte-array cache
  // cast bytes into structure called data
  EEPROM.get(addr,data);
  Serial.println("Old values are: "+String(data.val)+","+String(data.str));

  // fiddle with the data "read" from EEPROM
  data.val += 5;
  if ( strcmp(data.str,"hello") == 0 )
      strncpy(data.str, "jerry",20);
  else
      strncpy(data.str, "hello",20);

  // replace values in byte-array cache with modified data
  // no changes made to flash, all in local byte-array cache
  EEPROM.put(addr,data);

  // actually write the content of byte-array cache to
  // hardware flash.  flash write occurs if and only if one or more byte
  // in byte-array cache has been changed, but if so, ALL 512 bytes are
  // written to flash
  EEPROM.commit();

  // clear 'data' structure
  data.val = 0;
  strncpy(data.str,"",20);

  // reload data for EEPROM, see the change
  //   OOPS, not actually reading flash, but reading byte-array cache (in RAM),
  //   power cycle ESP8266 to really see the flash/"EEPROM" updated
  EEPROM.get(addr,data);
  Serial.println("New values are: "+String(data.val)+","+String(data.str));
}

void loop()
{
  delay(1000);
}

UPDATE:  If you want to understand how the "EEPROM" is emulated in the ESP8266, you might want to reference https://github.com/esp8266/Arduino/tree/master/libraries/EEPROM, specifically, EEPROM.h.
Also, EEPROM.end is not needed, it simply clears the local byte-array cache of the flash/EEPROM from RAM.  It serves on other function.

you have saved my day, I was searching for more than five hours for a solution and you have gave it !

The actual Arduino documentation is really lacking here and the sources do not really help either. Is EEPROM.end() still needed? Why is begin(512) needed?
Plus a get()/put() combination or using update() would help to prevent EEPROM wear. Maybe you could update the answer.

I did a copy/paste of this exact code for a NodeMCU v3 and it's not retrieving the written value after a power cycle (I commented out the "write portion for the second run").

@WhiskerBiscuit,  are you seeing ANY output in serial console?  are you sure baud rate is set correctly?   i don't have v3, just v0.9, so can't help if this is a forwards compatibility problem.

from reference "EEPROM.write does not write to flash immediately, instead you must call EEPROM.commit() whenever you wish to save changes to flash. EEPROM.end() will also commit, and will release the RAM copy of EEPROM contents."

What I have learnt practically is that EEPROM.commit() is absolutely necessary, at least on esp8266, in order for the EEPROM data to survive a reboot.

EEPROM.write(pos, val) writes one byte (val) at the address giving by pos. An "int" in ESP8266 takes 4 bytes, so it's a little more complicated, because EEPROM works in bytes, not ints.
Here is a code for writing one int val at some position pos in the EEPROM:
void eeWriteInt(int pos, int val) {
    byte* p = (byte*) &val;
    EEPROM.write(pos, *p);
    EEPROM.write(pos + 1, *(p + 1));
    EEPROM.write(pos + 2, *(p + 2));
    EEPROM.write(pos + 3, *(p + 3));
    EEPROM.commit();
}

and, of course, you need to read it back:
int eeGetInt(int pos) {
  int val;
  byte* p = (byte*) &val;
  *p        = EEPROM.read(pos);
  *(p + 1)  = EEPROM.read(pos + 1);
  *(p + 2)  = EEPROM.read(pos + 2);
  *(p + 3)  = EEPROM.read(pos + 3);
  return val;
}

In Arduino you call EEPROM.begin(), but in ESP8266 you have to call EEPROM.begin(n), where n is the total number of bytes you will need.
And remember that EEPROM have a short life span (by number of writes). You must minimize the number of writes!
EEPROM is permanent; you don't need to do nothing.

I did some searching and it seems EEPROMs can handle many more write cycles than flash storage but then flash storage also has a controller to stop using bad sections and keep working with the remaining working ones.

UPVOTED because of the life cycle alert.  100k cycles, some say.

Method using the number of letters.
#include <ESP8266WiFi.h>

const char* SSID = "R360"; //MAX 32
const char* PASSWORD = "HFDYUK64323246"; //MAX 32

#include <EEPROM.h>

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

  EEPROM_ESP8266_GRABAR(SSID, 0); //Primero de 0 al 32, del 32 al 64, etc
  EEPROM_ESP8266_GRABAR(PASSWORD, 32); //SAVE

  Serial.println();
  Serial.println(EEPROM_ESP8266_LEER(0, 32));//Primero de 0 al 32, del 32 al 64, etc
  Serial.println(EEPROM_ESP8266_LEER(32, 64));

  WiFi.begin(EEPROM_ESP8266_LEER(0,32).c_str(), EEPROM_ESP8266_LEER(32,64).c_str());

}
//
void loop() {}
//
void EEPROM_ESP8266_GRABAR(String buffer, int N) {
  EEPROM.begin(512); delay(10);
  for (int L = 0; L < 32; ++L) {
    EEPROM.write(N + L, buffer[L]);
  }
  EEPROM.commit();
}
//
String EEPROM_ESP8266_LEER(int min, int max) {
  EEPROM.begin(512); delay(10); String buffer;
  for (int L = min; L < max; ++L)
    if (isAlphaNumeric(EEPROM.read(L)))
      buffer += char(EEPROM.read(L));
  return buffer;
}

Use #include <EEPROM.h>
EEPROM.begin(size); //Size can be anywhere between 4 and 4096 bytes.
EEPROM.write(0, RedValue);   // To store in 0th Location
EEPROM.commit();

I use 2 separate functions in my code on ESP8266 - one with EEPROM.put(), one with EEPROM.get().
I had EEPROM.begin(sizeof...); only in EEPROM.put() function and put worked.
But it took me quite a while, until I found out, that it must be used before EEPROM.get() as well.


text:
Understanding flow of current with pull-up and pull-down circuits
I am new to all of this and was trying to figure out what was happening with pull-up/pull-down circuits.  I think I understand what happens when the board handles the pull-up/pull-down but I wanted to try to build the circuits.  I got help from another forum.  Once I made the circuits, I found that I don't understand the path that the voltage is traveling.  I have 2 examples with multimeters attached.
Pull Up
I understand the press of the button connect circuit to ground.  But why does the voltage everywhere go down to zero when it is connected to ground?  Does it have something to do with the multimeter can't read the voltage because the current is taking the path of least resistance - which I have read is a myth?

Pull Down
When compared to the Pull Up, why does the voltage go to 5 before the yellow wire when the button is pushed?  Isn't it connected to the ground again which seems like it should cause the same scenario as the Pull Up where they all read zero.  Or does the resistor before ground have something to do with this.

I know nothing about electronics.  Some information and links where I could find more information would be great.  Thanks.
All the gifs are screen recordings from circuits I built with circuits.io.  I want to get into making somethings but wanted to practice first before I spent any money.

It goes down to 0V because ground is the voltage reference.

It's very hard to read your circuit, because there are wires everywhere. However this is effectively what a switch and a pull-up resistor looks like:

Due to the pull-up, pin 8 on the Arduino (which the switch is connected to) is normally pulled-up to 5V if the switch is open.
When you close the switch pin 8 becomes 0V, thus your meter reads 0V.

On the other hand, with a pull-down resistor, the circuit looks like this:

Now pin 8 is normally zero volts with the switch open, and when closed pin 8 is connected to 5V to pin 8 becomes 5V.

See my tutorial on switches for more details.

What happens with the flow of current and the resistor to make one example read high and the other low.

Imagine a door with a spring on it to close it. The spring is like a pull-up (or pull-down) resistor (depending on whether you are trying to keep the door closed or open).
The spring gently pulls the door shut. However if you barge out of it with a handful of pizzas in your hand your override the spring. In the absence of the spring the door would just flap in the breeze, sometimes opening and sometimes closing.
The point is, a person is strong enough to force the door open, despite the spring. Similarly if you close the switch you override the pull-up (or pull-down) resistor.

Where does the 5V go when the switch is closed.

It flows through the resistor to ground (or 5V depending on which one you are talking about).

When the switch is open in the pull up example - is voltage going through the resistor? From what I'm reading online, in the pull up case voltage isn't traveling through the resistor until the button is pressed.

Voltage doesn't "go through" a resistor, current does.

With the switch open, effectively a tiny amount of current goes through the resistor to pin 8. It is a "high impedance" input which means it puts a very small load on the input. Thus there is a very small voltage drop over the 10k resistor, and almost the full 5V is presented to the input pin for reading.
To work out the exact amount, we can look at the datasheet which says that the maximum leakage current through an I/O pin at 5V is 1 µA. Now using Ohm's Law we can find the voltage drop over the 10k resistor:
V = I * R
V = 0.000001 * 10000
V = 0.01 V

Thus with 5V at the 5V pin of the processor, and a (maximum of) 1 µA consumed at pin 8, it will therefore have 4.99 V at the pin, which therefore reads HIGH.

With the switch closed, then we use Ohm's Law to calculate the flow through the resistor:
I = V / R
I = 5 / 10000
I = 0.0005 A

Thus 0.5 mA flows through the resistor with the switch closed. This is not enough to damage the resistor, or make a significant load on the 5V line.

I think you are getting confused (as I did when I was young) that a big resistance (like 10k) must "resist" a lot of voltage. It is easy to think that after going through 10k resistance there can't be much "voltage" left.
The fact is, though, that the voltage on the other end of a resistor is proportional to not only the resistance (R) but also the current (I). This is Ohms's Law (V = I * R)
So, if the current is very small (as is the case with an input pin) then the voltage drop over a resistor - even a large one - is very small.
So, the idea of a pull-up resistor is, that with no external influences (like a switch) then after passing through 10k resistance, there is still 5V at the other side.
Let me issue you with a challenge. Find a voltage source (eg. a battery). Measure it with your multimeter. Let's say you have a 5V source which is the Arduino 5V pin. Now get a 10k resistor. Put it in series with the 5V source. Now measure it on the other side of the resistor. Depending on the quality of the meter (and thus how much current it takes to measure a voltage) you will get very close to the same voltage reading. In my case I had 5V on one side of the resistor, and 4.99V on the other side. This is exactly what my calculations above predicted.

Thanks for the diagrams.  Maybe this is very basic, but can you explain why the pin takes current from the path without the resistor?  Like for the pull up, once the switch closes the pin is still connected to the 5v pin, but why does it use the ground pin to get a voltage of zero.   And if I put a multimeter on the section between ground and the switch, why would it read zero instead of 5?

What pin? In both diagrams pin 8 is connected to a resistor. In one it pulls the pin high (a pull-up) and in the other it pulls it low (a pull-down).

Sorry, I should have been more descriptive.  Yes, pin 8.  When the switch is closed in both examples pin 8 is connected to both ground and 5V.  What happens with the flow of current and the resistor to make one example read high and the other low.  Like in the pull up, all three pins are connected so what property or law of electricity makes it switch from 5V to 0V when it is still connected to the 5V.  Where does the 5V go when the switch is closed.  Path of least resistance comes to mind but I have read that that statement is a myth.  Thanks.

See my amended answer.

Thanks for working me through this.  When the switch is open in the pull up example - is voltage going through the resistor?  From what I'm reading online, in the pull up case voltage isn't traveling through the resistor until the button is pressed.  If this is the case, why does the input pin read 5V when the button is up if the voltage has to travel through the resistor from the 5V pin.

First, think of voltage and current this way:  Voltage is water pressure, current is the water flowing through the pipes.  Next, digital inputs normally have high resistance to ground and/or power lines.  So, without the button pressed, a trickle of current is still flowing through the pull up or pull down resistor.  But that trickle of current is enough to change the voltage at the pin.

When the switch is open in the pull up example - is voltage going through the resistor? - yes, that is why it is called a pull-up.

See my amended reply.


text:
PWM output voltage too high
I'm experimenting with PWM with the code below, but (according to my analog multimeter) the voltage on the output pins reach up to 5V whilst the largest analogRead(IN1) value is only around 700:
const int EN1 = 5;
const int EN2 = 6;
const int EN3 = 7;

const int IN1 = 9;
const int IN2 = 10;
const int IN3 = 11;

// SPWM (Sine Wave)
// const int pwmSin[] = {127, 138, 149, 160, 170, 181, 191, 200, 209, 217, 224, 231, 237, 242, 246, 250, 252, 254, 254, 254, 252, 250, 246, 242, 237, 231, 224, 217, 209, 200, 191, 181, 170, 160, 149, 138, 127, 116, 105, 94, 84, 73, 64, 54, 45, 37, 30, 23, 17, 12, 8, 4, 2, 0, 0, 0, 2, 4, 8, 12, 17, 23, 30, 37, 45, 54, 64, 73, 84, 94, 105, 116 };

/// SVPWM (Space Vector Wave)
//const int pwmSin[] = {128, 147, 166, 185, 203, 221, 238, 243, 248, 251, 253, 255, 255, 255, 253, 251, 248, 243, 238, 243, 248, 251, 253, 255, 255, 255, 253, 251, 248, 243, 238, 221, 203, 185, 166, 147, 128, 109, 90, 71, 53, 35, 18, 13, 8, 5, 3, 1, 1, 1, 3, 5, 8, 13, 18, 13, 8, 5, 3, 1, 1, 1, 3, 5, 8, 13, 18, 35, 53, 71, 90, 109};
const int pwmSin[] = {128, 132, 136, 140, 143, 147, 151, 155, 159, 162, 166, 170, 174, 178, 181, 185, 189, 192, 196, 200, 203, 207, 211, 214, 218, 221, 225, 228, 232, 235, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 248, 249, 250, 250, 251, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 253, 253, 253, 252, 252, 251, 250, 250, 249, 248, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 248, 249, 250, 250, 251, 252, 252, 253, 253, 253, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 254, 254, 253, 253, 253, 252, 252, 251, 250, 250, 249, 248, 248, 247, 246, 245, 244, 243, 242, 241, 240, 239, 238, 235, 232, 228, 225, 221, 218, 214, 211, 207, 203, 200, 196, 192, 189, 185, 181, 178, 174, 170, 166, 162, 159, 155, 151, 147, 143, 140, 136, 132, 128, 124, 120, 116, 113, 109, 105, 101, 97, 94, 90, 86, 82, 78, 75, 71, 67, 64, 60, 56, 53, 49, 45, 42, 38, 35, 31, 28, 24, 21, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 8, 7, 6, 6, 5, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 21, 24, 28, 31, 35, 38, 42, 45, 49, 53, 56, 60, 64, 67, 71, 75, 78, 82, 86, 90, 94, 97, 101, 105, 109, 113, 116, 120, 124};

int currentStepA;
int currentStepB;
int currentStepC;
int sineArraySize;
int increment = 0;
boolean direct = 1; // direction true=forward, false=backward

//////////////////////////////////////////////////////////////////////////////

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

  setPwmFrequency(IN1); // Increase PWM frequency to 32 kHz  (make unaudible)
  setPwmFrequency(IN2);
  setPwmFrequency(IN3);

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);

  pinMode(EN1, OUTPUT);
  pinMode(EN2, OUTPUT);
  pinMode(EN3, OUTPUT);

  digitalWrite(EN1, HIGH);
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, HIGH);

  sineArraySize = sizeof(pwmSin)/sizeof(int); // Find lookup table size
  int phaseShift = sineArraySize / 3;         // Find phase shift and initial A, B C phase values
  currentStepA = 0;
  currentStepB = currentStepA + phaseShift;
  currentStepC = currentStepB + phaseShift;

  sineArraySize--; // Convert from array Size to last PWM array number
}

//////////////////////////////////////////////////////////////////////////////

void loop() {

  analogWrite(IN1, pwmSin[currentStepA]);
  analogWrite(IN2, pwmSin[currentStepB]);
  analogWrite(IN3, pwmSin[currentStepC]);

  if (direct==true) increment = 1;
  else increment = -1;

  currentStepA = currentStepA + increment;
  currentStepB = currentStepB + increment;
  currentStepC = currentStepC + increment;

  //Check for lookup table overflow and return to opposite end if necessary
  if(currentStepA > sineArraySize)  currentStepA = 0;
  if(currentStepA < 0)  currentStepA = sineArraySize;

  if(currentStepB > sineArraySize)  currentStepB = 0;
  if(currentStepB < 0)  currentStepB = sineArraySize;

  if(currentStepC > sineArraySize)  currentStepC = 0;
  if(currentStepC < 0) currentStepC = sineArraySize;

  /// Control speed by this delay
  delay(10);
  Serial.println(analogRead(IN1));
}

void setPwmFrequency(int pin) {
  if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
    if(pin == 5 || pin == 6) {
      TCCR0B = TCCR0B & 0b11111000 | 0x01;
    } else {
      TCCR1B = TCCR1B & 0b11111000 | 0x01;
    }
  }
  else if(pin == 3 || pin == 11) {
    TCCR2B = TCCR2B & 0b11111000 | 0x01;
  }
}

If analogRead(IN1) is just around 700 max, shouldn't the voltage be around 3.5V (700/1023 * 5V)? How come the output voltage is so high?
Any help would be appreciated.

What is your schematic? You have some pins connected to other pins, I gather?

It seems that you misunderstand how pwm works.
Pwm is the modulation of duty cycle, so the pin are outputting square waves 0-5v at the same frequency, but varying the time it's low and the time it's high. Your multimeter probably is only displaying high intervals, instead your analog read probably has filters and calculates the efficient voltage of the sine wave (divide max for sqr(2)).


text:
Two Identical Potentiometers, two different results
quick question.  I have two 10 turn precision potentiometers and I tested both when I bought them a few weeks ago, both worked as expected.  However now that I have epoxied one of them into my project and wired it up, I don't get any resistance.  I get a max reading all the time regardless of where the dial is set.  So then I pull off the wiring and do the same setup with the other potentiometer and I am still getting expected results.
What could be the reasoning for the sudden difference in readings? Could the first one have gone bad, and if so how often does this happen and how can I avoid it in the future?
Everything falls within recommended specs of the pot and neither has been really used at all.

Could the epoxy have entered the pot?

Multi turn pots range in size from about sugar cube dimensions:

...to weighing a pound or more:

It would be easy to imagine epoxy entering a small plastic multi turn pot and "freezing" the parts within.  If this is what happened, try using a faster curing glue or mount the pot on a Printed Circuit Board (PCB) and glue the PCB.

I suppose it is possible, I will have to remove it and try the working one and see if I cant be more careful in the mounting process.  It is fairly solid and I doubt any epoxy got in it  but you never know.

Trimmers have a really low current rating, so if you hadn't protect it enough, maybe you have broken it. Always remember a pull up resistor of 10k or more.


text:
Passing array to library function
I'm trying to pass an array to a library (written in c++) but the error:
undefined reference to `MyLib::arrayTest(int*)'
collect2: error: ld returned 1 exit status
Error compiling.

Is being produced.
My Code Is As Follows:
Testing.ino:
MyLib test = MyLib(5,4,6);

void setup(){
    int arr[10];

    test.arrayTest(arr);

    Serial.println(arr[0]);
}

MyLib.h:
class MyLib {
    public:
        MyLib(int x, int y, int z);

        void arrayTest(int* n);

MyLib.cpp:
void arrayTest(int* n){
    n[0] = 15;
}

Any help is greatly appreciated :)

class MyLib is incomplete.

I have that correct in the code I just made a mistake when posting the question, sorry about that

This function:
void arrayTest(int* n){
    n[0] = 15;
}

is lacking the class qualifier:
void MyLib::arrayTest(int* n){
    n[0] = 15;
}

@StackNinja Easily done. I have done it myself numerous times.


text:
Arduino UNO suddenly stops responding
I wrote this simple script to control a servo over serial comm -
#include <Servo.h>
Servo steeringServo;
char data = ' ';

void setup() {
  steeringServo.attach(9);
  Serial.begin(115200);

}

void loop() {
  if(Serial.available()){
    data = Serial.read();
  }

  if(data =='L'){
    steeringServo.write(50);
  }
  else if(data == 'R'){
    steeringServo.write(135);
  }
  else if(data == 'S'){
    steeringServo.write(90);
  }

}

It was working fine, I was sending values through a python script. I turned my Arduino off and after a while I come back and reconnect all stuff exactly the way it was, but now my Arduino isn't responding! I tried sending values through the serial monitor to the above sketch but nothing happens! I tried another code which takes values over serial comm and that didn't work as well. The Arduino just receives the values but doesn't do what its supposed to when it receives.
Not only this, I tried uploading the sweep sketch and that didn't work either. Everything is connected exactly the way it was when stuff was fine.
What has gone wrong with my Arduino?
UPDATE
The Arduino works fine if the values are sent through my script.
UPDATE 2
The Arduino works fine if the values are sent through puTTY.

What script? Possibly when you turned it off and on again it went to a different serial port. Check which serial port shows up in the IDE.

Does the script give you some errors? Something like "cannot open COM port" or "COM port busy". Also, try to run your python scripts in administrator mode.

@FrAxl93 no the script doesn't give any errors. Tried running in admin mode, ran flawlessly

@NickGammon Nah, I thought that initially too the Serial Port is the same.

You never reset data. Every time you enter loop, data keep the last value you read.
You don't need to test data in every loop, only after you read something:
void loop()
{
    if(Serial.available()) {
        data = Serial.read();

        if(data =='L') {
            steeringServo.write(50);
        } else if(data == 'R') {
            steeringServo.write(135);
        } else if(data == 'S') {
            steeringServo.write(90);
        }
    }

I'm afraid that there are additional problems with the servo library: some implementations (looking at Servo-master) disable interrupts, which mess with your Serial port.


text:
Using an External ADC with Arduino
For my project I have to measure a  signal of the order of few microvolts.
As we know the least an Arduino can measure is ~5mV, due to its 10bit ADC and 5V reference voltage.
A solution to this problem can be to use an external ADC (16bit, I think will do).
Can you please guide me on this problem.Is it possible to use a external ADC,if yes how should I.Any other simple solution ?
Thank You
Anupam

You could get around 1mV resolution by using the internal 1.1V voltage reference inside the Arduino. However the maximum voltage you can measure will also be lowered to 1.1V

You can get resolutions as fine as 7.8125µV / LSB using a MCP3428 (4 true differential channels). I sell them on a shield on eBay: http://www.ebay.co.uk/itm/High-Precision-Analog-Data-Acquisition-Board-for-Arduino-chipKIT-etc-/182123969426

What is the range of input voltages you need to measure? If it is for example 0 to 10 mV, and the built in ADC's 10 bit resolution is sufficient, you could put an amplifier with a gain of 500 in front of the ADC and get 10 uV per count. Noise may be a problem however

Range is 0- 30mV (atleast)

Yes, if you have a 0 to 30 mV signal that you need to measure to an accuracy of 2 microvolts, you'll need an ADC with an effective number of bits (ENOB) of at least 13.9 bits and an amplifier to make the signal to match the range accepted by the ADC.
Most ADCs pretty much require some sort of op-amp or differential amplifier between such low-level input signals and the ADC input pins.
A few ADCs have a differential amplifier already built in -- that makes things a lot easier to get working, but I don't know if any of such ADC available would meet the other requirements of your project.
I don't know any way to make such high-resolution measurements other than using a dedicated external ADC chip.
You'll want to read the ADC datasheet -- some of them, and so far all the microcontrollers I've seen that claim to have a built-in "16 bit ADC", have an effective number of bits (ENOB) worse than the 13.9 ENOB you need at the sampling rates I typically use.
Adafruit has a very nice tutorial describing how to connect the 12-bit ADC ADS1015 or the 16-bit ADC ADS1115 to an Arduino.
The Arduino playground has a brief tutorial describing connecting a 12-bit ADC MCP3208 or a 13-bit ADC MCP3304 to an Arduino.
I see from the Arduino blog and other sites that people have connected some even higher resolution ADCs to an to an Arduino board, including
the 24-bit Linear LTC2440 ADC;
the 18-bit LTC2400 ADC (24 bit at 5 samples per second); and
the 24-bit ADC TI ADS1220.

Arduino blog. "Archive for the ‘ADC’ Category"
Peter Oakes. "Arduino UNO, Using precision ADCs and DACs". (video tutorial: connecting the 24-bit ADC TI ADS1220 to an Arduino).
Martin Nawrath. "Connect a LTC2400 High Precision 24 Bit Analog to Digital Converter ... to the Arduino"
John Boxall. "Tutorial – Arduino and the TI ADS1110 16-bit ADC".

Sounds like a fun project.
Good luck.
EDIT:

Steve Luce. The LTC2440 24 BIT ADC and the Arduino Uno.

Everyone that uses an ADC needs some antialiasing filter between the signal and the ADC.
People that measure very faint signals usually need some sort of amplifier between the signal and the ADC.
You may find the list of suggested op amps on p. 7 of the AMP03 datasheet useful.
Because historically ADCs were expensive (and high-resolution ADCs were unavailable), people have developed many clever tricks for processing signals before feeding the processed signal into a relatively low-resolution ADC.
(Lock-in amplifiers, chopper amplifiers, manual precision gain adjustment, manual precision offset adjustment, heterodyning, etc.)
Have you tried asking "What sort of amplifier do I need to measure ((something)) with a 16-bit ADC" at https://electronics.stackexchange.com/ to learn some of those tricks that specifically apply to ((something))?

Thank You so much David for your answer.Yeah MCP3304 looks like a better ADC as my signal has a frequency of 10Hz.The processing has to be done before 100ms.ADS1115 samples at a very low rate.Is it possible to measure 10microvolt using mcp3304 ?

The ADS1115 can be programmed to several different sampling rates, from 860 samples/s to 8 samples/s. Often that is adequate for a nominal 10 Hz analog data signal. What are you really trying to measure?

Yeah I think you are right David. ADS 1115 is good enough.My signal is pulsed ,0.5-1microsecond long at a period of 100 milliseconds.I am using a peak detector for this.To acquire the data(from the peak-detector,i.e capacitor) i need an ADC.


text:
How to make "IF "Temperature exceeds" logic to work in same arduino code
I have the below code working from https://www.youtube.com/watch?v=Y30iEOxl1To - to receive temperature & humidity as an sms when i give a missed call to a specific number (sim on the gsm shield)
The above code is like on demand sms. I also want to alter this code so it can automatically send me another sms if the temperature exceeds a threshold.
Please help.
Below is the code...
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "call.h"
#include <DHT.h>
#include "sms.h"

SMSGSM sms;
#define DHTPIN 7
#define DHTTYPE DHT22

CallGSM call;
boolean started=false;
char sms_text[160];

DHT dht(DHTPIN, DHTTYPE);

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");
}

void loop()
{
    float humidity, temperature;
    String smsText ="";
    if(temperature>29)
    {
        switch (call.CallStatus())
        {
            case CALL_NONE: // Nothing is happening
                break;

            case CALL_INCOM_VOICE : // Yes! Someone is calling us
                Serial.println("RECEIVING CALL");
                call.HangUp();
                delay(1000);
                humidity = dht.readHumidity();
                temperature = dht.readTemperature();
                delay(1000);
                smsText = "Temperature: "+String(temperature,1)+"C Humidity: "+String(humidity,1)+"%";
                smsText.toCharArray(sms_text,160);
                //Serial.println(smsText);
                sms.SendSMS("+91**********",sms_text);
                break;

            case CALL_COMM_LINE_BUSY:  // In this case the call would be established
                Serial.println("TALKING. Line busy.");
                break;
        }
        delay(1000);
    }
}

The code below will check if the temperature goes above 29 degrees. It also check whether the temperature was below 29 previously, to prevent it from sending an SMS every second, for as long as it's above 29 degrees C.
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "call.h"
#include <DHT.h>
#include "sms.h"

SMSGSM sms;
#define DHTPIN 7
#define DHTTYPE DHT22

CallGSM call;
boolean started=false;
char sms_text[160];

DHT dht(DHTPIN, DHTTYPE);

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");
}

float previousTemperature = 0;
void loop()
{
    float humidity, temperature;
    humidity = dht.readHumidity();
    temperature = dht.readTemperature();
    delay(1000);

    // check if temperature has raised to above 29 degrees
    if(temperature>29 && previousTemperature<=29)
    {
        sendSMS(temperature, humidity);
    }
    previousTemperature = temperature;

    // check for incomming call
    switch (call.CallStatus())
    {
        case CALL_NONE: // Nothing is happening
            break;

        case CALL_INCOM_VOICE : // Yes! Someone is calling us
            Serial.println("RECEIVING CALL");
            call.HangUp();
            delay(1000);
            sendSMS(temperature, humidity);
            break;

        case CALL_COMM_LINE_BUSY:  // In this case the call would be established
            Serial.println("TALKING. Line busy.");
            break;
    }

    delay(1000);
}

void sendSMS(float temperature, float humidity)
{
    String smsText ="";
    smsText = "Temperature: "+String(temperature,1)+"C Humidity: "+String(humidity,1)+"%";
    smsText.toCharArray(sms_text,160);
    //Serial.println(smsText);
    sms.SendSMS("+91**********",sms_text);
}

You are awesome :-)

Thank you. Just make sure to mark this answer as accepted, in return.

I get this error now when compiling the same code in ARDUINO IDE
/Users/administrator/Documents/GSM_Call_Receive/GSM_Call_Receive.ino: In function 'void loop()':
GSM_Call_Receive:42: error: 'sendSMS' was not declared in this scope
sendSMS(temperature, humidity);
^
GSM_Call_Receive:56: error: 'sendSMS' was not declared in this scope
sendSMS(temperature, humidity);
^
exit status 1
'sendSMS' was not declared in this scope

That’s not how it works!

well i had the void sms part before the loop function and it started working

how do we keep the existing code and also include a logic which sends the temperature to a phone number that is not configured in the code.

You should create a new question.

My bad, i am not good at posting. Let me create a new question

Kindly help here
https://arduino.stackexchange.com/questions/51768/how-to-get-temperature-sms-to-any-calling-number

posted a new question

Please stop bugging me!

Sorry. Will not disturb you on this again.


text:
Interfacing pc mouse (serial port DB-9)
So I`ve got that mouse with serial connector. It is named serial so it should be easier to connect than even a ps2 mouse, right?
I can`t find any instruction on it. Or should I see instruction on ps2 mouse and plug in the same wires?
Btw mouse has only 4 wires connected inside, as usual PS2 mouse. I want to connect it the same way as ps2 mouse to get easy readings of rotary encoder.

UPD1: I`ve tried to connect it like a PS2 mouse according to this schema with no success. So either a mouse is dead or it uses some kind of different connection?

It might be easier, but you have to figure out how. For PS2 you can use copy-paste existing code, and get it to work in minutes.

A serial mouse is designed to connect to a PC's true serial port - it's an actual RS-232 device using ±5V. As such it won't connect directly to the Arduino's RX/TX pins, you'll have to go through an RS-232 transceiver chip.
It also gets its power from the RTS line, but I never knew what the current draw of one of those things was - be careful trying to power it from the Arduino!
Different mouse manufacturers used different protocols. The original standard used a three-byte protocol at 1,200 bps 7N1. The encoding had the following properties:

The leading bit of the first byte of the packet was set - all future bytes had the leading bit cleared.
The first byte had the buttons' states, and the most significant bits of the X and Y deltas;
The X delta was encoded in the second byte;
The Y delta was encoded in the third byte.

http://paulbourke.net/dataformats/serialmouse/

Other manufacturers added things like extra buttons and scroll wheels that didn't fit in the packet structure. So they modified the protocol, but stuck with some features of the original:

The data rate was (usually) still 1,200 bps, although sometimes they used 7N2 or 8N1 instead.
The leading bit was still used to indicate start of packet;
The X, Y (and Z) wheels still indicated deltas.

http://www.cpcwiki.eu/index.php/Serial_RS232_Mouse

Thanks for the answer! So I should get a grip on a RS-232 transceiver chip and serial mouse protocol. Fair enough.

If you really want to pursue it, but it would be easier all around to use a PS/2 mouse, not only electrically but because most Arduino's don't have a 2nd UART to spare, and implementing the PS/2 mouse synchronous signalling in software is small and more efficient that implementing a serial UART in software.


text:
Strange behaviour with using max
I have this really simple code.
Let's say I have a variable X.
Then all I want to do is create a random value R, if R > X then I want X to become R.
But for some reason, my n_of_buttons_pressed climbs up and then sometimes drops back to lower values. I can not wrap my head around how it could get a lower value then a previous value.
#define N_OF_BUTTONS 60

int n_of_buttons_pressed;

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

void loop() {

  n_of_buttons_pressed = (int) max(random(0, N_OF_BUTTONS), n_of_buttons_pressed);

  Serial.print("n_of_buttons_pressed:");
  Serial.print(n_of_buttons_pressed);
  Serial.println();

  delay(100);

}

The max() “function” is actually a macro defined in Arduino.h as
#define max(a,b) ((a)>(b)?(a):(b))

This expands in your code into something like
buttons_pressed = random(0, N_OF_BUTTONS) > n_of_buttons_pressed) ? \
                  random(0, N_OF_BUTTONS) : n_of_buttons_pressed

The problem with the macro is that it evaluates at least one of its
arguments twice. In this case, if the test is true, the variable
buttons_pressed gets assigned another pseudo-random number.
The way around this is to store the pseudo-random number in a variable,
to avoid random() being evaluated twice:
int pseudo_random = random(0, N_OF_BUTTONS);
buttons_pressed = max(pseudo_random, n_of_buttons_pressed);


text:
How can I include examples in library?
I have written a library for Arduino, my_library, consisting of my_library.h and my_library.cpp, both included in my_library folder. Actually the library is recognized from IDE Arduino and works fine.
I want to add some examples, let's say Example1 and Example2. How is that possible?
Should the examples be included in my_library folder?
or should be included in another folder inside my_library folder?
I tried several combinations but none worked. Do I miss something?

You need to create a folder called "examples" in your library folder. Within there, each in its own folder, you place your examples.
For example:
MyLib/
MyLib/MyLib.h
MyLib/MyLib.cpp
MyLib/examples/
MyLib/examples/Example1/
MyLib/examples/Example1/Example1.ino
MyLib/examples/Example2/
MyLib/examples/Example2/Example2.ino

Be sure to name the example's folder the same as the name of the example.


text:
Cannot read NTAG203 with MFRC522
I tried regular RFID tags and It works but when I tried NTAG203 it won't detect.
P.S. I used the code "dump_data" example of MFRC library.

what are regular RFID tags? MFRC522 reads NFC tags - "RFID" tags include non NFC tags

@JaromandaX Mifare 1k Card is what i referred to. I could easily read that card but not a NTAG203 sticker


text:
XBee WiFi: Does it work on the Wireless Proto Shield?
I have been following this tutorial by sparkfun
https://learn.sparkfun.com/tutorials/internet-datalogging-with-arduino-and-xbee-wifi
and I have XBee Wifi but not the Shield of SparkFun. I have the Wireless ProtoShield which is provided by Arduino.cc
I wonder if both are compatible with each other?
Thank you in advance.


text:
Getting negative results from calculations
I'm trying to proportion potentiometer value to analog pin value. Like 1024 to 255.
int readVolumePot() {
    int val = analogRead(potVolumePIN);

    Serial.print("VOL");
      Serial.println((val * 255/1024));

      return (val * 255/1024);
  }

As potentiometer turns I got irrelevant values.
VOL3
VOL3
VOL3
VOL17
VOL-16
VOL-16
VOL-21
VOL-1
VOL-10
VOL-3
VOL-4
VOL11
VOL8
VOL13
VOL17
VOL15

In Arduino's website they say

some constant calculations may overflow (e.g. 60 * 1000 will yield a
  negative result).

Notwithstanding, I cannot find an appropriate way to convert the potentiometer value to analog pin value.

Try using map().

a more elaborate answer here

analogRead() returns a number from 0 to 1023, and you want to convert that to a range from 0 to 255? One easy way would be to simply divide the reading by 4.
On a more general note, given that the numbers will (should!) never be negative, there's a flavour of int called unsigned int. By using that:
unsigned int val = analogRead(...);

you can cover a range from 0 to 65535 instead of int's -32768 to 32767. That will give you a little more head room - but not enough to multiply the maximum value 1023 by 255 first.
There's also another type long. That covers the range from -2 to 2 billion (and a bit), while unsigned long goes from 0 to 4 billion (and a bit) - but that uses a LOT of processing for the poor Arduino to work with.

A nice feature of unsigned ints: if val is unsigned, then val / 4 is optimized by the compiler into a bit shift, much more efficient than the actual division you would get if val was signed.


text:
HUGE deviation in Sharp IR sensor values if other pins are defined in void setup()
I wrote this code for a project -
int sensorpin = A5;
int val = 0;
double avgval = 0;
int E1 = 11;
int brake = 12;
char data = ' ';

void setup()
{
  Serial.begin(115200);
  pinMode(E1, OUTPUT);
  pinMode(brake, OUTPUT);
  pinMode(sensorpin, INPUT);
}

void loop()
{

  if (Serial.available()>0){
      data = Serial.read();
    }

  val = analogRead(sensorpin);
  avgval = average(val);
  double volt = (avgval*5)/1023;
  Serial.println (avgval);
  Serial.println(volt);
  delay(1000);

  if (data == 'G'){
    analogWrite(E1, 255);
    digitalWrite(brake, LOW);
  }

  if( volt > 1.5 && volt < 1.75 ){
    digitalWrite(brake, HIGH);
  }
}

double average(double adc){
  int n = 1;
  double avg = 0.00, sum = 0.00;
  while(n<=23){
    sum = sum + adc;
    avg = sum/25;
    n++;
  }
  return avg;
}

The code works fine, except for the fact that the Sharp IR sensor (GP2Y0A710K0F) outputs values which are wrong (by a HUGE distance), ONLY if in the void setup() function, the commands -
pinMode(E1, OUTPUT);
pinMode(brake, OUTPUT);

are left uncommented. If I comment the above two statements, the sketch works fine.
What on earth is wrong here? I can't make out anything.

Not sure why commenting out those two lines makes a difference.  I think we need to see a schematic to resolve this.
However...
You do not use "pinMode" to setup an analog input!
Look at the examples on the "analogRead" page.  Notice there is no setup needed for the analog pin.  Just call "analogRead" like you are doing and everything should be fine.

And that was it! Removing the line pinMode(sensorpin, A5) and uncommenting the two lines solved my problem. Getting the expected readings now. Thanks very much! That was something I should have noticed long ago.


text:
Uno timer 2 set up
I am trying to use Timer2 in an Uno in fast PWM mode.  Can someone explain how to set up the TCCR2A & B registers?
Currently I have:
  TCCR2A |= _BV(WGM21) | _BV(WGM20);
  TCCR2B &= ~_BV(WGM22);

  TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
  TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
  TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

I would like to have the inverted value on TCCR2B, but I think it can be inverted using OCR2B ^= 255, correct?  This is to have a varying signal on Pin11 and its inverse on Pin3, the signal is generated by varying the OCR2B value.
Thanks

I realized a mistake, what I need to do is set up pins 11 and 3 (TCCR2 A & B?) to fast pwm mode.  Then I will set OCR2A to a value, and OCR2B to the value's inverse.  Should this work?

I also tried:   TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);  But I'm still not getting output on pin 3.  Thanks.  Sorry for the excessive posts.

If you want to get two complementary PWM signals, you have to set the
same value to both output compare registers. This is necessary to have
the two signals in phase. You also have to configure one PWM in
non-inverting mode and the other in inverting mode. For example:
TCCR2A = _BV(COM2A1)  // non-inverting PWM on OC2A
       | _BV(COM2B0)  // PWM on OC2B:
       | _BV(COM2B1)  //    inverting mode
       | _BV(WGM20)   // fast PWM
       | _BV(WGM21);  // ditto
TCCR2B = _BV(CS10);   // clock at F_CPU / 1
OCR2A  = 84;          // duty cycle ~ 1/3
OCR2B  = 84;          // same signal, complemented

Checked on the scope: when pin 3 goes high pin 11 goes low and
vice-versa.

Thank you.  What I need is both PWM signals in non-inverting mode.  Then I need to invert the duty cycle OCR2B w.r.t. OCR2A.  So as OCR2A increases, OCR2B will decrease the same.  The actual PWM signals are to be in-phase, but complementary duty cycle.  Sorry for the confusion.

Thanks Edgar, I was able to sort through the 328p datasheet and get the registers figured out.  First time I have worked with registers and bit values and bit math so it took me some time to understand this but it works really well now.  Thanks again.


text:
Arduino clone changing its serial port on slight physical displacement, even during an ongoing serial communication
I'm using an Arduino clone for serial communication. However, as soon as I even touch the board, it resets, and the serial communication stops. When I view the serial port using the 'Tools' menu of Arduino IDE, I observe that it has changed. Sometimes, opening the serial monitor crashes Arduino IDE. I was using MATLAB as well, and observed that it crashed too whenever I initiated serial communication. The setup was working well for a week, when suddenly I encountered this problem.
Do you think that there is a problem with Arduino clone? Any help would be appreciated.

Is it a CH340G USB chip?

If the board is resetting when you touch it you might have a bad connection.  It could be worth checking you USB lead is plugged in properly, changing the USB cable and looking at the socket on the board for bad soldering.

Apologies for posting so late. I figured out that it was the problem with the board itself. As Matt suggested, it was bad soldering on the board. I replaced it with Arduino Uno, and it is working fine. Thanks.


text:
Problem in using COZIR W-100 with arduino
I was using the COZIR W-100 carbon dioxide sensor with an Arduino Mega 2560 with the example code from this site.
But the measured value of carbon dioxide by sensor was 90 ppm in fresh air and that is not correct. Please help me find the cause and a solution.

You're right. 90ppm is too low.

Since that is a  20% CO2 sensor, should you multiply by 5?


text:
How to transmit serial data from laptop USB out to Teensy?
I want to send serial data from my laptop to a Teensy LC chip through the laptop's USB port. I am not sure how to do this. From reading I have found two possibilities, which both seem to have problems:

Get a USB to serial adapter cable, connect the USB to the laptop, the serial to a MAX232 chip, the MAX232 chip to the UART serial on the Teensy. The ambiguity in this option lies in the fact that the MAX232 chip requires a minimum 4.5V input, and the specs on the Teensy LC say it has 3.3V and one 5V digital output (would this one output be compatible with a MAX232?). Also, it has only 3.3V input, so it sounds like 5V coming from the MAX232 chip would be too much (I guess I could incorporate a chip like https://www.adafruit.com/product/735 ?). Now if I were to go this route with a Teensy 3.1, which says its input pins are 5V tolerant, its voltage output is also only 3.3V (and there is no mention of any 5V output). I guess the answer here would be to incorporate a chip like https://www.adafruit.com/products/1787 ?
The second possibility I looked into would be a USB-to-TTL adapter cable to go straight to the Teensy LC, but I read somewhere that the serial UART with Arduino is different in some way and I wasn't sure if the serial communication coming through the USB-to-TTL cable would be compatible with the Teensy. I was looking at one of these cables at Sparkfun, and I think I would connect the TxD from the cable to the RX on the Teensy, the RxD from the cable to the TX on the Teensy, and the GND cable to a ground on the Teensy.

Could someone point me in the right direction regarding sending serial data through a laptop's USB out to the Teensy?

Is there any particular reason why you don't want to use the existing USB connection for serial communications?

Yes. I was going to use the usb port to connect to another laptop as its keyboard, and transfer the incoming serial keystrokes to the other laptop through the teensy usb-keyboard interface.

Your second option is the easiest.

a usb to ttl adapter cable to go straight to the Teensy LC, but I read somewhere that the serial UART with Arduino is different in some way

Without seeing what you read, perhaps they were just talking about the fact that the Arduino is not "true" RS-232, it's only at TTL (or 3.3V) levels.

and wasn't sure if the serial communication coming through the usb to ttl cable would be compatible with the Teensy.

It should be compatible, especially since you note that the Teeny is 5V-tolerant.

I was looking at one of these cables at sparkfun, and I think I would connect the TXD from the cable to the RX on the Teensy, the RXD from the cable to the TX on the Teensy, and the GND cable to a ground on the Teensy.

That's it in a nutshell!