text:
In what situation would the Vin pin be attached to any of the I/O pins?
In what situation would the Vin pin be attached to any of the I/O pins?
Also, in what situation would the Vin pin be attached to an external circuit?

Vin is exactly the same as using the barrel jack (DC in) on the Arduino.  You can use it when you want to power your Arduino from an external source and you don't want to have the bulk of a big power plug.  It can also be used as a power output when you are using the barrel jack, for instance for powering relays or motors.  It just saves on having to splice wires into the cable of a wall wart, for example.
The voltage you feed in to the Vin pin should be of the same specification as the barrel jack - that is, between 7 and 12V.  From there, just like the barrel jack, it goes to the 5V regulator to provide the 5V for the board, and then on to the 3.3V regulator for low powered peripherals.
If, at any time, you power the board from the USB and have something connected to the Vin pin that consumes power you risk damaging the 5V regulator on the Arduino since power will flow backwards through it form 5V to Vin, which it really isn't meant to do.  In these situations it is good to connect a diode between 5V and Vin such that the anode is on 5V and the cathode on Vin - so that if the 5V is higher than the Vin voltage then the current will bypass the regulator safely.

Thanks, also when do you think it would be acceptable to attach the positive or negative end of a power supply to an I/O pin?

@abc12333333 You have asked that as a separate question - see my answer there.

@Majenko Vin is exactly the same as using the barrel jack. The barrel jack has a polarity protection diode, while Vin hasn't (at least on the UNO). Other than that, they are indeed the same.

Vin connected to an IO pin: If you want to damage your Arduino.
Hypothetically, I could imagine a misguided attempt to detect if it's being powered from a barrel jack or from USB, but the higher voltage (and it will ALWAYS be a higher voltage if powered from that rail) is likely to damage the chip
To do that safely/correctly, you would need a voltage divider, to reduce both the voltage to a level below the +5v level.
Vin to an external circuit is very reasonable. If you have, for example, a motor that needs +12v, and your Vin is 12v, then you can provide the power for the motor from Vin, and still control it from the Arduino - you would use a transistor to turn the +5v from one of the digital pins (set to output) to 12v from Vin. This is typically what happens on a "motor driver" - for example, see http://www.hobbytronics.co.uk/image/data/tutorial/bipolar-stepper-drive.jpg - on the left-hand side, you will see "motor supply" - this runs at a higher voltage (and is isolated from +5v and Arduino pins), and if your motor needs what the barrel jack supplies (and is no more than 12v), then Vin is perfect.
The other situation is that you can put +7v to +12v INTO the Vin, instead of using the barrel jack - this will power your Arduino.

Thanks, also when do you think it would be acceptable to attach the positive or negative end of a power supply to an I/O pin?

Directly connected, there's no point, though it's not unusual to connect it via a resistor as a part of a voltage divider.


text:
ESP 8266 does not respond at all
I have a ESP8266_01, and I wired up. It does not work for me.
I have connected the ESP to an Arduino Uno. I am using a 5V pin from uP with a 3.3V regulator, and I have a voltage divider between RX(ESP) and TX(uP). And I am sure that the wiring is correct. The thing is, I am not getting anything back from ESP, not even errors. And I tried to use different baudrates as well. There is a blue LED flashing from ESP only when I am using 115200, and red LED lights up constantly at any other baudrate.
What have I done wrong here?
I did 4 hours of research already and don't know what else I can do now.
If you have any idea, please leave me a word.

I did the exact same method and got looping of "Sending an AT command...". Seems to me software serial did not print AT. When I connect using a FTDI cable, it works perfectly. I am sure the ESP8266 is working but I am unsure that my connections are correct. I use an external 2 AAA batteries to power the chip as well as 3.3V from the board. For TX RX, I use logic shifter and voltage divider. All combinations failed to produce results. Please advise.

Start by uploading blink sketch to your Arduino then connect it to your ESP8266 like this: TX-TX and RX-RX.
Now open Serial Monitor and send AT command and see if it responds. If so then you can control it using your Arduino by wiring it back to TX-RX and RX-TX.
PS: Don't forget to set the line ending in the Serial Monitor to Newline or Carriage Return.
Edit: Use this code to connect to ESP8266:
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  ESP8266.println("AT");
  delay(30);
  while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}

Since the Hardware Serial interface will be busy when connected to Computer, then you have to use another Serial interface to communicate with your ESP8266. In this case, Software Serial comes handy.

Not sure about uploading blink sketch?

Trust me, I've ran into that problem of yours. You need to upload blink sketch or any sketch that doesn't use the Serial interface (I've chosen blink since it's already there).

YOU ARE ALMOST SAVING ME! Yes it does reply me a OK, when i send AT! But when I try to wire it back to TX-RX,RX-TX, it gets stone again?

Yeah, what I've told you to do lets you bypass your microcontroller and just use the board to connect to ESP8266. When you wire it back to Rx-Tx then you must make the microcontroller take over. I'll send you a code that you can use to send an AT command and get response.

THX a lot, man!

source: Stack Exchange

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

sort: votes


text:
Uno pin 13 LED mysteriously always ON at 0.14V unless pinMode OUTPUT

I upload a blank sketch: pin 13 LED is on. Why?
I connect pin 13 to GND: it turns off until I remove the connection
I connect multimeter between pin 13 and GND: measures 0.14V and LED turns off until multimeter is removed
I press hard reset: LED blinks a few times, turns off for a second then turns on
I upload a sketch that on setup sets pinMode(13, INPUT): pin 13 LED is on
I upload a sketch that on setup sets pinMode(13, OUTPUT): pin 13 LED is off 0.01V
I upload a Blink example: Everything works fine, LED cycles from 4.84V to 0.01V

Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal?
I swear it wasn't like this a few days ago.

The LED is driven by an op-amp (see the schematic). When the pin is configured as input the op-amp has an undefined input (floating input). Thus it may or may not turn on the LED. If you configure it to an output the op-amp is driven in a known way.

Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal?

It's perfectly normal.

I think they did this to stop the LED "loading" the SCK pin (pin 13), particularly if you have it configured as an input and are trying to measure something, the 1k resistor and LED would throw out the measurement.
You could conceivably have a pull-down resistor from SCK to GND, but that would load the pin as well.

Nice answer - especially with the schematics

Apparently it's normal. Although random. Sometimes the default voltage of the pin is high enough to make the LED light up because of the op-amp. Sometimes it isn't.
Source: https://electronics.stackexchange.com/a/39707

If SCK is set as an input then pin 5 of the op amp goes high (pnp transistor input stage) and the op amp output goes high turning on the LED.

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


text:
Understanding transistor datasheets
I'm trying my best to understand and utilise questions that already exist as well as other websites, however I just wanted to check the circuit I've come up with (which is a very simple switch circuit) will work.
I plan on using a BD139 transistor, although I haven't purchased anything yet, so can change to anything really.
The fans are each 0.09A at 12V. I've calculated that R1 should be 360ohms. The 5V control will be coming from an Arduino. I believe it's within the specs of the transistor. Ic max is 1.5A.
Does the circuit look correct? Are there any changes I should make?

For saturation you should assume hfe to be 10. This gives:
(5V − 0.85V) / ((0.09A ⋅ 3) / 10) = 154 Ω
Consider using a 150-220Ω base resistor instead. And since a fan is an inductive load, don't forget the flyback diode from the collector to the +12V rail. A 1N4000 series diode should be fine for this small a load.

Where did you get that value for hfe?

That is a safe assumption for normal (i.e. non-darlington) transistors. It's used by EEs the world over.

The datasheet specifies 25 (minimal) for Hfe. Using 150Ω would result in about 32mA of current, which is above the recommended 20mA for a digital pin.

@Gerben: Are you sure you didn't confuse the Vbe and Vce on the datasheet? Vbe(sat) according to the chart is about 0.85V at Ic=0.3A.


text:
SIM900 Modem is not responding
I'm working with arduino nano and it has interfaced with SIM900 GSM. I'm sending "AT\r" to GSM modem, but not getting response.
void setup()
{
  Serial.begin(9600);
  Serial.println("Setup is Ready");
}

void loop()
{
   Serial.write("AT\r");
   delay(1000);
   if(Serial.available() > 0)
   {
     Serial.println("Data received");
     Serial.println(Serial.read());
   }

}

Serial monitor:
Setup is Ready
ATATATATATATATATATATATATATATATATATAT
I've set the 9600 baudrate to modem and my rx and tx is connected correctly...
What is the problem?
Thanks

You should not use the same Serial interface to debug and talk to your SIM900. You should use a SoftwareSerial interface to talk to the SIM900 and use the hardware Serial to send response back to your computer.
Try this code:
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of SIM900
const byte txPin = 3; // Wire this to Rx Pin of SIM900

// We'll use a software serial interface to connect to SIM900
SoftwareSerial SIM900(rxPin, txPin);

void setup() {
  Serial.begin(115200);
  SIM900.begin(9600); // Change this to the baudrate used by SIM900
  delay(1000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  SIM900.println("AT");
  delay(30);
  while (SIM900.available()){
     String inData = SIM900.readStringUntil('\n');
     Serial.println("Got reponse from SIM900: " + inData);
  }
}

You aren't talking to the SIM900. You are just communicating with the serial monitor.


text:
Assemble or typecast byte array to float
The serial port on my Arduino Mega is receiving 3 floats as bytes (total of 12 bytes, 4 per float) over serial. Unfortunately I cannot assemble the 4 Bytes in a float, as the serial monitor only displays
0.00
0.00
0.00 etc.
Here is the code:
void serialEvent2() {
  if (Serial2.available() > 11) {
    byte yawData[3];
    yawData[0] = Serial2.read();
    yawData[1] = Serial2.read();
    yawData[2] = Serial2.read();
    yawData[3] = Serial2.read();
    float yawAngle = *((float*)(yawData));
    Serial.println(yawAngle);

    byte pitchData[3];
    pitchData[0] = Serial2.read();
    pitchData[1] = Serial2.read();
    pitchData[2] = Serial2.read();
    pitchData[3] = Serial2.read();
    float pitchAngle = *((float*)(pitchData));

    byte rollData[3];
    rollData[0] = Serial2.read();
    rollData[1] = Serial2.read();
    rollData[2] = Serial2.read();
    rollData[3] = Serial2.read();
    float rollAngle = *((float*)(rollData));
  }
}

I made sure the data coming to Serial2 is not 0.
UPDATE: The initial mistake was my byte array not being sized correctly. I fixed it. The values I print are fine until after about a second, they get totally weird. Dropped bits/Bytes maybe? Seems odd because a sample sketch written in Processing works perfectly while taking the exact same input.

Your byte array is 3 bytes length, while you're assuming it's 4 bytes !

@KiraSan Thanks for the hint! Made an edit because of a new problem... Maybe you know some more magic tricks? ;)

