Running a servo and tone() won't compile? "multiple definition of `__vector_32'"? Im using Spark fun pro micro:https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro

I am controlling a servo motor which reads its data from a pot connected to A0, and then writes to the servo on D9.

A speaker is connected to A5. Im using tone()

If I comment out the servo part of it, the tone() works out just fine and vise versa..
The error message I get is "multiple definition of `__vector_32'"

Got a clue??!
Thanks!

The problem you're seeing arises when two codes (e.g. libraries) try to use the same interrupt.

If you look at the source code of the two libraries, you'll find that they both make use of a number of ISRs (interrupt service routines): Tone.cpp uses

ISR(TIMERn_COMPA_vect) {...}

for n = 0..5, while Servo.cpp uses

ISR(TIMERn_COMPA_vect) {...}

for n = 1, 3, 4, 5.

Now what happens when you compile this code is that they both libraries generate identical symbols (the __vector_32 part) which then clash when the compiled code is linked to give the final binary you'd upload to your Arduino.

There is no simple way around this because the interrupt handlers need to be  registered at certain fixed positions in flash memory and there can only be exactly one interrupt handler for each of these slots (these slots are simply entries in a look-up table with the addresses of the interrupt handlers in flash, cf. Table 9-1 in the datasheet).

Now to solve this problem you would need to find a way to either merge the interrupt handlers of the two libraries (not so easy I guess), or make them use different interrupts (without looking further into what options the pro micro offers, the code suggests that there are several TIMER interrupts which could be assigned one to the Servo, one to the Tone, if that is supported by the hardware).

In any case you'll not get around modifying the libraries (or writing your own code for one functionality or the other).


DS2413 One Wire IC read and store the addresses of individual IC's Hy,
Here I using 10 DS2413 to control gpios, it works very well with arduino ,I read the 10 ic address and store it in a 2D array, I want to control the individual IC using their address .Here all works well. My problem is the Ic address are not store in arrange wise manner. For ex, I have 10 IC's, Each IC's have unique address, The address of first IC1 is store in arr1, address of ic2 is arr2 and address of ic3 is store in arr3..... what i need is If i Swap the IC1 and IC2 the address of IC2 is store in arr1 and IC1 address is store in arr2.

The OneWire system has no concept of the arrangement of the bus. All it knows is the addresses, and it always searches for those addresses in a pre-defined order.
No matter what arrangement you have on the bus the devices will always be found in the same order.
You can think of it akin to a teacher taking the register in class. They call out the names in alphabetical order and the pupils answer (if they are there). All it tells the teacher is who is there and who isn't. It doesn't give them any information about where in the class the pupil is sat.
You can read more about how the address searching is done here.


Does the SIM800L works in the US? I want to know if the SIM800L works on US soil? I can´t get it to work on the H2O network! Does it work wit ATT or I only need the APN settings? If so what are the commands for data connection and configuration? Does the SIM800C works then?

I wanted to post an update in April 2021 on the status of this question.
The SIM800L will work in the US, but T-Mobile is the only carrier that it can interface with. AT&T shut down its compatible towers in 2017. T-mobile will shut down its 2G network at the end of 2022.
So, the SIM800L is only good for another year and a half. Maybe you're better off finding a different module!


Arduino-based mains frequency monitor follow-up Following my
previous question, I'm getting closer to thinking about putting together this mains frequency monitor. I would just like to do a sanity check on my electronics before I order the components and the board. Please keep in mind I am not qualified in this so I have had to research how all this will work.

A and B inputs will accept power from a 16VAC 1.25A unregulated power pack.

C1 is a 1µF 25V 85°C ceramic capacitor. I guess this is mostly unnecessary as the power pack should filter any DC bias, but it won't hurt.

D1 is an IN4001 1A standard recovery diode.

R1 is a 300ohm 500V 3W resistor. The RMS power is 16VAC, which is half-wave rectified, so that's sqrt(2) * 16 = ~24V peak @ 300ohm = 80mA peak, and about 25mA on average (right?)

IC1 is a 4N28 optocoupler. It's weird, in one data sheet I see 80mA max forward current on inputs but in another I see 60mA. Anyway, the average should be 25mA so I guess that's probably going to be okay?

The Arduino I will use is the Arduino Micro, as it's quite small and also has a 16Mhz crystal oscillator that will provide a more stable clock than a ceramic resonator. The Arduino will be powered by USB, which I believe is 5V. The digital I/O pins I believe will also operate at 5V and are rated at 40mA max.

C will come from one of the Arduino's digital output pins, and D will go to the Arduino's GND.

R2 is a 150ohm 500mW 250V resistor, that should ensure the C→D current does not exceed 40mA @ 5V.

Now, assuming the components look okay and the circuit looks okay (I assume the circuit is fine), I just had some questions:

Do I need to add anything to the output of the 4N28 coming from the input? I think with a regular transistor, some of the base current gets added to the collector current?
What can I expect the response on the output of the 4N28 to look like? I assumed that it would more-or-less be a square wave, where even a tiny current on the input would activate the transistor and allow the output current to flow freely on the other side, but someone has suggested that this might not be the case?
The way it is set up, the Digital I/O pin can be "trying" to output or not, and that's basically irrelevant to what the transistor is doing. When the transistor is on, the output current from the pin will successfully flow to GND. I assume there is a way to detect this in the Arduino? Something like setting the output pin to 1 and check in loop when there is or is no current flowing?

Thank you!

You should remove the capacitor. It won't remove any DC offset because there can be no DC offset. From where would the DC offset be relative? There is only two points in the circuit, and both of them are direct from the transformer and is an AC waveform. There is no concept of a DC offset in such a circuit.  All the capacitor will do is impose a phase change between the current and voltage of the AC waveform limiting the current during the conducting period of the diodes. You have a resistor for that function.

You make some incorrect assumptions about how to read the data. You talk about outputting a signal and somehow finding out if the transistor is on or not by if that signal is being output. That's completely backwards. Instead you should treat the transistor like a simple pushbutton and provide it with a pullup (or pulldown if you prefer) resistor, like this:

simulate this circuit – Schematic created using CircuitLab

You should feed the signal into an interrupt-enabled pin (such as D2 on the Uno as shown) so that an interrupt can be used for capturing the incoming edge time. Better would be to use the Input Capture peripheral, but that is harder to program for as there is no (AFAIK) library for it.

Yes, it would be possible to use the internal pullup resistor of the input pin instead of an external one, however using an external one allows you to fine tune the resistance which, coupled with the gate capacitance of the input pin, forms a low-pass filter limiting the frequency range you can monitor. At 50Hz it shouldn't be a problem though, so the choice is yours. Personally I use an external one.


producing sine wave variable in amplitude and frequency How to produce a sine wave with variable frequency and variable amplitude?
I found a library to produce variable frequency called sinwave but not produce variable amplitude (I want -2V to 2V amplitude)

You can use a digital potentiometer as a programmable attenuator or as a feedback element in a programmable gain amplifier circuit.

See references  at arduino.cc regarding interfacing an AD5171 or AD5206 to Arduinos.


Updating Server using ESp8266 with Direction Button Pressed IN I've connected a 5-way tactile switch to a ESP8266 module and am using the Arduino IDE to create an automatically updating web server that displays the direction that the button is pressed in when pressed. Currently the webpage displays the first direction that the button was pressed in but does not update the page after I press the button several more times. Below is my code:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

//ssid and password info, ommitted here for obvious reasons

int upPin = 5;
int leftPin = 4;
int centerPin = 0;
int rightPin = 2;
int downPin = 14;

ESP8266WebServer server ( 80 );

void handleRoot() {
    server.send(200, "text/html", "\
  \
    <meta http-equiv='refresh' content='1'/>\
  \
  \
  \
");   // Send HTTP status 200 (Ok) and send some text to the
browser/client
}

void setup(){
 Serial.begin ( 115200 );
 WiFi.mode ( WIFI_STA );
 WiFi.begin ( ssid, password );

 server.on ( "/", handleRoot );
 server.on ("/", button );
 server.begin();

void loop(void){
  server.handleClient();
  button();
}

void button(){
  if (digitalRead(rightPin) == LOW)
  {
    server.send(200, "text/html", "
*RIGHT#
");
    delay(10);
  }

  if (digitalRead(leftPin) == LOW)
  {
    server.send(200, "text/html", "
*LEFT#
");
    delay(10);
  }

  if (digitalRead(upPin) == LOW)
  {
    server.send(200, "text/html", "
*UP#
");
    delay(10);
  }

  if (digitalRead(downPin) == LOW)
  {
    server.send(200, "text/html", "
*DOWN#
");
    delay(10);
  }

  if (digitalRead(centerPin) == LOW)
  {
    server.send(200, "text/html", "
*CENTER#
");
    delay(10);
  }

}

I changed the code so that the button function runs with "/" and took out the server.on("/", handleRoot) line, thanks to @Juraj. Sigh


Arduino Due Pinout with Explanations? I am trying to understand what each pin on my Arduino Due is and what it is used for, and so I have been searching for things like "Arduino Due pinout", "Arduino Due pin mapping" and similar.

The best I could find was this table, however it doesn't help you out at all if you are completely new to electronics and have no idea what TX2, SDA or NPCSO mean, etc.

Does anybody know of Arduino/Due documentation that explains what each I/O pin is?

The Arduino Due is backed by an Atmel SAM3X8E ARM Cortex-M3 microprocessor and most of the pins on the Due are connected directly to this chip. Therefore, you can refer directly to the chip's datasheet for descriptions of these hardware features.

Atmel SAM3X8E ARM Cortex-M3 datasheet


1x4 Button membrane help Im trying out this membrane from Adafruit that i bought last week but i have a little issue. ITS SO SENSITIVE! i as so just touch it with my finger and it transmits!. Anyone that has worked with this membrane have the same issue? is there some sort of "fix"?

UPDATE

Its really simple. But one weird thing, not sure if its supposed to be like that, but by default, the buttons are on HIGH. i used Serial.println(digitalRead(one)); to verify that and the output was 1.

int two =  8;
int one = 9;
int four = 10;
int three = 11;

void setup() {
  pinMode(one, INPUT);
  pinMode(two, INPUT);
  pinMode(three, INPUT);
  pinMode(four, INPUT);
  Serial.begin(9600);
}

void loop() {
  if(digitalRead(one) == LOW){
    Serial.println("One");
  }else if(digitalRead(two) == LOW){
    Serial.println("Two");
  }else if(digitalRead(three) == LOW){
    Serial.println("Three");
  }else if(digitalRead(four) == LOW){
    Serial.println("Four");
  }
}

pinMode(one, INPUT);

You have configured the input with no pullup. Since it is a CMOS input and hence very high impedance, it effectively acts as an antenna picking up random signals including that of your finger becoming capacitively coupled to it. You must enable the pullup on the pins (and connect the common to ground) if you want correct operation.

 pinMode(one, INPUT_PULLUP);


ESP8266 Library Method List Is there a place that lists all the common methods used with the standard ESP8266 libraries in Arduino?

Looking at the GitHub page, there is a document explaining how everything works, https://arduino-esp8266.readthedocs.io/en/latest/


How to use float data from a sensor with the Arduino mouse library I'm using a gyroscope, which returns angular velocity in floats. I'm trying to use this data with the arduino mouse library. The move function requires a signed character. I'm not what the best way is to convert the float data from the sensor into signed char.
In what way can I do this, losing the least in terms of precision?
I found out you can use dtostrf to transfer floats into an array of characters, but not sure what to do following this or if it's even the best way.
I would appreciate any guidance.

The mouse library expects the movement coordinates to be provided as
8-bit signed integers, which corresponds to the int8_t data type. This
type is actually an alias to signed char, but calling it this way is
confusing, as the word char somehow implies a type meant to store
characters, which is definitely not the case here.
Converting a float to any integer type can be done by plain
assignment, with two caveats:

If the float exceeds the range of the integer, the assignment will
wrap around modulo 2^(integer size in bits). This is undesirable and
can be prevented by first constrain()ing the float to the
appropriate range.
The assignment rounds towards zero, whereas rounding to the nearest
integer is better if you want to minimize the errors. This can be
achieved with the round() macro.

In summary:
// In global context:
const float scale = 0.4;  // scale factor for mouse moves

// Within loop():
float rotation = get_data_from_gyroscope();
int8_t mouse_move = round(constrain(rotation * scale, -128, +127));

Note that the optimal scale can only be determined experimentally: you
have to tweak it until your input device “feels” right.


Help making LEDs blink like blinkers in a car I am trying to make blinkers and hazards lights for a car.  I can get
the left and right blinkers to work. I cannot figure out how to get
the lights to blink simultaneously like hazard lights would.

What I think I want is that when both inputs are HIGH then Both LEDs will
blink together at the same time.

I left the garbage and comments in the code so you can see what I have
tried.

Thanks for your help.

/*
 Blinkers and Hazard Lights

 Simulates a vehicles blinkers and Hazard Lights
 left button connected to pin 2 using a pushdown resister
 right button connected to pin 3 using a pushdown resister
 left LED connected to pin 9
 right LED connected to pin 10
 Hazard LED is Pin 13 At one point I was trying to make pin 13 represent the hazard lights but that is not what I want to do.

 When left button is pushed Left LED will Blink
 When Right Button Is pushed Right LED will Blink

 If this worked the way I wanted it to. when both buttons where HIGH both LED 9 & 10 would blink simultaneously.

 created 2015
 by thomsl41@gmail.com

*/

// constants won't change. They're used here to
// set pin numbers:
const int buttonPinLeft = 2;     // the number of the pushbutton pin
const int buttonPinRight = 3;
const int buttonPinHazard = 2 && 3;
const int ledPinLeft = 9;      // the number of the LED pin
const int ledPinRight = 10;
const int ledPinHazard = 13;

// variables will change:
int buttonStateLeft = 0;         // variable for reading the pushbutton status
int buttonStateRight = 0;
int buttonStateHazard = 0;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPinLeft, OUTPUT);
   pinMode(ledPinRight, OUTPUT);
   pinMode(ledPinHazard, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPinLeft, INPUT);
  pinMode(buttonPinRight, INPUT);
  pinMode(buttonPinHazard, INPUT);
}

void loop(){
  // read the state of the pushbutton value:
  buttonStateLeft = digitalRead(buttonPinLeft);
  buttonStateRight = digitalRead(buttonPinRight);
  buttonStateHazard = digitalRead(buttonPinHazard);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonStateLeft == HIGH) {
    // turn LED on:
  digitalWrite(ledPinLeft, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(ledPinLeft, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second
  }
 else {
    // turn LED off:
    digitalWrite(ledPinLeft, LOW);
  }

if (buttonStateRight == HIGH) {
    // turn LED on:
  digitalWrite(ledPinRight, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(ledPinRight, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second

}
  else {
    // turn LED off:
    digitalWrite(ledPinRight, LOW);
  }
}

/*if (buttonStateHazard == HIGH) {
    // turn LED on:
  digitalWrite(ledPinLeft, LOW);
  digitalWrite(ledPinRight, LOW);
  digitalWrite(ledPinHazard, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(2000);              // wait for a second
  digitalWrite(ledPinHazard, LOW);    // turn the LED off by making the voltage LOW
  delay(2000);              // wait for a second
  //}
 //else {
    // turn LED off:
   // digitalWrite(ledPinHazard, LOW);
 }

}
*/

It looks like you need to do something like:

if ((buttonStateRight == HIGH) && (buttonStateLeft == HIGH)) {
    digitalWrite(ledPinRight, HIGH);
    digitalWrite(ledPinLeft, HIGH);
}
else if (buttonStateRight == HIGH) {
    digitalWrite(ledPinRight, HIGH);
}
else if (buttonStateLeft == HIGH) {
    digitalWrite(ledPinleft, HIGH);
}
//One delay for all
delay(500);
//Shut anything off that might be on after the delay
digitalWrite(ledPinRight, LOW);
digitalWrite(ledPinLeft, LOW);

Your code is really hard to read but it may mostly be because you need to insert four spaces at the beginning of each line of code to make it look right on this forum.


Switching a Solenoid Using Arduino's 5V Output? I'm a bit stumped on how to switch on a solenoid using a transistor using my Arduino Nano's 5v Output. The solenoid runs on 12V, so I used an NPN transistor to connect the 12V source to the solenoid whenever Arduino sends current to the transistor's base. I connected all the grounds together to the Nano's ground pin, but the solenoid still doesn't switch.
I know the transistor works properly, because the solenoid switches when I use the battery to send base current instead of the Nano. I would think the Nano is capable of sending enough current to activate the Collector -> Emitter path but might be wrong. I'm also wondering if it's an issue with grounding the circuit, but I've made sure there is a common ground. What do you think I'm doing wrong? BTW the transistor I am using is D882P. I would appreciate any help.

simulate this circuit – Schematic created using CircuitLab

Note: this answer demonstrates using the 2N3904 NPN transistor for all of the calculations, since that's what's in the schematic in the question. However, after writing the answer, I noticed the words at the end of the question state it is a D882P (also an NPN type) transistor. So, just follow my methodology here but use the appropriate values for your NPN transistor type, which you can obtain from the datasheet. A quick Google search for "d882p datasheet" reveals this as a potential datasheet.
2N3904 is an NPN transistor (datasheet), as opposed to a PNP transistor, so it must be connected directly to GND and switch the low side of the circuit only, so wire it like this instead:

simulate this circuit – Schematic created using CircuitLab
Notice I've added a diode, D1, to dissipate inductance-induced voltage spikes created when electromagnetic fields (a form of energy storage) collapse in the inductor each time you turn the switch OFF. This diode, due to its function (not type), is called a "flyback", "snubber", or "clamp" diode. Again, it protects the transistor and other components from inductance-induced voltage spikes from the relay coil/inductor. When a voltage spike occurs, it will simply travel around that loop through the diode, relay, and resistor R2 again and again and again until it has all been dissipated as heat in those components and there is no more voltage spike remaining.
I've also added a resistor R2 to limit current through the relay coil. You'll have to size this appropriately to get the correct current through your relay coil, based on the relay's datasheet. If your relay's datasheet says to hook up the relay to 12V directly, you can remove this resistor.
And you'll definitely need a base resistor (R1 in my circuit) or else you'll burn up your Arduino pin.
First, let's collect some necessary values from the Datasheet. These will be used in the calculations below:

VBE(sat) = 0.65 to 0.95V.

This is the diodic voltage drop from Base to Emitter when the transistor is "saturated", or fully ON.

hFE_min = 30

Notice in the screenshots below that I have crossed out all of the 2N3903 transistor hFE entries so they don't distract us from the 2N3904 entries, which is the transistor type I'm using for this example. I then chose the lowest hFE entry for this transistor, which is 30.
This is the "guaranteed" minimum, or worst-case, DC current gain. The formula is simply: I_max_permitted_from_Collector_to_Emitter = gain * I_Base_to_Emitter. So, if your gain is 30, for example, and you drive a base current of 5mA from Base to Emitter, then the "guaranteed" maximum possible current allowed from the Collector to the Emitter will be 30 gain * 5mA = 150mA. Again, this is not what you will get into the Collector, this is what you could get before the transistor itself starts limiting the current into the Collector rather than your load limiting the current through the Collector.

Ic_max_continuous = 200mA

This is the max continuous current you can get from Collector to Emitter without overheating the transistor (assuming, I think, you have adequate cooling through conduction and possibly even convection and radiation via heat sinks--I need to brush up on the thermal and power equations myself). The datasheet may specify if a heat sink is required to achieve this current, but regardless, you should keep your continuous current down to about half this value or less if possible, as the device may reach crazy high temperatures of like 150 C or something with this current and no convective cooling or heat sink. For short bursts, hitting this current is just fine.

Here are some screenshots of where to find these values in the datasheet:

Notice in this next image I've crossed out all of the 2N3903 hFE lines so they don't distract us from the 2N3904 entries, which are for the transistor we care about in this example. Choose the lowest hFE value as the gain you will use in your estimates in order to have a "conservative" estimate, virtually guaranteed to fully turn on your transistor in all cases (ie: for all Collector current values you might like to switch on and off).

Now, let's calculate a Base resistor value for an NPN BJT transistor, assuming your goal is to fully turn on (saturate the Base-Emitter channel of) the transistor:
VBE(sat) has a diodic voltage drop of 0.65 to 0.95V, so your resistor would have to burn off 5 - 0.95 = 4.05V to 5 - 0.65 = 4.35V. Let's just use the lower 4.05V value so we will size for higher currents and faster turn-on speeds.
Your minimum hFE (gain) value for the 2N3904 transistor (not the 2N3903) is 30. Maximum continuous Collector current, Ic is 200mA, so let's increase that by a factor of 2 to 4 and size for 200mA * 3 = 600mA to 1) more fully saturate the Base to Emitter channel and get closer to full turn on under all cases, 2) get faster turn-on, and 3) overcome the fact that decreased gain occurs at higher Collector currents. In Figure 15. DC Current Gain, from the datasheet, for instance, shown below, it shows that the normalized gain decreases from ~0.28 at 100mA Collector current to ~0.13 at 200mA Collector current, which means that the gain of 30 found in the datasheet at 100mA Collector current indicates the gain at 200mA Collector current will actually be approximately 30 gain/(0.28/0.13) = 13.9 gain. Simply multiplying the Collector current we are sizing for by a factor of 2 to 4 (3 in our case) accounts for this fact, so we will use 600mA instead of 200mA in our maximum Collector current calculations below.

So, 600mA / 30 gain = 20mA Base to Emitter to get rock solid turn-on performance. Arduino can do up to 40mA per pin so this is Ok. Note that I recommend 30mA max per Arduino pin (for the ATmega328 microcontroller), and there is also a combined output limit for the ATmega328 microcontroller of 200mA for all pins combined, which you should keep in mind. I describe this on my website in my article "Arduino Power, Current, and Voltage Limitations" here.
V = IR, so R = V/I, so resistor, R that we need = 4.05V/0.020A = 202.5 Ohms. This is the minimum recommended base resistor size. Don't go too much smaller than 200 Ohms, if you go smaller than that at all. A 100 Ohm resistor, for instance, would allow a maximum base current of I = V/R = (I intentionally use the higher voltage value here) 4.35V/100 Ohms = 43.5mA, which could damage your pin.
Don't go larger than 600 Ohms or else you risk not turning on the transistor fully by not saturating the Base to Emitter channel. A 600 Ohm resistor would give you a guaranteed max Base to Emitter current of I = V/R = (I intentionally use the smaller voltage value here) 4.05V/600 Ohms = 6.75mA, which with a gain of 30 would give you a max Collector current (based on your relay coil resistance now) of 6.75mA * 30 gain = 202.5 mA. However, as indicated from Figure 15 shown above, a more realistic gain at 200mA Collector current might be only 13.9, which means your maximum allowed Collector current with a 600 Ohm resistor would be 6.75mA * 13.9 gain = 93.8mA. But, at this current your gain would actually be > 30, not 13.9, which leads back to the 200mA Collector current number. You can see this is a juggling game of numbers since the gain is NOT constant NOR linear, but rather is a function of Collector current, as shown by Figure 15 above. So, perhaps your actual maximum allowed Collector current with a resistor of 600 Ohms would be more like 130mA or something. The point is: any larger of a base resistor than 600 Ohms and you most likely won't be able to achieve the transistor's rated maximum continuous Collector current even if you wanted to. So, there's a reasonable R value range!: 200 Ohms to 600 Ohms, perhaps even leaning more towards the 200 Ohms side if you expect to have high momentary Collector currents anywhere near your maximum continuous Collector current rating of 200mA.

Additional notes on high-side vs low-side driving with NPN BJT or N-Channel MOSFET transistors, for clarity:
An NPN transistor can switch high-side voltages too--you just have to drive the necessary Base to Emitter current is all (and don't exceed any maximum ratings)! That's it! So...if you try to drive the high side, think about it: you turn it on with 5V so your voltage from Collector to GND can't exceed ~5V now because as current starts to flow through the collector, voltage would come up on the Emitter side until your base current no longer flows. Your system would be fighting itself. Even if you gave it 12V before the Collector you'd never see more than ~5V at the Emitter, assuming your Base drive voltage was 5V. If you can design around it, go for it, but generally the "easy" or "normal" way to do things is to use NPN to switch low-side voltages and PNP to switch high-side voltages.
The same goes for N-channel and P-channel MOSFETS. Use N-channel to switch low-side voltages and P-channel to switch high-side voltages, UNLESS you are doing some fancy driving (again), of N-channel to switch high-side voltages, as N-channel MOSFETs are more efficient and can switch higher currents than their equivalent P-channel pairs, due to some electron hardware mumbo jumbo stuff.
Keywords: transistor sizing; BJT transistor circuit calculations, equations, and datasheet; arduino and electrical engineering: transistor (BJT) sizing, equations, datasheet, and calculations example


How send method POST with JSON? Arduino UNO R3 + SIM900 Why is the server side of php not loading any data from arduino? What did I do wrong?

  String reading="{\"latitude\": 12.983027,  \"longitude\": 80.2594}";
  mySerial.println("AT+HTTPINIT");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"CID\",1");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"URL\",\"http://gerro.usermd.net/updateData.php\"");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"CONTENT\", \"application/json\"");
  toSerial(1000);

  mySerial.println("AT+HTTPDATA=" + String(reading.length()) + ",100000");
  toSerial(5000);

  mySerial.println(reading);
  toSerial(1000);

  mySerial.println("AT+HTTPACTION=1");
  toSerial(15000);

  mySerial.println("AT+HTTPREAD");
  toSerial(1000);

  mySerial.println("AT+HTTPTERM");
  toSerial(500);

Result:

AT+HTTPINIT

OK
AT+HTTPPARA="CID",1

OK
AT+HTTPPARA="URL","http://gerro.usermd.net/updateData.php"

OAT+HTTPPARA="CONTENT", "application/json"

OK
AT+HTTPDATA=46,100000

DOWNLOAD

OK
AT+HTTPACTION=1

OK

+HTTPACTION:1,200,55
AT+HTTPREAD

+HTTPREAD:55
array(0) {
}
array(0) {
}
nic ciekAT+HTTPTERM

OK

EDITING

void toSerial(int delay_ms)
  {
    delay(delay_ms);

    while(mySerial.available())
    {
       Serial.write(mySerial.read());
    }
  }

PHP

<?php
var_dump($_POST);
if (isset($_POST['latitude']) && isset($_POST['longitude']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
//code
} else {
echo 'nic';
}

You had to change the php file:

var_dump($_POST);

to:

echo print_r(json_decode(file_get_contents("php://input")));

Thank you !


Simple ESP32 MCP2515 CAN code to VP230 I have a working code that uses MCP2515 CAN module. Wanted to minimize the size of required modules, so I went with VP230 CAN transceiver and I'm having trouble relaying the same data through different libraries. All it has to do is log in with the first ''payload1'' and send voltage instruction with ''setdefaultvolt''. Any help is greatly appreciated.

MCP2515 code:

#include <mcp_can.h>
#include <mcp_can_dfs.h>
#include <SPI.h>
#include <Wire.h>

//pins:
#define CAN_INT 17                                                                         // Set INT to pin 2
MCP_CAN CAN(5);                                                                         // Set CS to pin 4 (D2)

void setup()
{
  Serial.begin(115200);
  delay(100);
  pinMode(17, INPUT);                                                                       //Setting pin 2 for /INT input

START_INIT:
  if(CAN_OK == CAN.begin(MCP_ANY, CAN_125KBPS, MCP_8MHZ))
  {
  }
  else
  {
    delay(100);
    goto START_INIT;
  }
  CAN.setMode(MCP_NORMAL);                                                        //set operation mode to normal so the MCP2515 sends acks to received data.
  unsigned char payload1[8] = {0x16, 0x50, 0x71, 0x07, 0x97, 0x089, 0x00, 0x00};  //login data with serial number
  CAN.sendMsgBuf(0x05004804, 1, 8, payload1);                                     //send login data

  unsigned char setdefaultvolt[5] = {0x29, 0x15, 0x00, 0xFE, 0x10};              //this is the command for setting the default output voltage (Last two bytes, LSB first). 16 80 is the maximum voltage of 57.6 V
  CAN.sendMsgBuf(0x05019C00, 1, 5, setdefaultvolt);                              //send setup data
}

void loop()
{
}

VP230 code:

#include <CAN_config.h>
#include <ESP32CAN.h>

CAN_device_t CAN_cfg;

#include <SPI.h>
#include <Wire.h>

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

  CAN_cfg.speed=CAN_SPEED_1000KBPS;
  CAN_cfg.tx_pin_id = GPIO_NUM_19;
  CAN_cfg.rx_pin_id = GPIO_NUM_23;

  CAN_frame_t my_frame;
  CAN_frame_t my_frame2;

  ESP32Can.CANInit();

  my_frame.FIR.B.FF = CAN_frame_ext;
  my_frame.MsgID = 0x05004804;
  my_frame.FIR.B.DLC = 8;

  my_frame.data = {0x16, 0x50, 0x71, 0x07, 0x97, 0x089, 0x00, 0x00};

  ESP32Can.CANWriteFrame(&my_frame);

  my_frame.FIR.B.FF = CAN_frame_ext;
  my_frame.MsgID = 0x05019C00;
  my_frame.FIR.B.DLC = 5;

  my_frame2.data = {0x29, 0x15, 0x00, 0xFE, 0x10};

  ESP32Can.CANWriteFrame(&my_frame2);

}

void loop()
{
}

Just spotted this, but if any one else finds it: You have one CAN speed set to 125kb on MCP2515 the other to 100kb on the VP230.
That's why you won't get anything!
Mark


Why is there a plastic sleeve on my HC-05 bluetooth module I would like want to know why the bluetooth module has a plastic sleeve covering it?

Is it possible to remove it?

It is to protect it. You should keep it so that the modules lasts longer.

If you remove it, just don't do anything stupid.


Variable updated in ISR is miscounting I'm using a timer to fire a interrupt in configurable time periods.
In that ISR, a pin is toggled, and a uint32_t variable is incremented.

In the main program, a while loop waits until that variable has reached a certain threshold - to then disable the timer via its clock source selection.

while(stepcounter <= threshold) {
}
disablecounter();

Sometimes - depending on optimization level, whether I put a small delay in the while loop, etc., this check seems to fail - advancing to disablecounter() even though stepcounter has not reached threshold.

If I stack the while loop like this:

while(stepcounter <= threshold) {
}
while(stepcounter <= threshold) {
}
disablecounter();

it runs just fine. This also works:

while(stepcounter <= threshold) {
  while(stepcounter <= threshold) {
  }
}
disablecounter();

I'm assuming there's some odd behaviour when comparing rapidly changing 32-bit numbers against a threshold.
This issue also occurs when using a uint16_t for stepcounter, but after a higher number of cycles.

For analysis, I'm simply running this loop over and over again; setting stepcounter back to 0 and restarting the timer. With uint32_t, it usually fails after the 5th or so loop. For uint16_t, it fails after around 25 loops.

Using a tempstepcounter like this also seems to work, but only when comparing against both counters at the same time:

while(tempstepcounter <= threshold || stepcounter <= threshold) {
  tempstepcounter = stepcounter;
}
disablecounter();

Any ideas on this? It this because 32-bit numbers take longer to read from the registers than the time from ISR to ISR?
ISR frequency should be around 32 kHz during this.

ISR code:

ISR(TIMER1_COMPA_vect) {
  PORTF ^= (1 << PORTF0));
  stepcounter++;
}

You need to declare it volatile in both places and shut off interrupts while reading it. The mainline  has to read it byte-by-byte, and an interrupt could otherwise occur between any two byte-reads, rendering the result of the 4-byte read as garbage.

'volatile' informs the compiler that the variable might not contain what it did last time (which the compiler might otherwise expect if the code being compiled doesn't change it. Turning off the interrupts protects the variable being changed while it's being read.

An even better way to protect the reads than turning off interrupts, is for the ISR to update the counter, then set a single-byte flag to indicate that there's a new count. The mainline would monitor that flag and read the counter only when the flag gets set, then clear the flag. This can work as long as the mainline checks the flag frequently enough that it will never not notice the flag until just before the next update by the ISR. But if you can keep to that constraint, this is a better idea than turning off interrupts.

If too many sub-tasks resort to turning off interrupts, it can have a negative effect on response time or even cause missed interrupts in some cases. This is less likely to be a problem for the relatively simple programs most of us write and run, most of the time. But when you get to tracking and controlling more complex processes and make heavier use of the interrupt system, bad habits have a way of coming back to bite you.


ESP8266 + HC-05 on same arduino I'm absolutely new to arduino, so please excuse me if this is a noob question.
I want to use a ESP8266 esp-03 Wifi module with a HC-05 bluetooth module together with my arduino uno.
Unfortunately both use the TX and RX pins on the board.
Is there a way to use both, the wifi and the bluetooth modules?
Or do I have to purchase a wifi board?

You can (just about) use any combination of two of:

Serial to PC,
HC-05
ESP-03

You have, basically, a hardware UART (pins 0/1), and a software UART (any pins of your choice).

Only the hardware UART can be used for communication with the PC, and you can only reliably use one instance of SoftwareSerial.

So, you could:

Use Serial to the PC (0/1) and HC-05 (SoftwareSerial, your choice of pins), or
Use Serial to the PC (0/1) and ESP-03 (SoftwareSerial, your choice of pins), or
Hardware Serial for ESP-03 (0/1) and SoftwareSerial for HC-05 (your choice of pins), or
Hardware Serial for HC-05 (0/1) and SoftwareSerial for ESP-03 (your choice of pins)

If you want anything more complex than that then you need to use a board with more than one hardware Serial port (such as a Mega2560).


RF network using Arduino I am working on home automation project. A network consists of one master device and many (maybe 10-20) slave devices, all communicating via these RF modules. I am using arduino in slave devices. Master will be based on raspberry Pi (most probably). Slave nodes can be sensors or switches(to control household electronics). To and fro communication will include data such as : a) Turn off bulb 1, b) Turn on TV, c) Set the bulb brightness to 34%, d) Temperature reading is 23 degree Celsius etc.

From security point of view, imagine there are similar other networks in the range and one network must not interfere with another. As such, I need to implement some sort of authentication whenever each data transfer takes place between master <---> slave. What logic do you suggest for this process?

There can be cases when data has not been received successfully by the receiving end. In such cases, I am planning to use some sort of checksum and acknowledgement system. If acknowledgement is not received, data will be resend in time intervals of 1s, 5s, 10s, 30s, 30s. If these 5 resends fail, the slave/master will be considered as unavailable/powered down. Your opinions/suggestions on this?

Slave arduino will be busy controlling appliances/sensors connected to it (real busy when controlling appliances). As such, it won't have much time for communication. Less time required for communication == Awesome. How much time do you think the arduino will take to complete one such data transfer?

Another solution I could think of was using two arduinos connected via i2c in each slave module. One arduino will be busy controlling the lights/sensors. Other one will take care of RF communication. If it receives some valuable info which was meant for this particular module, it will transfer the same to the other one using i2c bus. Is this a feasible backup plan?

Am I doing wrong by selecting RF modules for this purpose? Should I switch to Zigbees?

Thanks guys for reading. Any constructive suggestions from your side will be very helpful.

The NRF24s are great, but limited to communication only.

Digi's XBee 2mW module has got great indoor range, but more to the point it's got 8 I/O lines and 6 10-bit ADCs on board. It's also built for mesh networks (or you can get star-network equivalents) and has security encryption to boot. This means that, for some of your nodes, you don't need any other hardware to have a fully functioning control point (not including relays and sensors of course), so you can ditch having arduinos at every node.

They're so easy to use, very low power, and have plenty of support and documentation available online.

Do it!


Common ground serial communication trouble SIM800L I have a trouble when i'm using SIM800L module with common ground with combinaison with : FTDI232+ARDUINO PRO and Li-po battery. I use common ground to allow Arduino see the serial of SIM800L.

I use battery (lipo) to power the SIM800L to allow 2A peak current.

Serial work but sometime the module reset(i think) and i see strange character. The SIM800L no work correctly.

I meet the same trouble when i use the FTDI's VCC, every time I use the common ground i have this problem.

Look the gif you can see the problem :

I'm using this wiring

It's strange because when i connect the SIM800L directly with FTDI232 i have no problem all work fine.

I use this code to debug the Serial communication :

#include <SoftwareSerial.h>
SoftwareSerial serialSIM800(RX,TX)
[..]
//On Setup
 Serial.begin(115200);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(115200);
  delay(1000);
  serialSIM800.print("AT\r");
  //[..]
void loop(){

 if (serialSIM800.available())
     Serial.write(serialSIM800.read());

 if (Serial.available()) {
    while(Serial.available()){
      Serial.print(">");
      char test=Serial.read();
      Serial.print(test);
      Serial.println();
      serialSIM800.write(test);
 }

There are a few things that escape me that's why I need your lights, thanks by advance.
Regards

I finally fixed my issue.
I disable the auto baud rate of SIM800L trough FTDI232, with these at commands:

AT + IPR = 9600
AT & W

AT + IPR: Fix the baud rate at 9600
AT & W: Save in SIM800L

Then when i use with SoftwareSerial i have no issue anymore. When i reset the module with short connect RST with GND i have a good reply from SIM800L :

RDY

+CFUN: 1

+CPIN: READY

Call Ready

SMS Ready

Thanks for your help.

Note : And be sure you are a good power supply and good wire.


Exit status 1 expected primary-expression before ']' Arduino Here's the whole error:

 Arduino: 1.6.7 (Windows 7), Board: "Arduino/Genuino Uno"

 *\readMifare\readMifare.ino: In function 'void loop()':

 readMifare:113: error: expected primary-expression before ']' token

    if (uid[] == { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

            ^

 readMifare:113: error: expected primary-expression before '{' token

    if (uid[] == { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

                 ^

 readMifare:113: error: expected ')' before '{' token

 readMifare:121: error: expected '}' at end of input

    }

    ^

 exit status 1
 expected primary-expression before ']' token

   This report would have more information with
   "Show verbose output during compilation"
   enabled in File > Preferences.

Here's the code

 #include <Wire.h>
 #include <SPI.h>
 #include <Adafruit_PN532.h>

 // If using the breakout with SPI, define the pins for SPI communication.
 #define PN532_SCK  (2)
 #define PN532_MOSI (3)
 #define PN532_SS   (4)
 #define PN532_MISO (5)
 // If using the breakout or shield with I2C, define just the pins connected
 // to the IRQ and reset lines.  Use the values below (2, 3) for the shield!
 #define PN532_IRQ   (2)
 #define PN532_RESET (3)  // Not connected by default on the NFC Shield

 // Uncomment just _one_ line below depending on how your breakout or shield
 // is connected to the Arduino:

 // Use this line for a breakout with a software SPI connection (recommended):
 Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

 // Use this line for a breakout with a hardware SPI connection.  Note that
 // the PN532 SCK, MOSI, and MISO pins need to be connected to the Arduino's
 // hardware SPI SCK, MOSI, and MISO pins.  On an Arduino Uno these are
 // SCK = 13, MOSI = 11, MISO = 12.  The SS line can be any digital IO pin.
 //Adafruit_PN532 nfc(PN532_SS);

 // Or use this line for a breakout or shield with an I2C connection:
 //Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

 #if defined(ARDUINO_ARCH_SAMD)
 // for Zero, output on USB Serial console, remove line below if using      programming port to program the Zero!
 // also change #define in Adafruit_PN532.cpp library file
 #define Serial SerialUSB
 #endif
 #include <Servo.h>

 Servo servo1;

 void setup(void) {
   #ifndef ESP8266
   while (!Serial); // for Leonardo/Micro/Zero
   #endif
   Serial.begin(115200);
   Serial.println("Hello!");

   nfc.begin();

   uint32_t versiondata = nfc.getFirmwareVersion();
   if (! versiondata) {
     Serial.print("Didn't find PN53x board");
     while (1); // halt
   }
   // Got ok data, print it out!
   Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
   Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
   Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

   // configure board to read RFID tags
   nfc.SAMConfig();

   Serial.println("Waiting for an ISO14443A Card ...");
   servo1.attach(9);
 }

 void loop(void) {
   uint8_t success;
   uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
   uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

   // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
   // 'uid' will be populated with the UID, and uidLength will indicate
   // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
   success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

   if (uid[] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

      int position;
      for(position = 0; position < 180; position += 2){
       servo1.write(position);
       delay(20);
      }

   }

Please note that I'm using an example from the Adafruit official PN532 library examples and trying to edit it.

I wouldn't use strncmp because the UID might have zeroes in it. This looks safer:

   uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
   uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

   const uint8_t wantedUid [] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 };

   // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
   // 'uid' will be populated with the UID, and uidLength will indicate
   // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
   success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

   if (success &&
      uidLength == sizeof (wantedUid) &&
      memcmp (uid, wantedUid, sizeof wantedUid) == 0) {
      ...

I threw in a test for the uidLength being the expected size, otherwise you might find a 4-byte card happens to match the first four bytes of the wanted UID.

memcmp compares a block of memory for the number of bytes you specify. It returns zero on a match.


Multiple I2C devices on Arduino I'm design a custom PCB based around the Arduino Zero/Adafruit Feather M0. The plan is to use a few I2C devices. I just had a few questions about whether I've designed the board correctly.

You'll see that I've used 10k resistors on each devices's SDA and SCL lines, but is this necessary? I've seen it mentioned on a few online documents for certain breakout boards etc...

Also, are the devices just connected in parallel? Are there any considerations I need to make when using 3 I2C devices like this?

You'll see that I've used 10k resistors on each devices's SDA and SCL lines, but is this necessary? I've seen it mentioned on a few online documents for certain breakout boards etc...

You should have just two 3.3K resistors - one on the SDA and one on the SCL lines.  However all your 10K resistors in parallel will equate to about the same thing - just taking up 3x the space.

  Also, are the devices just connected in parallel?

Yes, it's a simple multi-drop bus.

  Are there any considerations I need to make when using 3 I2C devices like this?

Not really, no.  The frequencies in use are generally too low to require any specific layout considerations. Just try to keep vias to a minimum and don't snake the traces around the board too far.


Keypad giving random inputs I have a keypad like this:
here is another, closer look at the bottom part.
Basically, I want the LED to power the amount that I pressed.
this is my code:
int LED = 1;
int inputs[4] {
  6,
  4,
  2,
  0
};
int outputs[4] {
  13,
  12,
  10,
  8
};
void outputAllBut(short int);
int numberInputCheck();
int inputCheck();

void setup() {
  for (int i = 0; i < 4; i++) {
    pinMode(outputs[i], OUTPUT);
    pinMode(inputs[i], INPUT_PULLUP);
  }
  pinMode(LED, OUTPUT);
}

void loop() {
  while (true) {
    int x = numberInputCheck();

    if (x == 500) {
      break;
    }

    delay(500);

    for (int i = 0; i < x; i++) {
      digitalWrite(LED, HIGH);
      delay(500);
      digitalWrite(LED, LOW);
      delay(300);
    }
  }
}

int numberInputCheck() {
  while (true) {
    for (int i = 0; i < 4; i++) {
      outputAllBut(i);
      for (int m = 0; m < 4; m++) {
        if (digitalRead(inputs[m]) == LOW) {
          switch (i) {
          case 0:
            if (m == 3) {
              return 500;
            } else {
              return m + 7;
            }
          case 1:
            if (m == 3) {
              return 500;
            } else {
              return m + 4;
            }
          case 2:
            if (m == 3) {
              return 500;
            } else {
              return m + 1;
            }
          case 3:
            return 500;
          }
        }
      }
    }
  }
}

void outputAllBut(short int b) {
  for (int i = 0; i < 4; i++) {
    if (i != b) {
      digitalWrite(outputs[i], HIGH);
    }
  }
}

int inputCheck() {
  for (int i = 0; i < 4; i++) {
    if (digitalRead(inputs[i]) == LOW) {
      return i;
    }
  }
  return 5;
}

for reference, the numberInputCheck function is the one that might go wrong here, I want it to wait for an input and return the number that I pressed. i is the rows and m is the columns.
My problem is that whenever I press the keypad at one of the numbers, it will give me a random amount of times that the LED turns on, there doesn't seem to be any pattern.
m+1, m+4 & m+7 is because m is my columns so if I press 0 and the row is 0 then I add 1, same goes with everything else. Can anyone help me?

Your outputAllBut function is wrong. It turns all but the specified output high, but it doesn't turn the specified output low. As a result, after calling it multiple times, you end up with all of the outputs high forever (since you don't have code anywhere else that would turn them off), so it's just a question of timing which one it considered "on" any time you press a button.

Side note: toggling the outputs between low and high to do the matrix read is dangerous, as pressing multiple buttons at a time can cause a short circuit that way. You should instead always keep all of them low, and control which one is active by setting it to output mode and the rest to input mode.


To what extent is Javascript used in robots? I originally discouraged my friend against the use of Javascript in his robot project because I didn't know any use for Javascript outside of web developement but then I saw this book on amazon. Since I wouldn't want to mislead him could someone help me develop a better understanding of how often Javascript is used when making robots with an Arduino?

It wouldn't be my first choice for programming of robotics, but it's certainly doable.

Thanks to NodeJS, JavaScript (or ECMAScript as it is properly known) has broken free of the browser and is now a general programming language.

Thanks to the BeagleBone Black (and others), which runs most of its systems by default through NodeJS, including its web-based IDE, you can program the whole board with ECMAScript.

So yes, you can do robotics with ECMAScript, and there are platforms which do allow you to do robotics with ECMAScript.

Would you want to do it in a real industrial environment?

As I said - it wouldn't be my first choice.


ADC with better performance I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do). So I am in need of an Analog-to-Digital Converter(ADC) which has a very high sampling rate (sampling rate has to be constant and known), can be interfaced with Arduino Mega or Raspberry Pi and noise should be neligible to minimum level of voltage magnitude that it can count. Can anyone suggests me with any ADC that follows these characteristics?

I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do).

10Ksps and 12bit-resolution adcs are fairly common for onboard ADC. you should be able to find lots of mcus that have adc modules that can do that.

even for an external adc, that's not difficult at all. because of the speed, you are likely looking at a spi adc module.

precision is another matter.


Interface Processing with Arduino to operate a servo by MouseX I want to make a servo change its angle using my mouse. When I move mouse horizontally the servo should change its angle correspondingly.
This is the sketch I wrote, unfortunately the servo doesn't move one bit. HELP.

Processing Code:

import processing.serial.*;
Serial port;
void setup() {
  size(256, 150);
  println("Available serial ports:");
  // if using Processing 2.1 or later, use Serial.printArray()
  println(Serial.list());
  port = new Serial(this, Serial.list()[1], 9600);
}

void draw() {
  // draw a gradient from black to white
  for (int i = 0; i < 256; i++) {
    stroke(i);
    line(i, 0, i, height);
  }
  // write the current X-position of the mouse to the serial port as
  // a single byte
  port.write(mouseX);
  println(mouseX);
}

Arduino Code:

#include <Servo.h>
Servo myservo;
void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
  // initialize the servo:
  myservo.attach(10);
}
void loop() {
  byte pos;
  // check if data has been sent from the computer:
  if (Serial.available()) {
    // read the most recent byte (which will be from 0 to 255):
    pos = Serial.read();
    // set the angle of the servo:
    myservo.write(map(pos, 0, 255, 0, 180));
  }
}

When you try and solve a problem you want to focus on just one part at a time.  If I have understood what you are doing correctly then you are trying to:

Get a computer to talk to an Arduino over serial
Get an Arduino to position a servo
Get an Arduino to decode information sent by the computer
Get the computer to code the information
Get the computer to draw graphics.

You can try and ice a cake, feed a baby, talk on you mobile and drive a truck all at the same time, it doesn't mean its a good idea.  When you crash what was the cause?  You haven't got a clue, you were too busy trying to do all that not analyse what is happening at the same time.

So, what I'm trying to say is break it down.  Normally with motors the problem is related to power, people assume that the Arduino can provide enough power for a servo, that's not always the case.

I would:

Write a program that sets the servo to 10 hard coded positions.
Write a program that sets the servo to the position manually entered on the command line.
Write a program that draws the gradient, interprets the user entry and writes the command to be sent to the Arduino to the command line.
Write a program that runs on the Arduino and echoes what it receives over the serial line to some "other output mechanism"  (Connecting the computer via SoftwareSerial might be a good idea).

And once they are all working as you expect connect them all together and it will all magically work :)

(Sorry if I'm teaching you to suck eggs, if you have already done all this ignore me)


Why does starting the serial monitor restart the sketch? If I upload any sketch that sends serial data, I immediately see the TX/RX LEDs flash once the sketch is uploaded. If I then start the serial monitor, the sketch appears to restart.

A bare minimum sketch that shows this behaviour:

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

void loop()
{
  Serial.println("Loop");
  delay(1000);
}

Tested with several boards and Mac and Windows versions of the IDE.

Example output - it goes back to "Setup" when I open the serial monitor:

Why is this?

The Arduino uses the RTS (Request To Send) (and I think DTR (Data Terminal Ready)) signals to auto-reset. If you get a serial terminal that allows you to change the flow control settings you can change this functionality.

The Arduino terminal doesn't give you a lot of options and that's the default. Others will allow you to configure a lot more. Setting the flow control to none will allow you to connect/disconnect from the serial without resetting your board. it's quite useful for debugging when you want to be able to just plug in the connector and see the output without having to start the sketch over.

Another way to disable the auto reset is to put a pull up resistor on the reset pin.

Disabling Auto Reset On Serial Connection


Connecting a servo motor to an Arduino I currently have a push solenoid connected to my standard Arduino board. The Arduino is powered via its USB cable, while the solenoid is powered using a 12V Huawei adapter (in conjunction with a MOSFET driver module).

How can I switch out the push solenoid for a servo motor? The operational voltage of the servo is 4.8 to 7.2V (with a stall torque of 13 kg-cm) to give you an idea of its size. I have been told to buy a DC-DC step-down module (to adjust the Huawei supply from 12V down to 5V) but I think it could be easier to power the servo using some sort of USB?

Or other suggestions are welcome. I want the easiest solution (since I am NOT tech savvy) and I can't buy parts until I am for certain the solution will work (that's research for you). Thanks!

You will have to check in the servos datasheet for the maximal current, that it draws (motors draw more current, when inhibited by mechanical force, so be sure to get the maximal current from the datasheet). From the data, that you gave us, I think it will draw rather much current. So you should not power it over the USB port of your PC (which gives 500mA at maximum). Also you should not use the 5V pin of your Arduino, or you may fry components like the diode, that lies in the current path from USB to 5V pin.

For your step down module, you will also have to check, if it can provide the current, that the servo needs, or you may kill it. If you want to use USB, you can use a standard USB charger or powerbank. Often these can provide more than 1A (depending on the actual product). Most USB wallwart chargers have a current specification on them. But (as said earlier) don't provide the power through the Arduino. Provide it directly from the source, so that the possibly high current for the servo does not have to pass trough the Arduino. You can also power the Arduino with the same source in parallel to the servo, so that you don't need two sources or a converter.

For more info, you will have to provide more information about the servo


Arduino YUN real time control I have a very specific problem, exactly with real time control. For example I try to write an application where I can edit min or max temperature that after reaching it , I will receive SMS with message. I'm wondering how to edit variables "on-the-fly" because, as I know Arduino IDE use it own libraries not this from C/C++, and I don't know how to get to SD card in Arduino too. Can someone help ?

Thanks

the SD card is at /mnt/sd/ . you should consider reading the yun tutorials here before going further, the ability to send and receive data is at the heart of the yun design.


When setting hardware timers as interrupts, should I prefer a lower prescaler value or a lower CTC? I'm currently playing with Arduino's hardware timers, and a question came to my mind. Let me explain it a bit.

Let's suppose I want a certain function to execute every 1024 clock ticks. AFAIK, I could achieve this in several ways, playing with the prescaler value for Timer2, and its CTC:

Setting the prescaler to 1 and the CTC to 1024
Setting the prescaler to 8 and the CTC to 128
...
Setting the prescaler to 1024 and the CTC to 1.

All these ways would achieve what I want, but, which one is more efficient? Or it doesn't matter at all?

Thanks in advance for sharing your knowledge :P

If 'clock tick' count (here 1024), timer width and  MCU clock used are constant (a fixed value), I would not go for last option i.e. prescalar 1024 and CTC of 1. Here are my reasons (specially for Arduino )

1) When CTC is close to zero ( like 1-> 10), sometimes timer behaves as if count is zero and outputs a square wave (with 50% duty ratio) with half the demanded frequency. So make CTC reasonably big. But again selecting a high clock frequency (pre scalar 1) may also show reduced accuracy. A intermediate option I think is better.

2) When count CTC changes dynamically in a process, timer pre scalar should be selected such that CTC count will always be less than or equal to timer width over whole process.