Did you try the code in my answer? maybe you should inverse the bytes order to get the correct values.

@KiraSan Yep, tried it, gives me not a single correct reading :/

I have edited my answer since that time. please check it out.

But it's still about the Byte order, right? Checked that, doesn't work...

Can you show me the code running on the sender of these bytes?

I'm using a pretty good firmware for my the IMU from which the data it coming. The file with the output code can be found on Github.

You might also want to take a look at this Processing sketch, as it demonstrates reading the data successfully.

Let us continue this discussion in chat.

I tried the code below and it worked for me, don't miss the delay() part:
Sender Code:
void setup() {
  Serial.begin(9600);
}

void loop() {
    float yaw = 10.5;
    float pitch = 20.15;
    float roll = 100.10;
    float ypr[3];
    ypr[0] = yaw;
    ypr[1] = pitch;
    ypr[2] = roll;
    Serial.write((byte*) ypr, 12);  // No new-line
    delay(1000);

}

Receiver Code:
void setup() {
  Serial.begin(9600);
}

void loop() {

}

void serialEvent() {
    if (Serial.available() == 12){
      byte yawData[4];
      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawAngle = *((float*)(yawData));
      Serial.println(yawAngle);

      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawPitch = *((float*)(yawData));
      Serial.println(yawPitch);

      yawData[0] = Serial.read();
      yawData[1] = Serial.read();
      yawData[2] = Serial.read();
      yawData[3] = Serial.read();
      float yawRoll = *((float*)(yawData));
      Serial.println(yawRoll);
    }
}

Results:

If you must do it that way I'd recommend using a union:
typedef union {
    float val;
    uint8_t bytes[4];
} floatval;

floatval v;
v.bytes[0] = Serial2.read();
v.bytes[1] = Serial2.read();
v.bytes[2] = Serial2.read();
v.bytes[3] = Serial2.read();
Serial.println(v.val);

A better solution is to just write and read the raw float data:
// Sender:
Serial.write((const char *)&myfloat, sizeof(float));

// Receiver
Serial2.readBytes((char *)&myfloat, sizeof(float));

Even better still is to define a struct which is the packet of data you wish to send:
typedef struct {
    float yaw;
    float pitch;
    float roll;
} attitude;

attitude myatt;
myatt.yaw = 14.9;
myatt.pitch = 23.4;
myatt.roll = 11.49;

Serial.write((const char *)&myatt, sizeof(attitude));

// receive:

attitude myatt;
Serial2.readBytes((char *)&myatt, sizeof(attitude));
Serial.println(myatt.yaw);
Serial.println(myatt.pitch);
Serial.println(myatt.roll);

First of all, thanks! I tried the method with a struct and it works for about a second until the data seems to be corrupted. Maybe a few bits are being dropped from time to time? How can I prevent this?

For that you need to construct a proper packet. I have a good library that can help. Google "Arduino ICSC"

try use memcpy, i think it might work:
void serialEvent2() {
  if (Serial2.available() > 11) {
    byte yawData[4];
    float yawAngle = 0;
    yawData[0] = Serial2.read();
    yawData[1] = Serial2.read();
    yawData[2] = Serial2.read();
    yawData[3] = Serial2.read();
    memcpy(&yawAngle, &yawData,sizeof(float));
    Serial.println(yawAngle);

    // same for others ...
  }
}

What if you write
yawData[3] = Serial2.read();
yawData[2] = Serial2.read();
yawData[1] = Serial2.read();
yawData[0] = Serial2.read();

i.e. you change the endianness of the representation

I already told him about it, but it turned out that it's not the problem, by looking at the sender's code, the bytes are in the same order as expected by the reader code.


text:
How to destroy my Arduino with I/O pins?
What are the most common ways of destroying a Arduino using the I/O pins?
Also, in what situation would it be acceptable to attach the positive or negative end of a power supply to an I/O pin?

putting a small firework under the micro and connecting an electronic match to a pin is a spectacular way to destroy and arduino using the I/O pins

Do the I/O pins have to be from the same Arduino we're trying to destroy? Or can they be from a different device?

There are many ways to destroy an Arduino, check out this article, 10 Ways to Destroy An Arduino.

Shorting I/O Pins to Ground
Shorting I/O Pins to Each Other
Apply Overvoltage to I/O Pins
Apply External Vin Power Backwards
Apply >5V to the 5V Connector Pin
Apply >3.3V to the 3.3V Connector Pin
Short Vin to GND
Apply 5V External Power with Vin Load
Apply >13V to the Reset Pin
Exceed Total Microcontroller Current

What are the most common ways of destroying a Arduno using the I/O pins?

Over-voltage and over-current.
Over-voltage involves putting too high (or too low) a voltage onto an IO pin.  Over-current involves trying to source (or sink) too much current through an IO pin.  Both can be fatal.

Also, in what situation would it be acceptable to attach the positive or negative end of a power supply to an I/O pin?

"Positive": When that power supply is no more than 5V and shares ground with the Arduino and you want to know if it's on or not, or measure the voltage (Analog Input).  Anything more than 5V will require a voltage divider to bring the voltage down to 5V.
"Negative": If by that you mean the ground terminal, and that ground terminal is shared with the Arduino ground, then you can do it any time - but why would you, since you'd just be connecting to the Arduino ground since they are one and the same. If it's not the ground terminal but a potential below ground, then never unless you use some circuitry to raise that potential above ground for measuring it.

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


text:
Giving the impression of a dying device - making a vibrating motor slow down and stop
I'm trying to make a gag gift for a friend. The effect I'm trying to imitate is of a device that starts up for a moment and then putters out like something is wrong.
So I need it to:
1. Vibrate a motor for a second or two.
2. Make the vibration sputter out.
3. Light up an LED behind an error message on a paper screen.
I have very little hands on experience with anything electronic, but I have some programming and I took enough physics to know what a capacitor, etc is.
My questions are whether an Arduino is a good and cost effective way to accomplish this and is there any beginner friendly advice anyone can give me to get this accomplish

You can control the motor using PWM (Pulse Width Modulation) and make it run for full, then slowly decrease the speed till stop and after light up the led.
This tutorial from Adafruit could be a good start if you are not familiar with PWM and have also some good advices: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview
Please be really careful about the supply source. Motors can easy draw more current then the limited available from the pins of arduino. Maybe a H-bridge could be helpfull here.(take a look at this for example of h-bridge: https://learn.adafruit.com/adafruit-raspberry-pi-lesson-9-controlling-a-dc-motor/lm293d )

If it's a smallish motor then the output pins should be able to handle it; I've driven a force feedback motor from a DualShock directly from an AVR before, with two PWM outputs acting as a H bridge.

@Personagem - Thank you for your response, particularly the warning. Based on what you've said, I think I need to figure out how large of a motor I need to vibrate a wooden box before I can determine if it would draw too much current...


text:
How to send volume +/- on Mac/OSX from Leonardo
I saw this answer but I can't find the analog for Mac.
I've tried cycling thru keycodes from 0x01 thru maybe 0x500, and I went thru ascii a few times, also found brightness up/down, and F11, F12, but they get pressed with fn key by default which makes them do operations other than vol +/-.

What makes you think that the upvoted answer in the other question doesn't apply to Macs?

@IgnacioVazquez-Abrams 1) I tried those codes 2) I can't find xev for mac.

Could you just untick the "Use all F1, F2, …" in System Preferences -> Keyboard?

Just wondering if that would be an option and if doing so would create the desired outcome.

I will try this out!

it was already unticked, changing it made no difference :(

Unfortunately, Fn is hardware and it is handled internally by the keyboard to do something hardware-based without sending any code. So the short answer is: you can't simulate Fn key with arduino.
What I think of as a solution is:

Create a program on your Mac that can listen for keyboard scan codes to do vol +/- or any other function.
Send a custom scan code from Arduino to your Mac ( a scan code that isn't part of the standard scan codes ).
When your listening program receives that code, it should do Vol +/- (or anything else )...

in my case there is no listening program, the leonardo equiv. board (irduino) is acting as a keyboard.

Oh sorry I may have misunderstood--- you mean to say create a custom mapping on the mac with keys I can send, have those alter volume, and run it along-side using the leonardo? This might work; I'm hoping to find a way to just send the keycode. I have a 3rd party USB keyboard that sends vol +/- just fine so I know keyboards can do this somehow.

I don't actually own a Mac, so my solutions are somehow limited, however, check out this page: http://lists.apple.com/archives/usb/2011/Aug/msg00020.html

It does say  : " Usage 233 (0xe9)  [volume up], Usage 234 (0xea)         [volume down]"

You might want to try these codes and see if that does something ...

Those third-party keyboards are using some sort of composite HID ( not only HID keyboard but also HID Consumer Device ).

thank you! it did not end up working, 0xe9 sends a "9" and 0xea sends "0"

Yes, as I thought, when your arduino acts like a HID Consumer Device, and you send 0xe9 or 0xea that will trigger vol+/- ..

but as long as it is  just a HID keyboard that won't work.


text:
Is it possible for Arduino to send a message to the internet without using a GSM shield?
I need an Arduino to send a message, to be displayed on the web, after pressing a push button, which is connected to an Arduino [or shield], without using a GSM shield.
I need to send a message just by using HTML/PHP code included in the Arduino IDE. This displayed message should contain two buttons. One button is used to turn a LED ON/OFF and the other to open a streaming video.
Can anyone help me with the Arduino code and explain how I should do that? Is there any third party device, apart from a GSM shield, that can help me to send that message?

Start with either the Ethernet shield or the WiFi shield.

I'm trying to understand what you really want, do you want your arduino to provide some sort of webpage containing two buttons. one to turn on a LED and the other one is used to open a streaming video? Is that what you want? Also, I feel myself confused about the buttons, which ones are the physical buttons and which ones are meant to be on the webpage?

yes, thats what i want exactly. i want arduino to provide a message after  pressing a button and the message must display on web shows 2buttons. one phyiscally connected to arduino and used to turn on/off led and the other button on the webpage to open a stream vedio/audio. Now do you understand what i want. and if yes, can you help me with arduino code?

note: i deal with Ethernet shield. and i need html and php code for control LED and open a stream video. additionally, without using a GSM sheild to let arduino send the message.

Yes I can help you, but have you tried something? What you need is to set up a Web Server on your arduino. You may look at this tutorial: https://www.arduino.cc/en/Tutorial/WebServer

Also, I don't understand why you involve the GSM shield? It has nothing to do with what you want to achieve.

You only need an Ethernet shield + buttons + LEDs ..

previously, i have applied this code from this site. but this need to enter my computer ip address into address bar then the webpage is display. now the situation is different. because  what i want is when i press on a push button, then the web page should display. can you help me with code, please?

and i need also php code that make me open a stream video/audio  live, can you help me, please?

Well, I guess you need some sort of program on your computer listening on Serial port, when you press a button, send a command via Serial port to that program and it will open that webpage. if you are interested I will show you an example ;)

IP with homing pigeons? https://en.wikipedia.org/wiki/IP_over_Avian_Carriers

Use this example to open a webpage using a push button, you need Python installed on your Windows.
Step 01:
Upload this sketch to your arduino:
const int buttonPin = 2; // the number of the pushbutton pin
int buttonState = 0;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
  Serial.println("OpenWebPage");
  }
}