i.e. the maximum 'timer tick count' should be comfortably accommodated by the timer with it's given width. Even here same dilemma again occurs, then selection based on point 1 is better.

If this is not enough, then only way I think is to implement each case  physically and check which combination gives you the best results. Practical results I think are more reliable ( may be you will get a board specific efficient combination!)


Arduino Gesture Sensor error:No such file or directory I cloned https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor
and copied the libraries into the Arduino libraries folder. I then launched Arduino and selected the example. I opened the file GestureTest and when I started upload I received this error:

GestureTest.ino:49:31: fatal error: SparkFun_APDS9960.h: No such file or directory
compilation terminated.

I checked the SparkFun_APDS9960.h and I found it in the Gesture_Sensor/Libraries/src folder.
Is there a solution to resolve this error?

SparkFun made a poor choice for the folder structure of that repository. Likely this has caused you to incorrectly install the library. Please follow these instructions:

Download the latest release from https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor/releases. Currently it is https://github.com/sparkfun/APDS-9960_RGB_and_Gesture_Sensor/archive/V_H1.0_L1.4.2.zip.
Unzip the downloaded file.
Rename the folder APDS-9960_RGB_and_Gesture_Sensor-V_H1.0_L1.4.2/Libraries/Arduino to SparkFun_APDS9960. This is not absolutely necessary but "Arduino" is not a very descriptive name for a library folder and the Arduino IDE works best when the library folder name matches the primary header file name so this is best practices.
Copy the SparkFun_APDS9960 folder to {sketchbook folder}/libraries. You can find the location of the sketchbook folder at File > Preferences > Sketchbook location.
Restart the Arduino IDE if it's running (not necessary with recent versions of the Arduino IDE).

Note that the folder structure of this library requires Arduino 1.6.x or newer.

UPDATE: I submitted a pull request to put the library in an appropriately named folder. This won't change the instructions above until the next release but it does remove the need to rename the folder if you are cloning the repository or downloading from the tip of the repository rather than a release.


Sending arduino signal to another arduino I'm working on a project which consists of 2 different function. since the arduino only can do 1 function so i decide to use 2 arduino instead. my idea is 1st arduino will give a output and the sketch on the 2nd arduino will run Only after the input given from the 1st arduino. So can i make a digital output which will be send to the input of 2nd arduino?

if it could be, i already make a code for the 2nd arduino which will be run after there was an input from the 1t arduino:

//define the input/output pins
#define FLOAT_SWITCH_PIN 2
#define PUMP_1_PIN 4
#define LED_PIN 7
#define output1starduino 3
//setup runs once
void setup()
{

  pinMode(FLOAT_SWITCH_PIN, INPUT_PULLUP);
  pinMode(output1starduino, INPUT_PULLUP);

  //setup output pins for relays/pumping station and LED board
  pinMode(PUMP_1_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);

}

//loop() runs indefinitely
void loop()
{

  if(digitalRead(output1starduino) == HIGH) // output from 1st arduino
  if(digitalRead(FLOAT_SWITCH_PIN) == LOW)
  {
     digitalWrite(PUMP_1_PIN, HIGH); //turn on the pump
     digitalWrite(LED_PIN, HIGH);    //turn on the LED
  }

  {
     digitalWrite(PUMP_1_PIN, LOW); //turn off the pump
     digitalWrite(LED_PIN, LOW);    //turn off the LED
  }
}