The Circuit:

pushbutton attached to pin 2 from +5V
10K resistor attached to pin 2 from ground

Step 02:
Open a text editor and paste this code to a new file:
import serial
from subprocess import call

ser = serial.Serial(
    port='COM5', # Change this to your COM port number
    baudrate=9600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)

if (ser.isOpen()):
    print "Serial Port is Open..."
    print "Waiting for a command ..."
    while 1:
        cmd = ser.readline()
        if cmd.strip() == "OpenWebPage":
            print "Received command from Arduino..."
            print "Opening webpage..."
            call(["explorer", "http://www.google.com"]) #change it the address you want

Save the file to your desktop, name it : SerialListener.py
Step 03

Now open a Command Prompt window.
Navigate to your desktop folder and execute this command: python SerialListener.py.
You should see Serial Port is Open... Waiting for a command ...
Press the push button, and a webpage should open in your default browser.


text:
ISR not working as it is supposed to
For a battery charging project, i am using an ARDUINO UNO which is driving a buck converter to provide the battery with the charging current. I am using external ADCs to measure the battery's charging voltage and current. The test setup is working fine, but right now i am just measuring the voltage and current at random time instants. However to measure it correctly, battery voltage reading should be done at an instant when the controller's PWM output is LOW (OFF duty cycle), and battery current reading should be done when PWM output is HIGH (ON duty cycle).
I looked into interrupts and learned about them that there are 2 types of interrupts in Arduino namely "external", and "pin change". So i downloaded the "PinChangeInt Library" to test it. I wrote a small test program where a PWM of 62.5kHz is being generated on pin3, and i am calling rising and falling edge triggered interrupts on this pin, i.e to display one value when rising edge occurs, and other value when falling edge occurs.  My code looks like following:
    #include <PinChangeInt.h>
    #define pw 3
    int pwm;

    void setup() {
      // put your setup code here, to run once:
      pinMode(pw, OUTPUT) ;
      pwm_setup();             // Set PWM to a frequency of 62.5kHz

      PCintPort::attachInterrupt(pw,rise,RISING);    // call void rise() when PWM is HIGH
      PCintPort::attachInterrupt(pw,fall,FALLING);   // call void fall() when PWM is LOW

      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      pwm = 127;                                                // 50% duty cycle
      pwm_on(pwm);

    }
    void pwm_setup()
    {

      TCCR2A = 0x23 ;
      TCCR2B = 0x09 ; // mode 7, clock prescale by 1
      OCR2A = 256-1 ;  // 256 clock periods = 16us per cycle
      OCR2B =0 ;
      TCNT2 =0 ;

    }
    void pwm_on(double)
     {
        OCR2B = pwm ;
     }

    void rise()
    {
      Serial.println("RISE");
    }

void fall()
{
  Serial.println("fall");
}

But it is not working the way i think it should. It keeps on displaying "fall" every time, whereas according to me it should display "RISE" and "fall" alternatively, right ? However if i remove the "PCintPort::attachInterrupt(pw,fall,FALLING); " line, it starts to display "RISE" as it is supposed to.
Since its my first time programming with Arduino, and i am just a beginning level programmer, i might be making some stupid mistake here. So can anyone point it out please ?
Your helpful comments and suggestions would be appreciated.
Thankyou!

I'm totally against big interrupt service routines. They are against everything ISR represent. So, in my opinion, you'd better throw away the library and start coding yourself. Register on the proper ISR (you can attach to the interrupt INT1, for instance, or to the portD pin change) and, in this ISR, check the pin value. Then set a flag and, in the loop, call the serial function. NEVER use serial inside an ISR, since serial functions are really slow (and you should stay in ISRs the minimum time you need)

Here are a few items to consider.

From #define pw 3 you are working with PD3, INT1.  As one of the Atmega328 Uno's two external interrupts, INT1 supports RISING and FALLING events separately.  Pin change interrupts (PCIs) on pins other than 2 or 3 of the Uno won't separate them and in the interrupt routine (one interrupt routine in that case, not two) you will need to test which occurs by reading the pin.
Serial communication depends on interrupts and won't work in an interrupt handler.  Instead, set a flag (via a volatile byte variable) to test in your loop().
For testing, put pwm_on(pwm) in setup() instead of loop().
In loop(), compute seconds = milli()/1000 and if seconds != prevsec, set prevsec=seconds, enable your PCI or external interrupt, then enter a loop that waits for a flag and takes a reading.  Or, in the interrupt handler, both set a flag and take a reading into a volatile variable.
If you only need to measure the quantities a few times per second, or a few times per minute, you could just busy-wait for the condition, then trigger a sample-and-hold, then convert analog to digital via analogRead().

Regarding sample-and-hold: Unless you change the ADC sampling rate, analogRead() will take up to 100 microseconds per reading.  If your input waveform is 62.5 KHz, it will toggle about about six times while being measured, which if measured directly is likely to give a random result.  However, if you use a sample-and-hold circuit, you can hold the ADC input constant until your measurement completes.
An alternative to using a sample-and-hold is changing the ADC sampling speed. See post #5 in thread Faster Analog Read? on forum.arduino.cc.  If you get the sample time down to 8 to 12 microseconds you can do ok with a busy-wait method.  Ie, when your code wants a reading, it has a loop that measures the PWM line over and over, and starts an ADC conversion shortly after the PWM gets to the state desired for the measurement.

1 applies (partly) to standard interrupt handling. The OP is using a library that handles the pinchange events checking the pin values. Your sentence, however, is wrong, since the arduino interrupt handling does not allow for multiple functions in the ISR, so if you attach both rising and falling you won't be able to use the former you attached

The PinChangeInt library checking pin values is one thing that makes it slow; I used it a few months ago but found it too slow, so used ISR()'s instead.  ... At the hardware level, PCI doesn't distinguish rising/falling, merely detects changes. ... I didn't imply "multiple functions in the ISR", but instead reading a pin and branching to one section of the ISR or another depending on its value.  Thanks for the comment!


text:
Modbus Communication protocol for Arduino as Slave
I have an Arduino Uno board, with these components:

rs-485 Modbus module shield
Multiprotocol radio shield board for Arduino

In addition I have a level sensor which reads either 1 when it is above water, and 0 when it is below.
I need to be able to give the value of this sensor to a modbus master over rs485.
Cooking Hacks Tutorial
This page has a description of how to use the ModbusMaster485 library, but I can not find any information about the slave library.
I can not find any documentation for this library, and would really appreciate any pointers.

Can you post the links to all the library that you've tried so that none of us would post the same. Thanks.

@Dat Ha I've tried using SimpleModBusSlave.h, but the problem is, I have to use Arduino Nano, while the data system in that library is using enum (so it starts from 0). Meanwhile, the data from master is reaching 3000+, which causing full-memory stack error

It's not very well documented for the slave but maybe that is because it only has two methods...
It looks like the slave library is contained in the same library as the master but with name ModbusSlave485.h
You can see in the .h it only has two public methods. One is connfigure() and the other is update(). see below an extract from the .h which explains what each method does.
#include "ModbusSlave485.h"

mySlave = ModbusSlave485();

void setup()
{
  mySlave.configure(slave, baud, parity, txenpin);
}

void loop()
{
  //check for update from master
  mySlave.update(regs, regs_size)
}

extract from .h
/*
 * configure(slave, baud, parity, txenpin)
 *
 * sets the communication parameters for of the serial line.
 *
 * slave: identification number of the slave in the Modbus network (1 to 127)
 * baud: baudrate in bps (typical values 9600, 19200... 115200)
 * parity: a single character sets the parity mode (character frame format):
 *         'n' no parity (8N1); 'e' even parity (8E1), 'o' for odd parity (8O1).
 * txenpin: arduino pin number that controls transmision/reception
 *        of an external half-duplex device (e.g. a RS485 interface chip).
 *        0 or 1 disables this function (for a two-device network)
 *        >2 for point-to-multipoint topology (e.g. several arduinos)
 */
  void configure(unsigned char slave, long baud);

/*
 * update(regs, regs_size)
 *
 * checks if there is any valid request from the modbus master. If there is,
 * performs the requested action
 *
 * regs: an array with the holding registers. They start at address 1 (master point of view)
 * regs_size: total number of holding registers, i.e. the size of the array regs.
 * returns: 0 if no request from master,
 *  NO_REPLY (-1) if no reply is sent to the master
 *  an exception code (1 to 4) in case of a modbus exceptions
 *  the number of bytes sent as reply ( > 4) if OK.
 */
  int update(int *regs, unsigned int regs_size);

  // constructor
  ModbusSlave485()
  {
    myDevice = RS485();
  }


text:
Python script to toggle LED's
I have 8 LED's connected to a shift register on my arduino uno r3. I am trying to write a Python3 script that will prompt a user to select one of the LED's and then prompt to toggle on or off.
Should be pretty basic but I cant seem to get this working.
I have already botched my code trying to get this running:
the jist of my python script is
import serial
import os
import time

os.system('clear')

ser = serial.Serial('/dev/cu.usbmodem1431', 9600)

while True:
    led = input("Which LED do you wish to operate? (press x to quit): ")

    if led >= '0' and led <= '7':
        print("Operating LED # %s" % led)
        ser.write(str.encode(led)) # sends the choice of led to arduino'
        on_or_off = input("Do you want to turn it on or off (press 0 for off and 1 for on): ")

        if on_or_off == '0':
            #send command to arduino to turn off the selected LED
            print("Command sent to arduino to turn OFF LED %s" % led)
            ser.write(str.encode(on_or_off))
        elif on_or_off == '1':
            #send command to arduino to turn on the selected LED
            print("Command sent to arduino to turn ON LED %s" % led)
            ser.write(str.encode(on_or_off))
        else:
            print("Please enter 0 or 1 to operate the LED. ")

    elif led == 'x':
        ser.close()
        break
    else:
        continue