as i write on the line, the "output1starduino" which an digital output from the first arduino. Is this the right way for me to write if i want the program here to run only right after the output from 1st arduino given?

*** this is the code of first arduino which will be sent to the 2nd arduino

int motorPin = 3; // motor pengisian (m1)
int blinkPin = 4; //
int motor1 = 5;// motor pembuangan
int motorklorin = 6;// pam topap
int switch1 = 2;// switch float
int indicator1 = 7;
int indicator2 = 8;
int indicator3 = 9;
int output1starduino = 2;
void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(blinkPin, OUTPUT); // penujuk fasa pengisian
  pinMode(motor1, OUTPUT);
  pinMode(motorklorin, OUTPUT); // MOTOR UNTUK topap
  pinMode(switch1, INPUT_PULLUP);// PELAMPONG
  pinMode(indicator1, OUTPUT);// lampu penunjuk fasa pembuangan
  pinMode(indicator2, OUTPUT);// lampu penunjuk topap
  pinMode(indicator3, OUTPUT);// lampu menunggu
  pinMode(output1starduino, OUTPUT); // KELUARAN KE ARDUINO 2
}

void loop()

{
  digitalWrite(motorPin, HIGH); // turn on the motor
  digitalWrite(blinkPin, HIGH); // turn on the LED
  digitalWrite(motor1, HIGH);// on lampu
  digitalWrite(motorklorin,HIGH);
  delay(1000);        //

  digitalWrite(motorPin, HIGH);  //
  digitalWrite(blinkPin, HIGH);  // penunjuk fasa pembuangan hidup
  digitalWrite(motor1, LOW);// motor pembuangan jalan (air start turun/pembuangan
  digitalWrite(motorklorin,HIGH);
  delay(180000);        //tempoh pembuangan

  digitalWrite(motorPin, LOW); // turn on the motor (motorisi balik air jalan/pengisian
  digitalWrite(blinkPin, LOW); //
  digitalWrite(motor1, HIGH);// filling motor on
  digitalWrite(indicator1, HIGH); //indicator
  delay(150000);        // duration filling

  digitalWrite(motorPin, HIGH);  // turn off the motor
  digitalWrite(blinkPin,HIGH);  // turn off the LED
  digitalWrite(motor1, HIGH);//
  digitalWrite(output1starduino, HIGH);
  delay(100000);        // multiply by 60000 to translate minutes to milliseconds
  }

An arduino may not be as fast as a PC or phone, but it is VERY fast indeed (16,000,000 operations /sec). Unless the code for arduino #1 is incredibly complex, the one arduino should be able to do it all on its own.
P.S. Please post the code for Arduino #1


Managing 80 ~ 90 accelerometers with Arduino If one were to want to keep track of data from 80 - 90 accelerometers using arduino, what would be the best way to go about this challenge?

1) Use the I2C address select inputs as an "enable".  If you run out of I/Os before running out of bus time, drive the enables from an I/O expandander. If your accelerometers are SPI, drive or use the expander to drive the chip selects.

2) Use a tree of slave MCUs (Arduino or otherwise) reading a number of accelerometers, extracting and batching the useful data, and reporting only that upstream to a master.  Probably use whichever of I2C or SPI your accelerometers are not using (SPI can be much faster, so hopefully that).

Some accelerometer / gyro parts have an on-board processor which you may be able to program to do some of the data extraction for you.

You could also consider using an FPGA to collect the data.  A commonly available one with enough I/O pins to have a dedicated connection to each accelerometer (and so read them all in parallel) would probably also have the internal resources to implement an Arduino-class soft core processor, if not better.


Arduino Mega PWM pins stop working for LEDs once servo is attached? I can get LEDs to fade properly using PWM on pins 44-46 on the Mega2560 when I don't have a servo attached, but once I "attach" the servo in the code, then PWM pins 44-46 don't work for PWM. They can still work with digitalWrite, but not with analogWrite.

This is the code:

#include <Servo.h>
Servo myservo;
int led = 46;

void setup()  {
  myservo.attach(3);
  pinMode(led, OUTPUT);
  analogWrite(led, 60);
}

void loop()  {}

If I comment out the "myservo.attach(3);" line, then PWM works for the LED pin. Otherwise the LED stays off. Why would PWM on pins 44-46 stop working once the servo is attached?

Looks like the mega has some clever servo handling features. Servo control always uses a timer of some sort and can conflict with the pwm timer. The first 12 servos knock out pins 44,45,46 ...

  For Arduino Mega it is a bit more difficult. The timer needed depends on the number of servos. Each timer can handle 12 servos. For the first 12 servos timer 5 will be used (losing PWM on Pin 44,45,46). For 24 Servos timer 5 and 1 will be used (losing PWM on Pin 11,12,44,45,46).. For 36 servos timer 5, 1 and 3 will be used (losing PWM on Pin 2,3,5,11,12,44,45,46).. For 48 servos all 16bit timers 5,1,3 and 4 will be used (losing all PWM pins).


How to Serial read two consecutive chars sent by computer to Arduino? My program reads the input and plays the appropriate note for 500 milliseconds. If I type in 'a', tone(8, 440, 500) will be called. I now want to add different note lengths so that in the future, I can play songs by sending code to Arduino. I was thinking that if 'a' is typed in, the program checks the next character. If it's a 1, it's a whole note. If it's a 2, it's a half note. My code doesn't work. What is wrong with it?

    if(Serial.available()>0){
    char character=Serial.read();
    if(character=='a'){
    char leng=Serial.read();
    if(leng=='1'){
    tone(8, 440, 1000);
    delay(1000);
    }
    else if(leng=='2'){
    tone(8, 440, 500);
    delay(500);
    }

    }
    }

Presuming that code is the interior of loop(), your Arduino will spin until a character arrives, that is, until Serial.available()>0 becomes true.

It then reads the character with Serial.read() and if it's an 'a' immediately does another Serial.read().  In general, some delay occurs between characters arriving via a serial interface.  Whenever the serial buffer is empty, an immediate Serial.read() will return -1 instead of an ASCII character.

To fix this problem, test for availability of a character before doing the second read.  For example, you could add

while (!Serial.available()){}

before the read, to delay until a character is available.


How To Stop Linear Actuator? I wrote a code but the motor does not stop,  it keeps moving
can anyone send to a code that can I stop the motor after my code that shows bellow?

const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin

void setup() {

pinMode(forwards, OUTPUT);//set relay as an output
pinMode(backwards, OUTPUT);//set relay as an output

}

void loop() {

 digitalWrite(forwards, LOW);
 digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
 delay(20000); // wait 2 seconds

 digitalWrite(forwards, HIGH);
 digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
 delay(2000);// wait 2 seconds

 digitalWrite(forwards, HIGH);
 digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
 delay(20000);// wait 2 seconds

 digitalWrite(forwards, HIGH);
 digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
 delay(2000);// wait 2 seconds

}

There's multiple things you can do.  Here's some examples.

1: Move code out of loop() and intosetup():

const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output

    digitalWrite(forwards, LOW);
    digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
    delay(20000); // wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
    delay(20000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds
}

void loop() {
}

2: Stop loop() from looping:

const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output
}

void loop() {

    digitalWrite(forwards, LOW);
    digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
    delay(20000); // wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
    delay(20000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    while (1); // Stop here and do nothing forever
}

3: Set a "I have done it" flag:

const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin
bool complete = false;

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output
}

void loop() {
    if (!complete) {
        digitalWrite(forwards, LOW);
        digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
        delay(20000); // wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
        delay(20000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds

        complete = true;
    }
}

Each has benefits and drawbacks. Which is right for you depends on what you are actually trying to achieve.


Sending a floating point number from python to arduino I am trying to send a floating point number from a python script to an Arduino.  I am not sure how to do this, especially in a pythonic way.

A little bit of research brought me to this very similar question:
How to send numbers to Arduino UNO via Python 3 and the module serial
I vaguely understand why this would work for an int but don't know how to modify it.

1) In this question it makes sense to convert to a char, send, and then convert back to a int by casting on the Arduino, I can't think how to do that for a float.

2) Why do they convert to a Char anyway?

3) What code do I run on the arduino to get this back into a float?

4) Can I use bitwise operators on floating point numbers?

I'm new to python and also to low level programming. I am also aware that python and low level don't mix to well. I am using Linux but ideally I need a cross platform solution. Although I would prefer to get it working then worry about cross platform later.

Floating point numbers are (should) be stored in IEEE 754 format.

If you simply write the binary bytes of a floating point number down the serial line, it should be possible to unpack them at the other end.