For some reason Arduino is only dealing with the first input...
HEre is my loop code on the arduino
void loop() {
  if(Serial.available() > 0){
    led = Serial.read(); // from python script the led to operate
    led = led - '0';
    if(led >= '0' && led <= '7'){
      if(Serial.available() > 0){
        ledState = Serial.read(); // expects the led state next
        ledState = ledState - '0';
        if(ledState == '0'){
          shiftWrite(led,LOW);
        }else if(ledState == '1'){
          shiftWrite(led,HIGH);
        }
      }
    }
  }
}

shiftWrite is a function I wrote because there are 8 LEDS hooked to a shiftRegister
update:
I tried the state machine suggestion and it didnt work...
  void loop() {
  while(Serial.available()){
    led = Serial.read();
    led = led - '0';
    if(led>= 0 && led <= 7){
      state = 1; //We've received the LED # go to state 1
      Serial.println(led);
      Serial.println(state);
      Serial.println(ledState);
      continue;
    }
    if(state == 1){
      ledState = Serial.read();
      ledState = ledState - '0';
      if(ledState == '0'){
        shiftWrite(led,LOW);
      }else if(ledState == '1'){
        shiftWrite(led,HIGH);
      }
      state = 0; //Ended the operation return to state 0
    }
  }
}

With the serial monitor in the arduino IDE open (not running the python script) I tried this input: 4,1
This is my output on the serial monitor:
4
1
0
1
1
0

Any ideas? Basically the same problem as before...I actually thought the state machine idea would work...

You actually didn't follow exactly my solution, you're assuming that '0' is 0 and '1' is 1 while in fact, '0' = 48 and '1' = 49. You have to write if(ledState == 0) not '0'. same for '1'

I'll give that a shot

void loop() {
while(Serial.available()){
led = Serial.read();
led = led - '0';
if(led >= 0 && led <= 7){
state = 1; //We've received the LED # go to state 1
Serial.println(led);
}
if(state == 1){
ledState = Serial.read();
ledState = ledState - '0';
Serial.println(ledState);
if(ledState == 0){
shiftWrite(led,LOW);
}else if(ledState == 1){
shiftWrite(led,HIGH);
}
state = 0; //Ended the operation return to state 0
}
}
}

Entering 4 ... it outputs
4
-49
So it's somehow jumping and setting ledState before I enter anything.

I figured it out, check your Serial Monitor, you must set it to No Line Ending. There is nothing wrong with the code, it's just the Serial Monitor, when you press Enter, it sends another character which makes the loop go crazy.

It is set no line ending... I was only using the serial monitor to debug...pythons output is doing the same thing

Post your complete code not only the loop(). It actually worked for me.

Try this code, it is working as intended:
void setup() {
  Serial.begin(9600);
}

int state = 0;
int led;
int ledState;

void loop() {

  while (Serial.available())
  {
    if (state == 0)
    {

      led = Serial.read() - '0';
      if(led >= 0 && led <= 7)
      {
        state = 1;
        Serial.println("Got LED number: " + String(led));
        break;
      }
    }
    if (state == 1)
    {
        ledState = Serial.read() - '0';
        if(ledState == 0)
        {
          Serial.println("LED n " + String(led) + " is now OFF");
        }
        else if(ledState == 1)
        {
          Serial.println("LED n " + String(led) + " is now ON");
        }
        state = 0;
    }
  }

}

This makes sense. I haven't tried it against my python code...but breaking from the loop once the LED is chosen should fix my issue.  I will update you tomorrow if this works.

You're assuming that the microcontroller is going to wait until you choose LED state, which is wrong. Try this:
int state = 0;
int led;
int ledState;

void loop() {
  while (Serial.available())
  {
    if (state == 0)
    {
      led = Serial.read() - '0';
      if(led >= 0 && led <= 7)
      {
        state = 1; // Here we have got the LED number, go to state 1
        continue;
      }
    }
    if (state == 1)
    {
        ledState = Serial.read() - '0';
        if(ledState == 0)
        {
          shiftWrite(led,LOW);
        }
        else if(ledState == 1)
        {
          shiftWrite(led,HIGH);
        }
        state = 0; // Here we ended the operation, return back to state 0
    }
  }

}

You need what we call a state machine, here I use state=0 for the state corresponding to choosing LED number, state=1 is for the state that waits for the operation ON/OFF.

I tried that, but its still not working. To debug I've got the serial monitor on the arduino ide communicating...and printing out what the arduino is receiving... I'll post a response so you can see my code...

I've updated my post...so you can see the output and new code.


text:
How to change SIM908 GPS location coordinates format?
I am using the SIM908 module to get GPS position.
The SIM908 sends the latitude and longitude in the ddmm.mmmm format, but major online services for GPS location (for example, Google Earth) use the dd.dddd format.
So, how can I modify my code to convert coordinates from the SIM908 to dd.dddd format?
This is the SIM908 GSM Library Code that I am using:
#include "gps.h"
char GPSGSM::getBattInf(char *str_perc, char *str_vol)
{
     char ret_val=0;
     char *p_char;
     char *p_char1;

     gsm.SimpleWriteln("AT+CBC");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("+CBC"))
          ret_val=1;

     //BCL
     p_char = strchr((char *)(gsm.comm_buf),',');
     p_char1 = p_char+1;  //we are on the first char of BCS
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_perc, (char *)(p_char1));

     //Voltage
     p_char++;
     p_char1 = strchr((char *)(p_char), '\r');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }
     strcpy(str_vol, (char *)(p_char));
     return ret_val;
}

char GPSGSM::getBattTVol(char *str_vol)
{
     char *p_char;
     char *p_char1;
     char ret_val=0;

     gsm.SimpleWriteln("AT+CBTE?");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("+CBTE"))
          ret_val=1;

     //BCL
     p_char = strchr((char *)(gsm.comm_buf),':');
     p_char1 = p_char+2;  //we are on the first char of BCS
     p_char = strchr((char *)(p_char1), '\r');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_vol, (char *)(p_char1));
     return ret_val;
}

char GPSGSM::attachGPS()
{
     if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSPWR=1", 500, 100, "OK", 5))
          return 0;
     if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSRST=1", 500, 100, "OK", 5))
          return 0;
     return 1;
}

char GPSGSM::deattachGPS()
{
     if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSPWR=0", 500, 100, "OK", 5))
          return 0;
     return 1;
}

char GPSGSM::getStat()
{
     char ret_val=-1;
     gsm.SimpleWriteln("AT+CGPSSTATUS?");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("Unknown")||gsm.IsStringReceived("unknown"))
          ret_val=0;
     else if(gsm.IsStringReceived("Not"))
          ret_val=1;
     else if(gsm.IsStringReceived("2D")||gsm.IsStringReceived("2d"))
          ret_val=2;
     else if(gsm.IsStringReceived("3D")||gsm.IsStringReceived("3d"))
          ret_val=3;
     return ret_val;
}

char GPSGSM::getPar(char *str_long, char *str_lat, char *str_alt, char *str_time, char *str_speed )
{
     char ret_val=0;
     char *p_char;
     char *p_char1;
     gsm.SimpleWriteln("AT+CGPSINF=0");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("OK"))
          ret_val=1;

     //longitude
     p_char = strchr((char *)(gsm.comm_buf),',');
     p_char1 = p_char+1;  //we are on the first char of longitude
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_long, (char *)(p_char1));

     // latitude
     p_char++;
     p_char1 = strchr((char *)(p_char), ',');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }
     strcpy(str_lat, (char *)(p_char));

     // altitude
     p_char1++;
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_alt, (char *)(p_char1));

     // UTC time
     p_char++;
     p_char1 = strchr((char *)(p_char), ',');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }
     strcpy(str_time, (char *)(p_char));

     // TTFF
     p_char1++;
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }

     // num
     p_char++;
     p_char1 = strchr((char *)(p_char), ',');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }

     // speed
     p_char1++;
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_speed, (char *)(p_char1));

     return ret_val;
}

void parseTime(char *field, int *time)
{
     ////////////////Time////////////
     char tmp[4];
     tmp[2]=0; // Init tmp and null terminate
     tmp[0] = field[8];
     tmp[1] = field[9];
     time[0] = atoi(tmp); // Hours
     tmp[0] = field[10];
     tmp[1] = field[11];
     time[1] = atoi(tmp); // Minutes
     tmp[0] = field[12];
     tmp[1] = field[13];
     time[2] = atoi(tmp); // Seconds
     /////////////Date///////////////
     tmp[0] = field[0];
     tmp[1] = field[1];
     tmp[2] = field[2];
     tmp[3] = field[3];
     tmp[4]=0; // Init tmp and null terminate
     time[3] = atoi(tmp); // year
     tmp[0] = field[4];
     tmp[1] = field[5];
     tmp[2]=0; // Init tmp and null terminate
     time[4] = atoi(tmp); // month
     tmp[0] = field[6];
     tmp[1] = field[7];
     tmp[2]=0; // Init tmp and null terminate
     time[5] = atoi(tmp); // day
}

// Read the latitude in decimal format from a GGA string
double convertLat(char* latString)
{
     double latitude = atof(latString);                                    // convert to a double (precise)
     int deg = (int) latitude / 100;                               // extract the number of degrees
     double min = latitude - (100 * deg);                  // work out the number of minutes
     latitude = deg + (double) min/60.0;                   // convert to decimal format
     return latitude;
}

// Read the longitude in decimal format from a GGA string
double convertLong(char* longString)
{
     double longitude = atof(longString);                                  // convert to a double
     int deg = (int) longitude / 100;                              // extract the number of degrees
     double min = longitude - (100 * deg);                 // work out the number of minutes
     longitude = deg + (double) min/60.00;                 // convert to decimal format
     return longitude;
}

You can convert between formats, as explained here