To do this (Arduino C/C++), make a pointer from your variable, by casting the address of it to char*. Void* would probably work too.

 float my_value = 22.812;
 my_port.write((const char *)&my_value, sizeof(float)/*4*/);

And the unpacking - there's a few ways to do this, but I like:

 float incoming_value;
 unsigned char buffer[4];

 // If we read enough bytes, unpacked it
 if (my_serial.readBytes(buffer, sizeof(float)) == sizeof(float))
     memcpy(&incoming_value, buffer, sizeof(float));
 else
     // I/O error - no data, not enough bytes, etc.
     incoming_value = 0

On the other end (python), bytes are best handled with the struct module.  This will handle the packing and unpacking for you.

import struct
...

try:
    ieee754_data = my_serial.read(4)
    my_float = struct.unpack('f', ieee754_data)
catch:
    # I/O Error, or junk data
    my_float = 0.0

And packing:

 ieee754_data = struct.pack('f', my_float)
 try:
     my_serial.write(ieee754_data)
 catch:
     pass #TODO - I/O Error

One more note - You might consider using doubles instead of floats for extra precision.  Python floats have the precision of a C/C++ double already.


Why doesn't data return when I use Sim808 http request Why is it that when i use this code for http request on DFRobot_sim808 , I get 'fetch over' message, that means that no data is being returned?

char strings:

char http_cmd[] = " HTTP/1.0\r\n"
                        "Host: 5ac80719.ngrok.io\r\n"
                        "\r\n";
char first[] = "GET /index.php?lat=";

char requestion[100];

functions to join them:

void setup() {
  float lat = 32.685362, lon = 48.411512;
  char char_coor[10];

  mySerial.begin(9600);
  Serial.begin(9600);

// Set Http Cmd
  strcpy(requestion,first);
// For Convert latitude float to char
  dtostrf(lat, 4, 6, char_coor);
  strcat(requestion,char_coor);
// For Convert longitude float to char
  dtostrf(lon, 4, 6, char_coor);
  strcat(requestion,"&long=");
  strcat(requestion,char_coor);
  strcat(requestion,http_cmd);

.
.
.

and fetching:

sim808.send(requestion, strlen(requestion)-1);
  while (true) {
      int ret = sim808.recv(buffer, sizeof(buffer)-1);
      if (ret <= 0){
          Serial.println("fetch over...");
          break;
      }

/*
The program stops at above
*/

      buffer[ret] = '\0';
      Serial.print("Recv: ");
      Serial.print(ret);
      Serial.print(" bytes: ");
      Serial.println(buffer);
      break;
  }

thanks

One problem I can see is the while loop has a break statement in it that "exits" the while loop before printing the data. Removing that break and printing the data out where the break "was" may help. Here's an example of what I'm trying to say:

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

void loop(){

  while(true){
    int ret = 0;
    if(ret <= 0){
      Serial.println("fetch over...");
      // Print out the received data here...
      Serial.print("Recv: ");
      Serial.print(ret);
      break;
    }
  }

}


H11L1 opto isolator does not pass signal to Arduino (correctly) I have made a very basic test circuit for the opto coupler H11L1 ('similar'datasheet: http://www.datasheet4u.com/datasheet/H/1/1/H11L1_MotorolaInc.pdf.html))

I use the test circuit:

simulate this circuit – Schematic created using CircuitLab

The LED and 470 ohm resistor is only for testing.
U1 is the Arduino (software serial pin 9/11) and U2 is the H11L1.

The LED is flashing similar to the RX led on the Arduino.

Also I tested before in an even simpler circuit that the signals from the H11L1 pass through pin 4 (although inverted, which seems to be normal).

However, I don't receive any data in the Arduino (I tried different Arduinos, different speeds, different H11L1).

The data I receive from the (hardware) serial/debug terminal:

0
0
0
0

etc.

My sketch:

#include <SoftwareSerial.h>

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

void setup()
{
    Serial.begin(9600);
    mySerial.begin(300);
}

void loop()
{
    mySerial.write('A');
    while (mySerial.available())
    {
        Serial.println(mySerial.read());
    }

    delay(100);
}

How can I get the correct signal? (meaning 'A' are printed instead of 0's?

Update

New sketch (not having the duplex problem):

#include <SoftwareSerial.h>

SoftwareSerial mySerial(12, 13); // RX, TX

void setup()
{

  Serial.begin(115200);
  mySerial.begin(115200);
}

void loop()
{
  Serial.print("Write: A ");
  mySerial.write('A');

  while (mySerial.available())
  {
    Serial.print((int) mySerial.read());
  }

  Serial.println("");

  delay(100);
}

Output:

Write: A
Write: A
Write: A
Write: A

etc.

Update

Problem solved: I put it in an answer for clearity.

simulate this circuit – Schematic created using CircuitLab

I'm not sure I can help much with the MIDI problem but I can help with the schematic. I've reorganised it for clarity. Since the opto-isolator has an open-collector output any loads it is driving should be connected to supply + rather than common.


FTDI to HM-10(CC2541) serial command no response I'm trying to communicate with my HM-10 module though a FTDI converter on my mac. I have installed the FTDI driver and disabled the mac's default FTDI driver. This is my arduino IDE setup:
board: I tried Arduino Uno/ Arduino Pro mini(ATmega328 3.3V)
Port: /dev/cu.usbserial-50285BI
programmer: AVRISP MKII

I connect rx on MH-10 to txd on converter and tx on HM-10 to rxd on converter. 3.3Vcc and GND respectively. The HM-10 module is powered up but I can not find the beacon signal. When I send command from arduino IDE's serial monitor there was no response from the chip at all. The RX and TX leds on converter never lighted up either. My goal is just to setup a BLE beacon and change the UUID(may do more advanced programming in future) and have been struggled on this for couple of hours. please help me.

Thanks!

Ahhh...After few hours of struggling finally found the solution. The "HM-10" module I was using was a copycat module and "Both NL &CR" option should be chosen as a newline/carriage return character will be feed at end of the AT command. I found the solution from these two awesome articles:

Working with cheap bluetooth BTLE4 devices HM-10 BLE-CC41A

Comparing the HM10 and BLE CC41a Bluetooth

Hope this will be helpful for someone meet this problem in the future.


Why doesn't millis() use 1 µsec or 1 msec interrupt? Arduino millis() does not make use of one millisecond interrupt. Instead they make use of 1,024 µsec interrupts and manipulate. Any specific reason why this was implemented this way?

In one case, we can go for timer0 without prescaler and use 1 µsec interrupts. In such case, we have to use CTC mode with OCR0A=15. Inside ISR, we could update the microsecond counter and if it reaches 1,000, we could update the msec timer count. Otherwise we could go for directly 1 msec interrupt (maybe using timer0).

I wrote this code to get micros() and millis(). But there is some issue and I'm not able to get it working correctly.

#include <avr/io.h>
#include <avr/interrupt.h>

#ifndef F_CPU
#define F_CPU 16000000UL
#endif

volatile uint32_t oneMilliCounter;
volatile uint32_t oneMicroCounter;
extern void initializeTimer0CTC_Mode (void);

extern uint32_t millis(void);
extern uint32_t micros(void);

volatile uint32_t oneMilliCounter = 0;
volatile uint32_t oneMicroCounter = 0;

uint32_t millis(void) {
  uint32_t value;
  uint8_t sregCopy = SREG;
  cli();
  value = oneMilliCounter;
  SREG = sregCopy;
  sei();
  return (value);
}

uint32_t micros (void) {
  uint32_t value;
  uint8_t sregCopy = SREG;
  cli();
  value = oneMicroCounter;
  SREG = sregCopy;
  sei();
  return (value);
}

void initializeTimer0CTC_Mode (void) {
  OCR0A = 15; // Set for 1 usec.
  TCCR0A |= 1 << WGM01;  // CTC Mode
  TIMSK0 |= 1 << OCIE0A;
  TCCR0B |= (1 << CS00); // prescaler=1
}

ISR(TIMER0_COMPA_vect) {
  static uint32_t prevMicro;
  oneMicroCounter++;
  if (oneMicroCounter - prevMicro >= 1000)   {
    prevMicro = oneMicroCounter;
    oneMilliCounter++;
  }
}

int main(void) {
  DDRD |= 1 << PD3;
  initializeTimer0CTC_Mode();
  sei();
  uint32_t prevTime = micros();
  while (1) {
    uint32_t currentTime = micros();
    if (currentTime - prevTime >= 1000) {
      PORTD ^= (1 << PD3);
      prevTime = currentTime;
    }
  }
  return (0);
}

One microsecond is only 16 CPU cycles.

The CPU needs 4 cycles to prepare itself for servicing the interrupt
(save the program counter, load the interrupt vector and clear the I bit
in SREG). The interrupt vector itself is a jmp instruction that takes
2 cycles. When the ISR is done, it executes the reti instruction
(return from interrupt) that takes 4 cycles. This means you have only 6
CPU cycles left for:

saving the context, i.e. pushing to the stack any register your ISR
may modify (2 cycles per push)
doing the actual ISR work
restoring the context (2 cycles per pop)
doing also some useful work in the main program.

There is no way you can do half of this in only 6 cycles.

Edit: I did a couple of experiments to gain more insight on the cost
of running an interrupt too often.

In the first experiment, I used your initializeTimer0CTC_Mode()
function to interrupt every microsecond the following program:

// This ISR consists of a sigle `reti' instruction.
EMPTY_INTERRUPT(TIMER0_COMPA_vect);

#include <util/delay.h>

int main(void)
{
    initializeTimer0CTC_Mode();
    DDRD |= _BV(PD2);       // PD2 = digital 2 as output
    sei();
    for (;;) {
        PIND |= _BV(PD2);   // toggle PD2
        _delay_us(499.75);  // 0.5 ms - 4 cycles
    }
}

The program is meant to generate a 1 kHz signal on pin 2, and
that's exactly what it does if the sei(); statement is commented out.
With the sei(); statement, the frequency drops to 375 Hz. This
shows that processing an empty interrupt (an ISR consisting solely of
the reti instruction) costs 62.5% of the CPU power, leaving 37.5% to
the main program. 62.5% is exactly 10 out of every 16 CPU cycles,
which confirms the cycle count of the first part of this answer.

The second experiment was to compile and disassemble your ISR. Here is
what I got:

__vector_14:
    push r1
    push r0
    in   r0, 0x3f  ; 1 cycle
    push r0
    eor  r1, r1    ; 1 cycle
    push r18
    push r20
    push r21
    push r22
    push r23
    push r24
    push r25
    push r26
    push r27
; static uint32_t prevMicro;
; oneMicroCounter++;
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    adiw r24, 0x01
    adc  r26, r1    ; 1 cycle
    adc  r27, r1    ; 1 cycle
    sts  0x0104, r24
    sts  0x0105, r25
    sts  0x0106, r26
    sts  0x0107, r27
; if (oneMicroCounter - prevMicro >= 1000)   {
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    lds  r20, 0x0100
    lds  r21, 0x0101
    lds  r22, 0x0102
    lds  r23, 0x0103
    sub  r24, r20   ; 1 cycle
    sbc  r25, r21   ; 1 cycle
    sbc  r26, r22   ; 1 cycle
    sbc  r27, r23   ; 1 cycle
    cpi  r24, 0xE8  ; 1 cycle
    sbci r25, 0x03  ; 1 cycle
    cpc  r26, r1    ; 1 cycle
    cpc  r27, r1    ; 1 cycle
    brcs 0f  ; 1 cycle if the if() condition is true, 2 otherwise
;   prevMicro = oneMicroCounter;
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    sts  0x0100, r24
    sts  0x0101, r25
    sts  0x0102, r26
    sts  0x0103, r27
;   oneMilliCounter++;
    lds  r24, 0x0108
    lds  r25, 0x0109
    lds  r26, 0x010A
    lds  r27, 0x010B
    adiw r24, 0x01
    adc  r26, r1    ; 1 cycle
    adc  r27, r1    ; 1 cycle
    sts  0x0108, r24
    sts  0x0109, r25
    sts  0x010A, r26
    sts  0x010B, r27
; } }
0:
    pop  r27
    pop  r26
    pop  r25
    pop  r24
    pop  r23
    pop  r22
    pop  r21
    pop  r20
    pop  r18
    pop  r0
    out  0x3f, r0  ; 1 cycle
    pop  r0
    pop  r1
    reti           ; 4 cycles

Unless otherwise noted in comments, every instruction of this listing
takes 2 cycles to execute. Note the large number of CPU registers saved
(push) and restored (pop), and the large number of SRAM accesses
(lds and sts): three 4-byte variables read and written back.
Counting the total number of cycles taken by this ISR is left as an
“exercise to the reader”.


Replacing BT module with 433 MHz transreceiver module I have made a prototype where I can send data from one arduino to another via Bluetooth(hc-05), they are working fine, but now I want to replace the BT module with RF module, how can I do that???

Yes, use VirtualWire or RadioHead. You might need to "evolve" your protocol to handle message fragmentation and loss. RadioHead has support for that.

Cheers!


Equivalent to POSIX mmap() in AVR-libc Is there an similar function in AVR-libc/Arduino C++ to mmap()? I'm looking for a way to place machine code in memory at runtime and make it executable.

No.

First, mmap() makes almost no sense on an AVR, as there's no memory management unit or concept of process memory to configure.  Some related concepts like sbrk() are occasionally implemented in a minimalist fashion to let library functions designed for larger computers work, but they typically only update a tracking variable or fail.  For things that are physically realizable you can write your own mmap() if you really want, either allowing (assigning) or disallowing a region, and even if you really want automatically copying part of a file off an SD card or whatever...

But more importantly, your actual goal is entirely unachievable, as the AVR is a strict Harvard Architecture which can only execute instructions from flash, never from RAM.

If you want to execute from RAM, try one of the various small ARM Cortex M0/M4/M3 platforms (many of which have Arduino ports), or even consider a larger Embedded Linux system, which will not necessarily be any more expensive than an Arduino.


Do multiple ultrasonic sensors need an external power source? So maybe it's a very low class form of question, but please bear with me. I'm working on a project with 7 HC-SR04 ultrasonic sensors connected to one Arduino. I tried to unify the trigger and echo pin, but the sensing isn't good enough, so I dropped the Uno and convert it to Mega. My question is, do I need external power source for those 7 Sensors? And how do I connect all of them? Thanks

Well, according to the datasheet the "working current" is 15mA.  Even if you had all 7 working at once, which I doubt you will - you'll be working through them in sequence I guess - that would be just 105mA - way below the 800mA the Arduino's on-board regulator can supply, and only a fifth of what a USB port can provide.

The datasheet doesn't mention the quiescent (idle) current, but it will be a tiny fraction of that 15mA and so can mostly be ignored.  Running the sensors in sequence, which is the most likely scenario, would use about the same amount of current as if you had 1 sensor - or 20 sensors.  Most of the current consumption would be while you are actively producing an ultrasonic chirp.

So no, you don't need an external power supply to run them all - just take them all from the Arduino's 5V pin.


Arduino communication to Raspberry Pi using HC-05 I'm using two HC-05 modules on two Arduino UNO boards. One of my modules connected successfully to a raspberry pi port. However the other doesn't want to connect, but sometimes it does and then randomly disconnects. When I did manage to connect both modules to port on the pi I had code written to send data to the pi and display it in the terminal but only one Arduino data would show up on the pi terminal even though both were sending data. Is there an easier way to connect the modules? I've been using the bluetooth manager tool on the pi

void setup() {
 Serial.begin(9600);
 pinMode(8, INPUT); // first sensor input
 pinMode(7, INPUT); // second sensor input
 pinMode(6, INPUT); // third sensor input
 pinMode(5, INPUT); // fourth sensor input

}

void loop()
{

    int sensordata_1 = digitalRead(8); // read status and store it into variable
     {
          if(sensordata_1 == LOW)        //  CAGE 1
          {
            Serial.println("Arduino 1 s1: 1");  //
          }
          else
          {
            Serial.println("Arduino 1 s1: 0");
          }
          delay(200);

    }
}

void setup() {
 Serial.begin(9600);
 pinMode(8, INPUT); // first sensor input
 pinMode(7, INPUT); // second sensor input
 pinMode(6, INPUT); // third sensor input
 pinMode(5, INPUT); // fourth sensor input

}

void loop()
{

    int sensordata_1 = digitalRead(8); // read status and store it into variable
     {
          if(sensordata_1 == LOW)        //  CAGE 1
          {
            Serial.println("Arduino 2 s1: 1");  //
          }
          else
          {
            Serial.println("Arduino 2 s1: 0");
          }
          delay(200);

    }
}

import serial
import time

port = serial.Serial("/dev/rfcomm2", baudrate=9600)
port_2 = serial.Serial("
port.flush() # This wil flush any input and output buffer, so it will
#avoid receiving or sending bad data

while True:

    if(port.in_waiting > 0):
        data = port.readline().decode('utf-8').rstrip() # decode will translate
        #the data from unicode to byte
        print(data)

port_2 = serial.Serial(" is most likely a copy and paste error on your part, but needs to be fixed if you want 2 serial ports to deal with
You only read from port in your Python while loop without touching port_2. This is the reason you only see output from one serial port
You should use a robust serial data packet-system. Right now you have no way of ensuring that the data received in Python is corrupt or not. You can easily use the pip-installable Python package pySerialTransfer and compatible Arduino library SerialTransfer.h (installable via the Arduino IDE's Libraries Manager).

For theory behind robust serial communication, check out the tutorials Serial Input Basics and Serial Input Advanced.


Error: invalid types 'int[int]' for array subscript I am trying to get an Arduino to work with some Adafruit Motor shields.
Everything seemed to work fine, but when I tried to create a function, I get the error in the subject. As far as I can tell, everything was declared properly (the array is initialized and is indexed elsewhere with without issue). Only the function seems to cause an issue.

Would anyone have a guess at what's wrong?

    //////// Imports
    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_PWMServoDriver.h"

    ////////My globals. Times are in milliseconds
    unsigned long currentTime = 0;
    unsigned long elapsedTime = 0;
    unsigned long startTime = 0;
    byte currentMotor = 1;
    byte currentShield = 1;
    byte motorRunning = 0;

    //// Settings

    // How many seconds between motors
    unsigned long endTime = 4000;

    // How many shields and motors per shield
    const int nShields = 1;
    const int nMotorsPerShield = 3;

    /////////MicroManager globals
    unsigned int version_ = 2;
    const unsigned long timeOut_ = 1000;
    byte currentPattern_ = 0;
    unsigned long time;

    /////////Adafruit globals
    Adafruit_MotorShield afms[nShields];
    Adafruit_DCMotor *motor[nShields][nMotorsPerShield];

    ////////////Setup
    void setup() {
      Serial.begin(57600);

      unsigned char address = 96;

      for (int i = 0; i < nShields; i++) {
        afms[i] = Adafruit_MotorShield(address);
        address = ++address;
        afms[i].begin();
      }

      for (int i = 0; i < nShields; i++) {
        for (int j = 0; j < nMotorsPerShield; j++) {
          motor[i][j] = afms[i].getMotor(j + 1);
          motor[i][j]->setSpeed(255);
        }
      }

      pinMode(13, OUTPUT);
    }

    ////////////////////Main
    void loop() {
      currentTime = millis();
      elapsedTime = currentTime - startTime;

      if (elapsedTime > endTime) {
        startTime = currentTime;
        currentMotor = currentMotor + 1;
        if (currentMotor > nMotorsPerShield) {
          currentMotor = 1;
        }
      }

      if (Serial.available() > 0) {
        int inByte = Serial.read();

        switch (inByte) {
          case 1:
            if (waitForSerial(timeOut_)) {
              currentPattern_ = Serial.read();
              if (currentPattern_ == 0) {
                for (int i = 0; i < nShields; i++) {
                  for (int j = 0; j < nMotorsPerShield; j++) {
                    motor[1][j]->run(RELEASE);
                  }
                }
              }
              else {
                switchMotor();
              }
              Serial.write( byte(1));
              digitalWrite(13, HIGH);
            }
            break;

          case 30:
            Serial.println("MM-Ard");
            break;

          case 31:
            Serial.println(version_);
            break;
        }
      }

      digitalWrite(13, LOW);
    }

    ////////////////Function definitions

    bool waitForSerial(unsigned long timeOut)
    {
      unsigned long starTime = millis();
      while (Serial.available() == 0 && (millis() - starTime < timeOut) ) {}
      if (Serial.available() > 0)
        return true;
      return false;
    }

    void switchMotor()
    {
      int shield = currentShield - 1;
      int motor = currentMotor - 1;
      for (int i = 0; i < nShields; i++) {
        for (int j = 0; j < nMotorsPerShield; j++) {
          if (i == shield && j == motor)
            motor[i][j]->run(FORWARD);
          else
            motor[i][j]->run(RELEASE);
        }
      }
    }

Take a close look at this line:

motor[1][j]->run(RELEASE);

Looks like it should be:

motor[i][j]->run(RELEASE);

Otherwise it is an illegal index (as there is only one shield).

The next error is in the function switchMotor(). Again, have a close look at the definition of "motor". There is a local variable with that name but you want to also access the global array with the same name.

void switchMotor()
{
  int shield = currentShield - 1;
  int motor = currentMotor - 1;
      ^
  for (int i = 0; i < nShields; i++) {
    for (int j = 0; j < nMotorsPerShield; j++) {
      if (i == shield && j == motor)
        motor[i][j]->run(FORWARD);
        ^
      else
        motor[i][j]->run(RELEASE);
    }
  }
}

My guess is that this is where the compiler give you the error message!

Cheers!