This could be a general programming question. The only thing specific to
Arduino here is that you may want a solution that minimizes the use of
memory and avoids floating point operations.
Here is a memory-friendly solution that reformats the string in place,
i.e. it overwrites the original string. In many cases this is
appropriate, as it is unlikely that you need the original string later,
but you have to make sure it fits your application. It works by first
moving a few characters around in order to have the format "dd.mmmmm",
then parsing the minutes and converting to fractional degrees, then
writing that in ASCII.
It should be noted that the only reason for dropping the last digit in
the minutes field is to avoid 32-bit operations. I compiled for an Uno
and checked the generated assembly: it uses only four bytes of RAM, in
the stack.
// Convert the format of a latitude from "ddmm.mmmm" to "dd.dddd".
// The string is converted in place.
void convertLat(char* s)
{
    // Convert ddmm.mmmm to dd.mmmmm
    s[4] = s[3];  // move minutes
    s[3] = s[2];  // move tens of minutes
    s[2] = '.';   // put decimal point
    s[8] = '\0';  // drop last digit

    // Compute fractional degrees.
    uint16_t fraction = atoi(s + 3);  // unit = 1e-3 arcmin
    fraction /= 6;                    // unit = 1e-4 deg

    // Write in ASCII, right to left.
    s[7] = '\0';
    for (int i = 6; i > 2; i--) {
        s[i] = fraction % 10 + '0';
        fraction /= 10;
    }
}

You can use this same function to convert a longitude from "dddmm.mmmm"
to "ddd.dddd" by just skipping the first character:
static inline void convertLon(char* s)
{
    convertLat(s + 1);
}

Addendum: To answer Lipsyor comment, it is possible to have the
latitude in units of 1e-6 deg by using 32-bit arithmetic:
// Convert the format of a latitude from "ddmm.mmmm" to "dd.dddddd".
// The string is converted in place.
void convertLat(char* s)
{
    // Convert ddmm.mmmm to dd.mmmmmm
    s[4] = s[3];  // move minutes
    s[3] = s[2];  // move tens of minutes
    s[2] = '.';   // put decimal point

    // Compute fractional degrees.
    uint32_t fraction = atol(s + 3);     // unit = 1e-4 arcmin
    fraction = (fraction * 10 + 3) / 6;  // unit = 1e-6 deg

    // Write in ASCII, right to left.
    for (int i = 8; i > 2; i--) {
        s[i] = fraction % 10 + '0';
        fraction /= 10;
    }
}

The + 3 in the computation is only to round to nearest. Dropping this
term should not make any significant difference.

There is a way to increase accuracy?

@Lipsyor: Sure. Do not drop the last digit, uint32_t fraction = atol(s+3) * 10 / 6;, and now fraction is in units of 1e-6 deg.

Thank you Edgar. I'm sorry but don't understand the operation in the code.
I removed the line that drop the last digit (s[8] = '\0';) and used uint32_t fraction = atol(s+3) * 10 / 6; instead of  uint16_t fraction = atoi(s + 3); fraction /= 6; but I have a great translation on the map. May you explain me?

@Lipsyor: You probably failed to properly write the number as ASCII. Since it's now in units of 1e-6 deg, you have to write six digits instead of four. C.f. the amended answer.


text:
LCD Pin Numbering vs I2C Controller Pin Numbering vs Sketch
I've been playing with an Arduino Uno, trying to get a 16x2 LCD screen to work with an I2C controller. I've got this LCD screen and this controller. And I've been trying to get the sketch below to work.
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7,3,POSITIVE);//, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup()
{
    lcd.begin(16,2);
    lcd.backlight();
    lcd.setCursor(0, 0);
    lcd.print("Hello world!");
    lcd.setCursor(0, 1);
    lcd.print("Row number: ");
    lcd.setCursor(12, 1);
    lcd.print("2");
}
void loop()
{

}

I've used an address scanner to verify that the address is correct (39 [0x27]), but it still won't display anything. It lights up, and I've tried adjusting the contrast, but it just won't display any characters.
I'm wondering if the definition of which pins are which is correct, but I can't seem to find anything detailing how the numbers used in the sketch correlate to the pins on the controller, which then correlate to the pins on the LCD screen. If any body can give me some insight I'd appreciate it.

In case it helps, the pins on the LCD screen are labeled as follows:
1  VSS VDD V0 RS RW E D0 D1 D2 D3 D4 D5 D6 D7 A K 16

So far I've tried a couple different things: I added a quick loop to blink the backlight, which does work with the constructor as shown; I added pull-up resistors to the data and clock pins, which didn't seem to affect anything; I tried switching the data and clock connections just in case, which then made the backlight not blink. I'll also add that I AM using the newer LiquidCrystal library from fmalpartida from here. Nothing has worked. Anybody have any more suggestions, please?

Yes, the pins can be different depending on the LCD and the controller. My favorite solution to this is to run a simple "i2c guesser" sketch that can be downloaded from the following forum thread (download link is at the bottom of the first post):
http://forum.arduino.cc/index.php?topic=260510.0
With that sketch it usually only takes me a couple minutes to find the correct pin numbers.

The handful of combinations that sketch tried did not seem to work. Thanks for the info though.


text:
Arduino Part Needs Identified

I do not know what part this is. I ordered an Arduino beginners kit and this part was not labeled. Please help!

It seems that it is an MPU6050 Module 3 Axis Accelerometer Gyroscope Module for Arduino.
Learn more: http://playground.arduino.cc/Main/MPU-6050


text:
How to connect MCP4141 digipot and a data logger shield to the same Arduino board
The main problem here is that they both need to communicate via the Arduino's SPI bus, and I know that each of the two devices will need its own CS pin (The data logger is hard wired to 10, so the digital potentiometer will need a different one)
This would be fine, except that the digital potentiometer has one pin for both SPI and SDO.
I read that to connect this to the Arduino, the shared pin on the digipot needs to be connected to the MISI pin on the Arduino (pin 12) and then to bridge the MISO pin to the MOSI pin with a resistor.
Would anyone be able to tell if this will work. I do not want to try connecting the two devices like this just in case it breaks something in the board.
Thanks

I have done the same thing in the past for a DS1302 RTC that uses the same communication system.  Yes, it works.  Will it interfere with the other communication though? Quite possibly.  It works fine for half duplex communication, but could cause interference with something else on the bus that is full duplex.
If in doubt, and you're not worried about high speed or high efficiency (you're not changing the potentiometer's value often) then use three other pins and bit-bang your own half duplex serial interface - it's not hard.

Thanks, I'll give it a go, and if it doesn't work, i'll try bit banging with three other pins. speed isn't a problem. I'll let you know how things go


text:
Diode lights generate false interruptions
I have spent quite a considerable time debugging my code that was triggering false interruptions. I have found out that the source of the error were the diode lights (on the picture). I would like to ask if anyone can point me to the possible source of such behaviour.
I will try to explain really briefly what the issue was providing only needed (from my point of view) details. If you would require more - tell me.
So, I have a board that looks like this:

You can see two reed switches (close circuit in the presence of a magnet) which leads the INT0 (pin 2) and INT1 (pin 3) on arduino to trigger an interruption on their RISING behaviour. The pull down resistors are 1kOhm. This cirquit works perfectly.
The original version of this circuit had lights in positions D5-D10 and D19-D24 (between the reed switches and the connections to the interruptor pins). The lights are these:

The part of the circuit with the red light (connected to INT1) worked flawlessly, while the circuit with the green light (connected to INT0) every once in a while triggered a false interruption in INT1. The lights, however were always blinking correctly.
I have nearly no experience with circuits and hardware, so a pointer on where to start reading to understand the issue is also welcome. Hope to hear from someone who knows what the cause could have been. I would still like to use the lights somehow, because they give a nice feedback on what is happening to the system.
Thanks!
PS. I do not think the code is necessary here, but I will post it too if you like. I am however quite confident that the bug is not on the software side.

Could be mechanical. Like the reed switch triggering due to vibration. Try swapping the two reed switches.

@Gerben, I though about it too. But the reed switches are far away from each other and while I test one, the other just rests on the table. The issue is definitely with the lights. When I take the lights out of the circuit everything works as intended.

What do you use the leds for? and.. They were with a series resistor, right?

@frarugi87, what do you mean by the series resistor? I'm afraid I don't understand that. I use them to indicate that the circuit has been closed. Just for visual information, that the magnet is close enough to trigger the reed switch. The actual functionality does not rely on lights of course. But it is nice to have such an indication.

Now I think I understood your problem ;) check my answer

Aaaaah, ok, now I see...
You put

+5V - Reed - LED - input pin - 1k resistor - ground

right?
If so the problem is that a red led has (usually) a voltage drop of about 1.5V, while the green one has a voltage drop of 1.8V-2.0V. The Atmega 328P has a Vih (i.e. the minimum voltage needed for a reliable high) of 0.6*Vcc, so for a 5V supply this value is 3V.
Consequently with a green LED you will have a value TOO CLOSE to the minimum acceptable value for the input pin. Note that the 2.0V value is an usual one, but different leds have different voltages.
Moreover the so-called high-brightness leds (the ones with a transparent case) have a more-than-3V voltage drop, so if you put for instance a blue led you will never receive a signal.
To solve the problem, you have three solutions:
1) use a (low brightness) red led also for the green path
2) remove the led from that path and drive it directly with the arduino (you will have also the notification that arduino has understood the command)
3) change the path to

+5V - Reed - input pin - LED - 1k resistor - ground

(i.e. take the voltage BEFORE the led, not after)
I think it'll work then :)
EDIT: according to the data I found on the internet the red led is usually 1.8V, while the green one is usually 2.1V. This does not change my answer, anyway.
And... You won't "fry" your pins with the 5V you are prividing to the circuit....

Thanks, that sounds about right! Thanks for the nice explanation! As the last small question - can you elaborate a bit more on your last sentence? "You won't "fry" your pins with the 5V you are providing to the circuit...." - am I on the way to doing this the way I've been addressing the problem?

That sentence was a reply to the edit to another answer (and the answerer removed the answer, so the sentence is meaningless now). He said that you'd better put the reed towards ground instead of vcc, otherwise you could fry the board. But this is not true, or at least this won't solve the problem. The only way to fry a pin with 5V is to connect it to Vcc and set it as an output in the arduino, but the same applies to a pin towards ground. If you set it as an input you can't fry it with 5V.

thanks! That agrees with what I know :) Then the issue is closed. Thank you again :)


text:
Problem with for loop
I'm having trouble with the syntax of code. I want to have the motor turn when the next average the program measures is 100 or more greater than the previous average it measured. I don't know how to write the if statement:
if(average == (average>=100)) {
for(pos = 0; pos <= 120; pos += 1) {
  sServo.write(pos);
  delay(50);
}
for(pos = 120; pos >= 0; pos -= 1) {
  sServo.write(pos);
  delay(50);
}
}

The motor should

turn when the next average the program measures is 100 or more greater than the previous average it measured

So simply write it:
// Old average is called "average"
// Compute the new average and put it in next_average
if ((next_average - average) >= 100)
{
  // Turn the motor
}
average = next_average;


text:
A question about Continuous Rotation Servo and Arduino
We have this project that uses a Continuous Rotation Servo and we have a slight problem controlling it. We're planning to attach a Rack Gear to the Servo to slide a stainless steel to the right, and vice versa.
The Question: Is it possible to stop the continuous rotation servo when the stainless steel hits a bump or it already made its proper position accurately?
This idea is like the Power Windows of cars.

Either add limit switches or use stepper-motors instead of a cr-servo.

You can track the servo rotation with an encoder and after reaching a specific position, you can send different instructions to execute other actions.
Other alternative is maybe you can place a limit switch at the position where you want it to stop.

I'd probably consider your suggestion. Thank you for your reply. :)

Glad I could help. Good luck.

The way that power windows detect fully open or closed is typically by measuring the motor current:  When a motor is stalled it's current increases because there is no longer any back-emf as there is when the magnetic fields are rotating.  You can measure this current and then stop when you see it increase over the running current.
This is especially useful in the context of the window example as limit switches would have to be set EXACTLY at the closed position which is hard to do and if they fail or get out of alignment can lead to burned out motors if the limit switch is set beyond the physical travel limit.  Furthermore, an obstruction will result in a burned out motor even if the limit switch is correctly set as the window could never reach its limit position.  In these two cases, a timeout would need to be included as a backup (A timeout is not a bad idea in any case!).


text:
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
So I try to compile and upload a simple code such as the Basic Blink.
I have not connected it to pin 0 or pin 1.
There is an LED with the "L" label on the card that works. So I guess not the chip is damaged?
I have selected the correct model which is Arduino Uno / Genuino. I've checked the drivers several times now, even reinstalled Arduino Software twice and tried on 2 different computers.
5V works with ground, I can get the LED to light up. But I cannot compile / upload code.
Error MSG: avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
(this message repeats 10 times with attempts)

I read something about bootloader, but I have no idea how to do this / what it is. I do not have the right components for bootloading I guess.
Also the COM is correct. I've tried using all the listed COMs without any result. Is this a hardware issue? Is my chip grilled or something?

That might be a bootloader issue, it is not hard to solve but you will need another arduino as programmer to reprogram the bootloader.

But the L led is working? If that one works, shouldn't the chip be working? By the way, how do I remove the chip?

Ah sorry, if the LED marked L ( usually known as pin 13 ) is on, then it might be another problem, since the booloader is still there. did you unplug any circuit attached to Arduino on upload time?

How to remove the chip? watch this video: https://www.youtube.com/watch?v=Hi5CsIsq28M

https://youtu.be/P6IKJehtB_c . Bad quality, but this is how it looks.

According to the video, your bootloader is still there and the reset works just fine, so the microcontroller is working. I see your TX LED constantly on ?!

TX led is flashing rapidly fast. Looks like it is sending all the time, is this normal?

No, there is something wrong, plug in your Arduino and try to uninstall its COM port from Device Manager, then unplug it, wait a few seconds and replug it again.

I uninstalled the COM port, waited a few seconds as you said and replugged it. Then I went over to the Arduino IDE and uploaded the blink again. Then the TX is high while it says "Uploading" and I still get the not in sync errors. Image: http://i.imgur.com/Kc4HltE.jpg

Overriding Baud Rate          : 115200 What does this mean?

I look into the Serial monitor, and it prints numbers like: 1187.50 etc

Yes, your arduino is constantly sending values to your computer. try to upload a sketch to your arduino and when you see uploading to I/O board try to press the reset button.

btw, make sure that you use AVRISP mkll as programmer.

I am using AVRISP mkll and tried reseting once I upload. No difference. Image: http://i.imgur.com/MOpwPSe.png

Try to connect RX and TX pins of your Arduino with a wire and then plug it to your computer, then open Serial Monitor and send some string and see if you get it back?

Should I add pinMode 0 and 1 as outputs in setup? I connected a wire from RX (0) to TX (1)

No don't use any sketch, just open the Serial Monitor and see what happens?

It prints numbers on the same line. I connected a wire from 0 to 1, right?

The TX light is flashing. RX light doesn't respond.

Do you have another arduino or another chip?

No, this is the only one. I uploaded an empty sketch and now the TX is lighting constantly.

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00 avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00 ...

Are there other solutions? I think the chip needs to be reprogrammed..

I feel the same, you either need another arduino to use it as ISP programmer or an AVR programmer.

I read somewhere else that one got it to work by changing the baud rate. Where do I change the baud rate? Did he just send a command in the serial monitor? avrdude.exe -v -P COM3 -c arduino -p atmega328p -b57600 ...

Before dealing with avrdude, did you try to change the usb cable? use a short one.

Also, try Tools->Programmer->AVR ISP. then upload blink sketch.

The solution that involved dealing with avrdude is for arduino clone boards based on CH340 chip. You arduino is obviously a genuine one.

Yes, mine is 100% genuine. I'll try the AVR ISP. And yes, I've tried 2 cables but none of them worked. They are long though.

Unfortunately it didn't work by changing to AVR ISP.

If you can get an AVR programmer that would solve your problem, it will use SPI interface to program the chip rather than the UART (Serial interface)

I tried another Arduino today and that one worked. So I guess the other Arduino board's chip has to be reprogrammed. Thanks for trying to help me.

Yes I think so, you may use that Arduino to reprogram yours.

You probably could try use Old bootloader option in the arduino IDE upload configuration

You should re-burn the bootloader. If you have another uno, you can burn bootloader here


text:
433MHz sending not receiving
I'm trying to send data using these cheap parts.
When I check the voltage on the data port of the transmitter, I see what I expect, 1.2 and 0.6 fluctuating while sending.
But when I check the receiver I get 0. I've got 3 of the sets and tried them all. Also tried it with running the transmitter on 11V for some extra power. I've added a LED to the transmitter to see when it transmits and I've added a not-so-good antenna to both while they are only 5cm apart during my tests.
Any advice would be appreciated.
Receiver
FS1000A with a LR433A
#include <VirtualWire.h>

const int led_pin = 6;
//const int transmit_pin = 12;
const int receive_pin = 11;
//const int transmit_en_pin = 3;

void setup()
{
    delay(1000);
    Serial.begin(9600);  // Debugging only
    Serial.println("setup");

    // Initialise the IO and ISR
    //vw_set_tx_pin(transmit_pin);
    vw_set_rx_pin(receive_pin);
    //vw_set_ptt_pin(transmit_en_pin);
    //vw_set_ptt_inverted(true); // Required for DR3100
    vw_setup(1000);  // Bits per sec

    vw_rx_start();       // Start the receiver PLL running
}

void loop()
{
    uint8_t buf[VW_MAX_MESSAGE_LEN];
    uint8_t buflen = VW_MAX_MESSAGE_LEN;

    if (vw_get_message(buf, &buflen)) // Non-blocking
    {
  int i;

        digitalWrite(led_pin, HIGH); // Flash a light to show received good message
  // Message with a good checksum received, print it.
  Serial.print("Got: ");

  for (i = 0; i < buflen; i++)
  {
      Serial.print(buf[i], HEX);
      Serial.print(' ');
  }
  Serial.println();
        digitalWrite(led_pin, LOW);
    }
}

Transmitter
#include <VirtualWire.h>

const int led_pin = 11;
const int transmit_pin = 12;
const int receive_pin = 2;
const int transmit_en_pin = 3;

void setup()
{
  // Initialise the IO and ISR
  vw_set_tx_pin(transmit_pin);
  vw_set_rx_pin(receive_pin);
  vw_set_ptt_pin(transmit_en_pin);
  vw_set_ptt_inverted(true); // Required for DR3100
  vw_setup(1000);   // Bits per sec
}

byte count = 1;

void loop()
{
  char msg[7] = {'h','e','l','l','o',' ','#'};
  Serial.println("sending");
  msg[6] = count;
  digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
  vw_send((uint8_t *)msg, 7);
  vw_wait_tx(); // Wait until the whole message is gone
  digitalWrite(led_pin, LOW);
  delay(1000);
  count = count + 1;
}

bro based on (You should be able to power the receiver + and GND I have one, which ran on 5v, I can't see if these are the same, and put a multimeter from GND to Data, and you should get about half of Vcc, ) he say
the problem is not with the module the problem is with the library

What I thought was the receiver turned out to be the transmitter. I've earned my noob medal now :)
The chip with the LR433A on it is the sending unit.
The code above and the wiring is all good!

I will, I have to wait a day to do that :)

Congratulations on your medal - I have a a pile of them this high ^

If you are not getting anything on the receiver, then the receiver is definitely the problem. These units will boost the gain until it get some signal, any signal.
You should be able to power the receiver + and GND (I have one, which ran on 5v, I can't see if these are the same), and put a multimeter from GND to Data, and you should get about half of Vcc, probably fluctuating a bit. If you look at the same with an oscilloscope, it should fluctuating wildly between 0 and Vcc volts. All of this should work without a transmitter, and without an Arduino (you will need a power supply for the receiver).
Note: this is from memory, I don't have mine here to test.
Once you are getting "random data" (background noise), you can progress to sending a signal.
Note that you should keep your "1"s and "0"s balanced to get a clear signal - check out Manchester encoding (this encodes a "1" as "1,0", and a 0 as "0,1", so there will be a perfect balance). You might also want to send a 1010101010 at the start - this gives the receiver a chance to adjust the gain to the correct level. Or, you can use some width-based encoding (e.g. "slow 1, slow 0" for a "1", and "fast 0, fast 1" for a "0").

When I put the multimeter to Data and GND on the receiver, the result is 0 fluctuating to -0 and you expect to see 50% of the Vcc input so around 2.5 Volts? I'll ask around for an osciloscope as I don't have one myself. Thanks for the advice on the signal encoding, I hope I can get to that soon.

I made a noob mistake as you can read below. Just wanted to let you know you are right about the half Vcc on the receiving Data+GND and thanks for your help.

In case anyone else sees your above comment, -0 means there is 0 volts flowing in the other direction. This is not uncommon when there is no power flowing through the wires, little random fluctuations will cause this. If there are less than -0 (e.g. -2.5volts), it means the power is flowing in the other direction (or you have the probes on your multimeter around the wrong way).


text:
Can I safely integrate 3,3v sensor with 5v Arduino UNO? How?
I plan to use Adafruit's RGB sensor with Arduino working as a RGB controller running on 5V. In my location, the 5V-compatible version of the sensor is not available.
There is a 3,3V pin on my Arduino board. Can I use it to power the sensor, or will the data pins (which are rated 5V) still burn it?
The TCS34725 chip uses I2C communication, which arguably would still be compatible with the 5V (http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter)
I am still very new to the electronics, and I don't feel confident enough to build my own level converter, and sadly, no converters advertised on arduino.cc are available in my country (Poland).

If you need I2C the best solution is go for a logic level converter based on BSS138 mosfet or similar. I've used a few and they never let me down. Examples: Sparkfun have this https://www.sparkfun.com/products/12009 and Adafruit http://www.adafruit.com/products/757

if you have also a few transistors available, you can make your own homemade solution till you get something more robust, according to arduino page: https://playground.arduino.cc/Main/I2CBi-directionalLevelShifter

(source: arduino.cc)

Thank you very much for this answer. The news is unfortunate for me, because these items seem not to be available in my country (including the ones you referred to). It seems it will be cheaper to ask retailers to get me the 5V-compatible version of the sensor instead.

You can use "logic level converter bidirectional," to connect modules with different voltage requirements. They are pretty cheap.


text:
sending ctrl-z in a struct?
I have a set of buttons wired to an arduino leonardo that are meant to send either single keystrokes to a computer "a, b, c..." etc, or a key sequence like ctrl+z (to perform an undo command.) Effectively this is a little usb keyboard with pre defined buttons. The way the struct is now, I can only manage to send one keystroke, never a modifier key+letter like I need.
The full code is listed here under "working code": Arduino sending keystrokes via push-buttons. Proper bouncing and manually setting buttons?
It just debounces the buttons and sends back actions (just single letters right now) using the ones defined in the struct. (thanks very much jwpat7)
The part in question is this
struct ButtonStruct buttons[nSwitches] = {
  {0, sw0, 'A'},
  {0, sw1, 'B'},
  {0, sw2, 'C'},
  {0, sw3, 'D'},
  {0, sw4, 'E'},
  {0, sw5, 'F'},
  {0, sw6, 'G'},
  {0, sw7, 'H'}};

I effectively want to replace the 'A' in {0, sw0, 'A'} to something that sends ctrl+z keystroke/keysequence instead of the letter 'A'.
I've tried KEY_LEFT_CTRL, setting a variable like char ctrlKey = KEY_LEFT_CTRL; and trying {0, sw0, ctrlKey, 'z'}, the "substitution" hex here: http://www.nthelp.com/ascii.htm and a number of other things.
I've read through a lot and I can't seem to find anything relevant. I've been told it's possible to use pointers to create a key-sequence but a -> operand in there just throws errors. I'm new and I realize I might have a core principal wrong, but isn't there some simple syntax to send a ctrl+z command (and then releasing it obviously) using that space? When I put {0, sw0, KEY_LEFT_CTRL, 'z'} it just reports "Lz", using the last letter in KEY_LEFT_CTRL instead of treating it as a modifier.  I'm so confused
(Also right now one press = one character and doesn't continually report like holding down a key on a regular keyboard.  I'd like to fix that too but I'd settle for just a bloody ctrl+z at this point.)
EDIT: Current Code (compiled!)
    enum { sw0=2, sw1=3, sw2=4, sw3=5, sw4=6, sw5=7, sw6=8, sw7=9}; // Switchbutton lines
enum { nSwitches=8, bounceMillis=42}; // # of switches; debounce delay
struct ButtonStruct {
  unsigned long int bounceEnd;  // Debouncing-flag and end-time
  // Switch number, press-action, release-action, and prev reading
  byte swiNum, swiActP, charMod, swiActR, swiPrev;
};

struct ButtonStruct buttons[nSwitches] = {
  {0, sw0, 'z',  KEY_LEFT_CTRL},
  {0, sw1, 'B'},
  {0, sw2, 'C'},
  {0, sw3, 'D'},
  {0, sw4, 'E'},
  {0, sw5, 'F'},
  {0, sw6, 'G'},
  {0, sw7, 'H'}};
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
    pinMode(buttons[i].swiNum, INPUT_PULLUP);
Keyboard.begin();
}
//--------------------------------------------------------
byte readSwitch (byte swiNum) {
  // Following inverts the pin reading (assumes pulldown = pressed)
  return 1 - digitalRead(swiNum);
}
//--------------------------------------------------------
void doAction(byte swin, char code, char tosend, char chmodi) {

if (chmodi) {    // See if modifier needed
   Keyboard.press(chmodi);
   Keyboard.press(tosend);
   delay(100);
   Keyboard.releaseAll();
} else {
   Keyboard.write(tosend);
}
}
//--------------------------------------------------------
void doButton(byte bn) {
  struct ButtonStruct *b = buttons + bn;
  if (b->bounceEnd) { // Was button changing?
    // It was changing, see if debounce time is done.
      if (b->bounceEnd < millis()) {
    b->bounceEnd = 0;    // Debounce time is done, so clear flag
    // See if the change was real, or a glitch
    if (readSwitch(b->swiNum) == b->swiPrev) {
      // Current reading is same as trigger reading, so do it
      if (b->swiPrev) {
        doAction(b->swiNum, 'P', b->swiActP, b->charMod);
      }
    }
      }
  } else {  // It wasn't changing; but see if it's changing now
    if (b->swiPrev != readSwitch(b->swiNum)) {
      b->swiPrev = readSwitch(b->swiNum);
      b->bounceEnd = millis()+bounceMillis; // Set the Debounce flag
    }
  }
}
//--------------------------------------------------------
long int seconds, prevSec=0;
void loop() {
  for (int i=0; i<nSwitches; ++i)
    doButton(i);
}

If you don't use swiActR take it out of the struct.  In current code, {sw0, 'R',  KEY_LEFT_CTRL} inits bounceEnd equal to sw0, swiNum to R, and swiActP to KEY_LEFT_CTRL.  Initializers have to be in the right order, ie have to match the order declared in struct.  Values can be left off at the end, to default to 0, but can't be left off the front

Ah, I see that, but even if I use {0, sw0, 'z',  KEY_LEFT_CTRL}, it appears I still get declaration errors in void doAction() like "'tosend' was not declared in this scope" and a few others

Both tosend and b aren't  declared in the scope of doAction.  Just change  char action, char chmodi to  char tosend, char chmodi  and delete the two lines with b-> at front.  In doButton add b->charMod to the first doAction call.  Delete else {         doAction(b->swiNum, 'R', b->swiActR); if you don't plan to do an action for button releases, else perhaps fix the code up with a modifier for the release action char.  Just make the function calls and function defs match up, only use vars that are in scope, etc

Woot! That compiled!  It was throwing each button like zP, AP, BP, etc but I just had to change the doAction to doAction(b->swiNum, 'P', b->swiActP, b->charMod); to order it correctly.  Awesome! I've updated the compiled code. It looks to be swiActR that is unused. Before cleaning that I just wanted to ask, is the current code handling key releases correctly on single characters without Keyboard.releaseAll(); after Keyboard.write(tosend); ? It's acting very well but I was under the impression swiActR was used for release before. Thanks so much! Checkmark+upvote on the way after you read this!

In some early code, swiActR held a character to be sent when a button on the arduino was released.   It wasn't related to sending a key-up to the PC.  IOW, Keyboard.write sends a key press and then a key release, so it was taking care of the PC side

Awesome, you walked me through this and I understand much better now, all my thanks!

First off, consider trying '\032' or '\x1A' for the ctrl-z.  (See, eg, How to send ctrl+z in C on stackoverflow.)
To send a ctrl-z, use something like:
Keyboard.press(ctrlKey);
Keyboard.press('z');
delay(100);
Keyboard.releaseAll();

For more examples of using modifier keys, see the KeyboardPress page at arduino.cc, and the example program KeyboardLogout.ino.  [To coordinate this with the struct data structure approach, you could use code somewhat like
tosend = b->actionChar1;
if (tosend < ' ') {    // See if modifier needed
   Keyboard.press(ctrlKey);
   Keyboard.press(tosend+96); // or is it 64?
   delay(100);
   Keyboard.releaseAll();
} else {
   Keyboard.write(tosend);
}

[You'll need to test which offset, 96 or 64, works in the above code; I don't have a Leonardo or similar to run this on, and haven't looked at the Keyboard library source to see how it treats this.]  Another way is to add a modifier-byte field in the struct, and issue it if its non-zero.]
Second, suppose the current form of ButtonStruct is analogous to
struct ButtonStruct {
  unsigned long int bounceEnd;  // Debouncing-flag and end-time
  // Switch number, press-action and prev reading
  byte swiNum, actionChar1, swiPrev;
};

where actionChar1 is the action character in use now.  You could add another byte to the struct, say actionChar2, and after a statement like Keyboard.write(b->actionChar1); add the following:
if (b->actionChar2)
  Keyboard.write(b->actionChar2);

which says to write out actionChar2 if it is non-zero.
In some of the questions linked to the previous question, you may see advice that Keyboard.write won't send non-printing characters.  I don't know if that's so, but in any case, there are mods available for Keyboard (ie, changes to the library) that allow non-printing characters and special characters to be sent.
Also note, if your program gets close to using all the RAM memory, you may want to keep buttons[] in ProgMem and access it from there so it doesn't need to be copied into RAM.  (See the three ProgMem questions that are linked in the top right sidebar . . .)   If you change the struct to use strings instead of single chars for its actions, using less RAM will increase in importance.
Edit re:  “what I don't know how to change ---> {0, sw0, 'A'}”:
{0, sw0, 'A'} initializes an element of buttons[].
In buttons[], each element is a ButtonStruct, because buttons[] is an array of ButtonStructs.  (For more about structs, see syntax and examples in eg Struct (C programming language) in wikipedia.)
You control what information can be in each element of buttons[] by modifying the definition of ButtonStruct.  If you need more data items in each buttons[] entry, then add more data items in the definition of ButtonStruct.  Likewise for fewer.
After you decide what information you need to have available to process a button press, modify ButtonStruct to contain exactly that information.  It may be that some information will apply in some cases but not in all.  If so, when you initialize buttons[], have some value (say 0) that stands for not-used, and fill in not-used spots with that value.
For example, if you need key modifiers (shift, ctrl, alt) add a modifier item to ButtonStruct.
Whenever you change ButtonStruct, you need to change buttons[] initialization to match.  For example, if ButtonStruct were to include Keyboard Modifiers and looked like
struct ButtonStruct {
  // Switch number, press-actions and prev reading
  byte swiNum, actionChar, charMod, swiPrev;
  unsigned long int bounceEnd;  // Debouncing-flag and end-time
};

[with some items in a different order than before!] your initializer elements in the buttons[] declaration could look like
  { sw29, 'Q' },

where charMod, swiPrev, and bounceEnd are left to default to zero, or like
  { sw37, 'R',  KEY_LEFT_CTRL},

where swiPrev and bounceEnd default to zero.
Then, in your button-action code you could say:
tosend = b->actionChar;
chmodi = b->charMod;
if (chmodi) {    // See if modifier needed
   Keyboard.press(chmodi);
   Keyboard.press(tosend);
   delay(100);
   Keyboard.releaseAll();
} else {
   Keyboard.write(tosend);
}

For those elements of buttons[] where you specified a modifier, the if's first branch executes, and for those where you didn't, ie, for plain unmodified characters, the second one does.
There are all sorts of variants on these methods.  For example, instead of specifying action characters and modifiers in the buttons[] array, you could change it so that you specify function names, or could have several classes of actions.  If 80% of the actions were to issue one simple character, make that class 0, so the action class can usually default to 0.

I'm afraid this doesn't help. Using {0, sw0, '\032'} or the '\x1A' reports nothing when the button is pressed. I have also previously tried the method of adding another action but it still leaves me with no clear syntax when trying to report a modifier like KEY_LEFT_CTRL in the struct. It never registers a ctrl at all much less combines it with 'z'..

This post is mistaken as it overlooks the fundamental fact that keyboards don't send ASCII codes - rather they send scan codes.

@ChrisStratton, yes, physical keyboards send scan codes, but the Arduino Keyboard library API accepts (for most calls) ASCII codes, not scan codes.  It also accepts some modifier-key codes like I mentioned in an answer-edit a few minutes ago

I apologise, I haven't made something clear.  THIS is what I don't know how to change ---> {0, sw0, 'A'}   I haven't used a setup like that before.  All these methods and I still need to know what goes in here---> {0, sw0, 'A'} to get new output.  I need some kind of alternate example for that bit of code to understand why I'm seeing the strange output I'm seeing.  The only thing that ever works in there is 'A' or a single character. If I use this setup without knowing how to change it I'm going to try something like  {0, sw0, actionChar1} or worse and It's going to fail again and again.

@sylcat, see edit

(sorry for the late reply, thank you for being patient with me) If I understood correctly, I add a charMod to the struct (And also needing and action character, I left actionChar as swiActP from the earlier code before.) If I'm right doButton is just the deBounce so that is left alone waiting to get to doAction, then in doAction I implement the if(chmodi) statement. I've edited in |current code| above which gets scope errors. Did I incorrectly pass char chmodi or place the tosend+chmodi declarations in the wrong place?

@sylcat See comment to Q


text:
Mpr121 multiple using breakout
I try more solution but there are not working. i use adafruit mpr121 lib, sparkfuns solution but there are not working. Some solutions say, cut the addr socket but i am not understand. maybe you show this solutions breakout, i try my code.

Unfortunately the wording of your question is very poor, however I think you are asking how to use multiple MPR121 devices on an Arduino?
According to the Sparkfun website you can change the I2C address from the default of 0x5A to one of four other addresses by cutting the jumpers on the back and connecting it to one of the other pins:

ADDR > GND  = 0x5A (default)
ADDR > 3.3V = 0x5B
ADDR > SDA  = 0x5C
ADDR > SCL  = 0x5D

I would also recommend using the Bare Conductive libraries rather than Sparkfun/Adafruit as they are more user friendly.


text:
Brushless motor "jiggles"
When I run my code, the ESC makes some noises, different on the high pulse and low pulse, then it begins to jiggle for a bit when it gets to the loop. Here is the code:
#include <Servo.h>

#define MAX_SIGNAL 2000
#define MIN_SIGNAL 1000
#define MOTOR_PIN 10

Servo motor;

void setup() {
  Serial.begin(9600);
  Serial.println("Program begin...");
  Serial.println("This program will calibrate the ESC.");

  motor.attach(MOTOR_PIN);

  // Wait for input
  while (!Serial.available());
  Serial.read();

  Serial.println("Now writing maximum output.");
  motor.writeMicroseconds(MAX_SIGNAL);
  delay(2000);

  // Send min output
  Serial.println("Sending minimum output");
  motor.writeMicroseconds(MIN_SIGNAL);
  delay(2000);

}

void loop() {
  motor.writeMicroseconds(MAX_SIGNAL);
}

Your code is familiar to the process of calibrating ESC controllers and is common. As your code is correct, we have to look at the connections. How is arduino connected to the ESC controller? can you provide a diagram? Only GND and Pin 10 should be connected. Do not connect the 5V of arduino. Power up the ESC with an external source. I think ESC signal port is Hi impedance so it should be no need for any resistor. Take a look at this site: http://robots.dacloughb.com/project-2/esc-calibration-programming/
You can see in that picture ( and the picture on the link provided), only pwm pin and ground are connected to arduino. Show us your connections if things keep going wrong. Also, does your power source provides enough juice to the motor?

I have seen that diagram and my connection is exactly like that. I think the power is the problem. How can I tell how much power is needed? Currently I am using a common square 9V battery.

can you provide us the model of the ESC you have? And if possible the motor model if any. That 9V may be the cause of that yes. I've searched a little more and came across this similar topic. In there they address two possible cause which can also be one of yours, the UBEC and the 9V. Take a look please, hope it helps. If motors came with some datasheet or similar, it could specify how much current it needs.

@DSchana this topic also describes similar problem as yours rcgroups. In the end the user also says he used a 9V with sucess but it quickly run out


text:
Can't read from DHT sensor when motor is running
I've been following this tutorial and I've run into some weird problems. When my motor starts running, I get "Failed to read from DHT sensor" on my serial window, meaning that readHumidity() and readTemperature() functions are returning NaNs.
This only happens while the motor is running. Once I stop the motor even momentarily, the DHT sensor starts working again.
Does anyone know why this is happening? I'm using a genuine UNO and a RHT03 sensor and some 5.9V motor (TD599839).
I've attached a diagram I made of my circuit in fritzing -

try to add a 100nF ceramic capacitor between the motor terminals.

And a flyback diode across the terminals, too - every little helps. On a different note, you are using a resistor with that LED, yes? I'll overlook the fact that it's the wrong way round in the schematic!

What is that capacitor doing there? Slow start?

First make sure that your motor has its own run back to ground - you must avoid motor current passing through the Arduino's ground.  Next, filtering your PWM is a bad idea - at a minimum it is inefficient.  You do not want to have your transistor "part way on" as that leads to conversion of power to heat in the transistor.  Instead, you want the transistor to only ever be fully on or off, applying full voltage to the motor at variable duty cycle. The inductance of the motor will cause some limitation of current, but the mechanical inertia of the rotor will accomplish the rest of the averaging.

Remove 10k resistor and use 1k instead. Or, just connect directly to Analog A0 pin. And modify your code. This may help you. Also consider GND to be 0V. Not below 1V instead while motor is working.

The problem may be electrical noise from the motor, or
you may have a wiring problem (an incorrect or intermittent connection).

Kira San’s comment “try to add a 100nF ceramic capacitor between the motor terminals” is directed toward suppressing electrical motor noise.  As brushes make or break connections on a motor's commutator, arcs and sparks can occur.  The capacitor will limit voltage rate of change thus suppressing some of that electrical noise.
CharlieHanson's comment (add a flyback diode across the motor terminals) is partly related to noise suppression but mostly to suppressing high voltage excursion that occurs when you shut off motor power.  While the motor is running, the magnetic field in it stores ½ L i² joules of power.  When current stops suddenly, those joules of power convert to a high voltage spike.  A flyback diode acts as a near-short to absorb that spike.  The cathode (cross-bar) of the flyback diode attaches to the high side of the motor voltage, as shown in the circuit diagram of the project you linked to on electroschematics.com.
Re “you are using a resistor with that LED, yes? I'll overlook the fact that it's the wrong way round in the schematic!”, if the LED is wired backwards as shown in your drawing, it won't turn on – which is a good thing, because without a resistor (say 300-3000 Ω) in series with the LED, enough current may flow to damage the Uno or the LED.  Turn the LED around on the schematic (and on your wiring setup if you didn't already), and add a series resistor.

Edit: A comment says, “Don't have a diode either :S Will an LED work instead?”.  LEDs typically have rather low reverse-voltage ratings – 4 to 5 volts.  You could put two or three in series and if they don't burn up you're ok for this experiment.  But in production, don't depend on LEDs as flyback diodes except where it doesn't matter what happens.

Gerben's comment, “What is that capacitor doing there? Slow start?” refers to the 100 μF capacitor shown between transistor base and emitter.  In conjunction with the 1KΩ resistor from D4, that gives RC=0.1 second, so the transistor will take an appreciable amount of time to turn on.  This has a couple of consequences:  PWM control may be less effective (at low duty cycles, PWM depends on short, high-current pulses, to overcome stiction etc) and the transistor will run hotter.  If it's a big power transistor, ok.  If it's a small switching transistor intended for full-on or full-off, no.

Edit: A comment refers to a fan speed controlled temperature page at electroschematics.com.  That page shows a BD139 power transistor, and says the 100 μF capacitor between transistor base and emitter eliminates some motor noise.  Thus it falls into the “big power transistor, ok” category.  Well, more or less ok.  A heat sink may be needed on the transistor and the capacitor probably doesn't need to be that big; eg try 10 μF instead of 100.

An ordinary 9V battery easily supplies a dozen milliamps, but current draw larger than that quickly depletes it.  See eg 9V Alkaline tests at powerstream.com and my answer to a previous question, Using Arduino Micro With 12V Buzzer that's somewhat related.  The motor shown (TD599839) is rated at 35 mA at 5.9 V no-load, so will draw say 50 mA no-load from a 9V battery and will try to draw several times that if loaded; ie it will overstress an ordinary 9V battery.  In brief: Use a wall-wart or equivalent, or a big battery, rather than a small 9V battery when running motors.

Sorry about that, didn't see that its backward in the schematic. I'm actually not using that LED in the actual project anyway, just playing around in fritzing. Thanks for pointing that out though.

I'm actually following another tutorial to control the motor speed -> http://www.electroschematics.com/9540/arduino-fan-speed-controlled-temperature/. Apparently its an RC filter to smooth out noise from the PWM.

Would it help if I changed the motor completely? Bought a less powerful one intended for hobbyists? Because the shop I bought the components from wasn't well stocked.

-> I'll try those out, but I don't have the necessary materials. 1. -> I only have 100uF capacitors, will those work? 2 -> Don't have a diode either :S Will an LED work instead? (or is that a totally crazy idea?)

@cybergla, see edits

In the long run if you are going to be in electronics I would suggest you learn how to draw schematics. KiCad is free and one of the better schematic capture programs available. It runs on most platforms. It will not be an overnight learning experience but there are lots of tutorials on line for it. If later you want to do simulation you will probably have to do a schematic anyway.