code wont upload to arduino starter kit My operating system : OS X EL CAPITAN

Please help I was trying to do project 05 Mood cue of the arduino starter kit. I completed setting up my board and writing the code and when I tried to upload I got this error message:

Arduino: 1.7.10 (Mac OS X), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/tty.usbmodem1411": Device not         configured
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

Can someone please help me?

Thank you Harry i managed to fix it by downloading CH341SER_MAC.zip just in case someone has the same problem wch.cn/downfile/178


LCD library and timer2 CTC interrupt not working together I want to set up real time counter along with lcd functions from LiquidCrystal library. But they don't work together. However, they work fine separately.
The code is working by itself, but by implementing counter function, LCD just freezes with other functionality.
Part of code:

    #include <LiquidCrystal.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7, 8, 9, 13, 12, 10);

volatile boolean timerFlag = false;
volatile unsigned long int tmr2Count = 0;

void setup(){

    timer2Init();
}
void loop(){
    checkState();

}
//everything works by commenting out ISR and timer2Init
//===================================================
ISR (TIMER2_COMPA_vect){
  if (timerFlag)
    tmr2Count++;
}
void timerStart(void){
  if ( !timerFlag )
    timerFlag = true;
}
void timerReset(void){
  timerFlag = false;
  tmr2Count = 0;
}
void timer2Init(void){
    //Timer 2 interrupt service routine CTC settings, 1 uS:

    TCCR2A = 0;
    TCCR2B = 0;

    //set CTC mode
    TCCR2A |= (1 << WGM21);
    //prescaler 1 for timer2
    TCCR2B |= (1 << CS20);

    // prescaler for 1 uS.
    OCR2A = 15;
    //set compare match for register OCRA
    TIMSK2 |= ( 1 << OCIE2A);
}
//========================================================

// menu
void checkState(void)
{
  // if button is pressed without menu being displayed
  if (userSettings.currentState == STATE_IDLE && encButton == true){
    userSettings.currentState = MENU_CHOICE;
    lcd.clear();
    lcd.setCursor(3,1);
    lcd.print("<Settings>");
    encButton = false;
  }

  int menuState = userSettings.currentState;

  switch(menuState)
  {
    case STATE_IDLE:
      timeDisplay();
      dateDisplay();
      break;

    case MENU_CHOICE:
      menuSettingDisplay();
      break;

    case MENU_CONTRAST:
      contrastSetting();
      break;

    case MENU_TIME:
      timeSetting();
      break;

    case MENU_DATE:
      setDate();
      break;

    case TIME_DISPLAY:
      timeDisplayOnOff();
      break;

    case DATE_DISPLAY:
      dateDisplay();
      break;

    default:
      break;
  }
}

I digged in LiquidCrystal.cpp and found that there is DelayMicroseconds function, I'm thinking that it could be the cause. If it's not, what can be done otherwise ?

You're getting interrupt every 16th CPU clock cycle. The ISR handler might be even longer than that and your code and lower priority ISRs suffers by "starvation" as MCU can't do anything else than processing ISR.

If you use prescaler value 8, then you have 1/2us resolution of TCNT2 and overflow interrupt (in normal mode) occurs every 128us, so there will be enough time to do something else. However, if you want atomic value of TCNT2 and counted value from ISR handler, you'll have to stop Timer2 for a while.


How to fix HC05 burning even after while using voltage regulator? I'm using two circuits for my wireless head mouse project, one of them is a transmitter circuit with Arduino Pro Micro, HC05 Bluetooth module, Elechouse Voice Recognition Module V3.1, GY-521 module based on the MPU6050 sensor. The receiver circuit (Arduino Pro Micro + HC05 Bluetooth) will receive the sensor readings from the transmitter circuit. Both modules were powered by USB from the laptop initially. They worked fine. To make the transmitter circuit completely detached from the laptop, I used a 9V battery, and a voltage regulator of 5V. The receiver circuit was still c. I should mention that I was using voltage dividers for both of the transmitter, and receiver circuit's HC05 Bluetooth modules.
onnected to the laptop USB.
.
After using the voltage regulator, the module was working fine but suddenly the HC-05 burnt, led stopped working. Transmission failed. HC05 of the receiver module also burnt after 2 minutes. Why did this happen? What's the solution?
Circuit connection:
Hc05 connection same for transmitter & receiver circuit
HC05 Tx -> Arduino Rx
Hc 05 rx -> 2k ohm -> gnd
Hc05 rx -> 1k ohm -> hc05 tx
Hc05 vcc -> arduino 5v
Hc05 gnd -> arduino gnd
Voice Recognition Module tx -> arduino 8
Rx -> Arduino 9
Vcc- 5v
Gnd - gnd
Mpu6050 sda - Arduino 2
Scl- Arduino 3
Vcc - 5V
Gnd- Gnd
Voltage regulator connection:
The connection was 9V battery +ve to input, -ve to ground, output to Arduino 5V

You said "I should mention that I was using voltage dividers for both of the transmitter, and receiver circuit's HC05 Bluetooth modules."
Voltage dividers are not a good way to lower voltage for power components. The voltage output will vary based on load, and they also dissipate the excess voltage as heat, so you need high current resistors.
Post a schematic of your system with the specific batteries, regulators etc that you are using.


Activating a Relay with Wemos D1 I have a problem similar to these questions:

Wemos D1 doesnt drive Relay

Wemos D1 is not triggering Relay

I got this BC548B transistor from an old apparatus I scratched. The transistor saturation voltage is 0.6V  according to the datasheet:

https://alltransistors.com/pdfdatasheet_fairchild_semi/bc548_bc548a_bc548b_bc548c.pdf

When I set up my circuit the wemos d1 inboard leds dim and the board resets so I guess something is going really wrong. Can someone advise if my design makes sense?

UPDATE

I replaced the 12V relay with a 5V one but still can't get it to work. Basically, the 3.3V signal seems to be too low to activate the solenoid. How can I raise the 3V3 signal to 5V? What was wrong with my idea of using a transistor to do it?

That appears to be a 12 "solid state" relay. That means that it is designed to be both powered by and switched by 12V. You're trying to drive it with slightly more than 1/3 of its rated voltage. Don't do that.
Edit:
Note that none of the relays being discussed are true solid state relays. These are are all conventional coil relays that include cicuitry that allows them to be driven by CMOS logic signals. A true solid state relay does not have any moving parts, but uses solid state components to do the job of a relay. Those cost significantly more money however.)

It might be that you can get away with driving a 5V solid state relay with 3.3V, or 12V relay with 5V, but you shouldn't do those things either.
Also note that even if you are using the correct relay, your relay almost certainly takes more current than the 5V pin on an Arduino can provide (When driven from USB, the entire system is limited to 500 mA, including the power needed to the Arduino.)
Edit:
These solid state relays come in 12V, 5V, and 3V flavors. Get a 3V one: https://www.adafruit.com/product/3191?gclid=EAIaIQobChMIyY_dxM344gIVELbICh1ufwivEAQYBSABEgI3wPD_BwE


Stacking shields without headers In the project I am working on, I have a limited space with which I can work. I am using an Arduino Uno with 2 Adafruit motor shields, and when I stack them using normal, female stacking headers it is too tall to fit. I thought that one way to solve this would be to lay them out side to side rather than one on top of the other. So, instead of this

+--------Motor shield 2 ----------+
|||||||||||||||||||||||||||||||||||
+--------Motor shield 1 ----------+
|||||||||||||||||||||||||||||||||||
+---------Arduino Uno ------------+

it would look like this

               -----------------------------------------Wires -------------------------------
+---------Arduino Uno ------------+    +--------Motor shield 1 ----------+    +--------Motor shield 2 ----------+

Would this be possible if I were to connect all of the pins with wires, and has anyone successfully done this before?

It is possible to have some success with this, but keep in mind that the longer the wire, the higher the inductance and voltage drop across the wire. Prefer to use a star topology rather than a chain topology, with the Arduino in the middle of all the shields in use.


Are there flexible pressure sensors for Arduino that can measure forces of at least 600 lbs? I'm in need of flexible pressure sensors that can read how much force is exerted on someone's foot while running (these sensors would be placed inside the shoe). Since pressure can often be three times the weight of the person, I need something fairly strong. Are there fairly cheap sensors that are available or hacks that could do the same thing?

Thanks!

Sensors such as you describe are usually called "Load Cell".

At the 600 pound weight, I haven't found any "flexible" load cells. A sensor would have to be quite robust.

Flexible might not be the best answer.

This load cell page has quite a range of load cells, several thousand pounds, also not very inexpensive.

This might be difficult to install in running shoes :


keypad code is not working and produces wrong numbers I have the following issues:

1) When i press for example number 7 on the keypad it shows a different number on the serial monitor
2) The servo motor works for any combination of 4 numbers.

Code:
/*http://openhwdesign.comLock system using a Keypad
*/

#include <Password.h>
#include <Keypad.h>
#include <Servo.h>
#pragma GCC diagnostic ignored "-Wwrite-strings"
Servo myservo; //declare servo
Password password = Password( "5523" );

const byte ROWS = 4; // declare the rows of the keypad
const byte COLS = 3; // declare the columns of the keypad

// Define the Keymap

char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};

byte rowPins[ROWS] = {2,3,4,5}; // Connect keypad’s pins to these Arduino pins.
byte colPins[COLS] = {6,7,8}; // Connect keypad’s pins to these Arduino pins.

// Create the KeyPad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup(){
Serial.begin(9600);
myservo.write(0);
pinMode(11, OUTPUT); //The green led is set as an output.
pinMode(12, OUTPUT); //The red led is set as an output.
myservo.attach(13); //The servo is connected to the digital pin 13.
keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad

}

void loop(){
keypad.getKey();
myservo.write(180); //why? what happens if you comment it? ###########################
//delay(5);
}

void keypadEvent(KeypadEvent eKey){
// When the KeyPad will be pressed, the results will appear on the serial monitor.
switch (keypad.getState()){
case PRESSED:
Serial.print("Enter: ");
Serial.println(eKey);
delay(10);

switch (eKey){
case '*':
checkPassword(); // Will check the password.
delay(1); // Delay used for stability.
break;

case '#':
password.reset(); //Will reset the password
delay(1); // Delay used for stability.
break;

default:
password.append(eKey); //Append any keypress that is not a ‘#’ nor a ‘*’.
delay(1);
}
}
}
void checkPassword(){

if (password.evaluate()){ //If the combination inserted is equal to the combination saved, the servo’ll rotate.
Serial.println("Accepted");
//delay(5000);
delay(10);
myservo.write(50); //was 140
delay(5000);

digitalWrite(11, HIGH); //Turn the green led on.
delay(500); //Wait 5 seconds.
digitalWrite(11, LOW); //Turn the green led off.

//break; // remove if trial did not work #####################try#####################
}
//break; // remove if trial did not work ##########################################
else{ //If the combination inserted isn’t equal to the combination saved, the servo will not rotate.
//delay(5000); delays response
Serial.println("denied");
delay(10);
//delay(5000);
myservo.write(20); // was 50
digitalWrite(12, HIGH); //Turn the green led on.
delay(5000); //Wait 5 seconds. was 500 ///
digitalWrite(12, LOW); //Turn the green led off.

    }
}

Thank you.

The first thing you need to do is just look at what the problem is.  Create a new sketch and paste this code into it.

#include <Keypad.h>

const byte ROWS = 4; // declare the rows of the keypad
const byte COLS = 3; // declare the columns of the keypad

// Define the Keymap
char keys[ROWS][COLS] =
{
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
};

byte rowPins[ROWS] = {2,3,4,5}; // Connect keypad’s pins to these Arduino pins.
byte colPins[COLS] = {6,7,8};   // Connect keypad’s pins to these Arduino pins.

// Create the KeyPad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void keypadEvent(KeypadEvent eKey)
{
    // When the KeyPad will be pressed, the results will appear on the serial monitor.
    switch (keypad.getState())
    {
    case PRESSED:
        Serial.print("Enter: ");
        Serial.println(eKey);
        delay(10);
        break;
    }
}

void setup()
{
    Serial.begin(9600);
    keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad
}

void loop()
{
    keypad.getKey();
    delay(20);
}

You should recognise it, its a reformatted version of your code (pretty code is easier to debug), but with only the keypad bits in.

Now load that onto your hardware and write down what number is shown when you press 1 three times.  Do it three times just to make sure its the same number and you haven't got something totally obscure happening. Repeat for the other 11 buttons.

If 7 and 3 always give you 3 and 6 then you have got your row and column wires crossed.
If 7 always gives you 1 and 9 always gives you 3 then the wires for row 4 and 2 are crossed over. etc
If you can't work out the patter post your findings and I'm sure someone will solve the puzzle.

As for problem 2, don't even go there until you know what you are typing. :)

Hope that helps


Callback functions when using a class This question is somewhat similar to How to pass non-static class member to callback?, but there are a few differences, especially since a lot of my uses have "interesting" additional complexities. I'd like to understand better my options in using them, since I have not gained enough understanding from other answers (and I need to write both the callback and the function that calls it).

I have a number of libraries that produce "events" that I'd like to be able to write separate classes or functions to respond to (so I don't need to customize every library every time I develop something). The annoying part is that I've long-since discovered the this pointer that's hidden in class method calls, which prevents me from passing currentgui.leftbutton as a function to menu.leftbuttonpressed(void (*callbackfuncptr)(void)).

I'm also using the ESP8266 web server library, which needs a callback in the context of the server object that can call the server as a global to actually get the data sent to it! (Unless the server passes its own this as a parameter to the callback, which I don't know since the documentation consists almost solely of a small number of "examples" which don't show the majority of the actual features of the web server, rather than a real explanation.)

I could use some variant of a pointer to a class method, but the syntax for that is eye-gouging and I'm using more than one class to provide callbacks to (especially for the task scheduler), so this would require customizing the library to handle pointers to every class I use again. I can't use polymorphism, either, since some classes contain multiple scheduler callbacks to be done on different times/conditions.

How do I handle these callbacks? My current method is to write a function that wraps the method's function, but that relies on a specific instance of that method, so it can't be reused. It's also really awkward since I'm now dealing with multiple functions/methods that are now very similar.

I would also like to be able to have a class, that when passed a web server object, registers itself as a callback to a particular page event (I want to write a network connection manager similar to the WiFiManager library, but with the ability to integrate with an existing webpage. I have all the code, but it currently can't be nicely integrated into a standalone class because of this issue). It needs to store a pointer to the server object to get the data once the callback's called, but it also needs to be attached to the callback of the class that holds that particular pointer AND the other handler functions once the data's retrieved.
There is already a library that does something similar, but I can't figure out at all how this works, since I was under the impression that this is not possible. Can someone help me understand how the following class operates?
https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266HTTPUpdateServer/src

The ESP8266WebServer uses callback functions to handle HTTP request by your code. This callback functions can't be members of a class. But you can use anonymous functions to implement this callbacks. And if you like you can implement them as 'redirects' to functions of your objects.

server.on("/leftbutton", []() {
  currentgui.leftbutton(server);
}

Note: this anonymous functions are called lambda functions and they can do some tricks with parameters too


How do I make a character array scanner properly? I start with this:

char delay_chars[10];

then I have a stream of incoming characters that I need to assign like this:

['I', ' ', 'l', 'o', 'v', 'e', ' ', 'p', 'i', 'e']

I can do that, but then more characters come in so I need it like this:

[' ', 'l', 'o', 'v', 'e', ' ', 'p', 'i', 'e', ' ']
['l', 'o', 'v', 'e', ' ', 'p', 'i', 'e', ' ', 'a']
['o', 'v', 'e', ' ', 'p', 'i', 'e', ' ', 'a', 'n']
['v', 'e', ' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd']
['e', ' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd', ' ']
[' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd', ' ', 'c']
['p', 'i', 'e', ' ', 'a', 'n', 'd', ' ', 'c', 'a']
['i', 'e', ' ', 'a', 'n', 'd', ' ', 'c', 'a', 'k']
['e', ' ', 'a', 'n', 'd', ' ', 'c', 'a', 'k', 'e']

You get the idea. I don't know how I can remove the first character of a char array (like I do with a String, remove(0, 1)) and I don't know how to add a new element at the end.

If I had to guess, I'd make a loop that will reassign the index of each character one step back or something like that but I'm not sure if that's how I should do it.

If I had to guess, I'd make a loop that will reasign the index of each character one step back or something like that but I'm not sure if that's how I should do it.

Yep, that's pretty much it...

Here's how I do it:

char data[10];

if (Serial.available()) {
    char inch = Serial.read();
    for (int i = 0; i < 9; i++) {
        data[i] = data[i+1];
    }
    data[9] = inch;
}

Every incoming character gets added to the end of the array after everything else has been shuffled down one place.


What are the consequences of different clock speeds on different boards? I am a programming amateur, arduino noob, trying to decide which board will be better for my project. I need a small board. I am trying to decide between the Teensy 3.2 and the RFduino. I want to have blue-tooth capability for over air routine changes to a WS2812B LED strip, which makes the RFduino attractive because of its integrated BLE4.0 antenna. However, I want to be able to have enough speed for imperceptible LED modulation, which makes the 72MHz speed of the Teensy attractive.

What would be the objective difference between the 16MHz processor on the RFduino versus the 72MHz on the Teensy3.2? Is this something I should be concerned with?

As was mentioned earlier about the DotStar LED strip/led

There is one thing missing in the calculation above. The End Frame shows as a 32 bit frame of all 1's. That is almost correct. The least obvious is that you need to add 1/2 of a bit for each led in the strip. This is due to the way that the clock is sent down the line. So the 180 led strip would require 90 bits in the End Frame. If you don't do this you will have some of the leds at the end that are not reacting correctly. I know this sounds strange, had me for a while (I use Raspberry Pi).

Also, I have seen where some have tested the SPI mode of sending the data down the line and managed to achieve about 16Mhz clock speeds. Great for POV display.

The DotStar don't require refreshment at all. Each LED has it's own PWM chip built in. They are more expensive than the Neopixel, so it depends on the application as to which is better for you. I loaded my string with colors and then disconnected the data lines (led strip on different power supply) and turned off my Pi. Yup, the DotStars stay as they are.

It has been said they are 'addressable' which is not truly accurate. When sending data, it is the first one, then the second and on. If you wanted, you can change only the first few. Odd hack. Just send the Start Frame (32 or more 0's) and start sending data to the first without affecting the rest of the strip. Note: you might have to account for the 1/2 bit clock loss. eg: 1 bit per 2 leds.

Here is a pretty good description of the DotStar functionality :
https://cpldcpu.com/2014/11/30/understanding-the-apa102-superled/

Here is a Youtube tutorial (2 short videos) that helped me quite a bit:
https://www.youtube.com/playlist?list=PLhXSL6B3uLd551fEQlQGd3LrhzvudKfJQ


Portable power for an UNO with a nrf24l01+ attached? Okay so I have an UNO that has an nrf24l01+ attached. I want it to be completely wireless so free of the 5v USB power and the 12V wall plug. In this case what can I use? I do not wish to plug the power directly into the Vin as I am relatively new and afraid that it might fry the board. So I wish to plug it into the barrel jack. So I have read that using a 9v battery to power UNO is a waste of power as most of the power is translated into heat. Also, using 4 AA batteries seem to be a good solution except that I'm not sure if it has enough power for nrf24l01+ as I've read that an arduino with nrf24l01+ on batteries creates an unstable wireless node. I would like some help on what I can power the UNO with.

I've used the usb battery chargers (marketed to recharge cell phones) with great success on many different Arduino boards. They come in a variety of mAH capacities and are easily recharged with any powered USB port/power adapter.

Here's a link to one I've used. (I'm not affiliated with Duracell in any way).

http://ww2.duracell.com/en-US/product/instant-usb-charger.jspx


I need a simple, low power, low cost wireless switch to transmit to Arduino I'm looking for a very simple wireless, low-power, low-cost switch that can transmit a signal to an Arduino. Ideally, each transmitter would have a signature. For instance, let's say I had 4 different transmitters that are attached to a sensor. When the sensor is tripped, I want to wirelessly send a signal to the Arduino. I've looked at these 433 MHz modules, but it seems like they would also need a microcontroller to send the data, while that's a possible solution, I'm wondering if there is a even smaller, simpler solution.

There is no such thing as a transmitter that can attach direct to a sensor, since no two sensors in the world work the same way. You need something intelligent between the sensor (to read the sensor value) and the transmitter (to tell it what to transmit).

There are "all in one" modules, like the ESP8266, which have an MCU and WiFi combined in one chip which are closer to what you want, but it is still down to you to program those modules to work how you need them to work for your sensors.


Garage door button with delay feature I am working on an art project that involves a garage door opener.  I am very new to Arduino, and electronics.  I have a starter kit with a ton of accessories.

The garage door opener has 2 screws (terminals?) designed to connect a button.  If I touch a wire between them, the opener will start.  I connected a button to my bread board, and ran wires to those terminals on the opener to see if a simple switch would work, and it does.

I want to:

press a button, and the Arduino connects the terminals on the opener, and then it starts
button is then ignored (delayed) for a set amount of time (5 seconds for this example)
after the set amount of time, the button works as normal (like in step 1)

I ran through some tutorials on buttons, and I think I got ahead of myself.

I can turn on an LED from a switch on the bread board, and use a delay(5000) to ignore any other button presses.  I tried to connect the wires that were going to LED to the 2 terminals on the garage door opener, and it did not work
In code, I setup pin 5 as OUTPUT, and pin 6 as INPUT.  I used the button to send a HIGH on pin 5, to see if that signal would work when connected to the 2 terminals on the opener.  I tested this a bit in code by reading the state of pin 6, and it appears to have worked.  However, it did not work when I connected both pin 5 to one terminal, and pin 6 to the other.

I tried looking for a simple example, but searching for garage door openers and Arduino results in too many tutorials on how to do super fancy wireless stuff.  I just want to ignore a button press for 5 seconds after it has been pressed once.

I'm looking for a simple example that allows my button to tell the Arduino to make that connection on the garage door opener.  I guess I'm looking for my Arduino to act like a switch instead of my (physical) switch?

My Arduino kit comes with a bread board, wires, switches, Uno R3 and tons of other stuff I haven't gotten to yet.  I apologize in advance if I'm not thinking of something super-simple that would solve my problem.  I'm very new to this.

Thanks for your time!

Edited for spelling.  Elaborated on my attempts.  I'm going to read about what a relay is.

I figure out a solution - I just needed to use a relay.

I didn't know what a relay was, and had a hard time figuring it out.  I've included some notes for anyone who finds this post in the future.

I can't determine if it took reading 3-4 articles on relays for it to sink in, or if one article was the best.  Anyway, for me this one helped the most: https://www.instructables.com/id/How-Electronic-Switches-Work-For-Noobs-Relays-and/
My relay looked different from most of the tutorials.  I figured it out by connecting a couple alligator clips to a 9v battery and listening for the click of the magnetic switch.  Then I used my volt meter to determine which leads were working with the relay.

Relay Setup:

I connected my ~5 to one lead on the relay, and 5v to the other
The Common (middle) lead connects to one terminal on the garage door opener
The N/C (Normally Closed) lead connects to the other terminal on the garage door opener

Button Setup:

The button setup was just like all the other button tutorials
When the button is pressed (LOW), I start and stop the relay to trigger a "button press" for the garage door opener (it starts)
I then run a delay for the set amount of time I want
All button presses are ignored until after the delay has finished

Now I can move on to the actual project.  Thanks!


MQTT vs Tinkerkit sensor Shield I'm working with this http://knolleary.net/arduino-client-for-mqtt/. I'm using Arduino Uno + Ethernet shield + Tinkerkit Shield. But, if i have only Arduino Uno + Ethernet Shield, i can connect my arduino with MQTT and make publish/subscribe, but, when i put the tinkerkit shield, i lost the connection and i cannot connect any more. Any idea? Tinkerkit sensor shield is incompatible with mqtt?

Thanks.

I think your problem is in wiring. Ethernet shield is using SPI communication, it requires pins: SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). Those pins must be left for the Ethernet shield. Information is from Arduino Uno description.

Does your Arduino communicates with you after you plug-in Tinkerkit? If not, maybe you have a short in Tinkerkit shield.


Digital read on voltages between 1 and 31 volts? Hello Arduino comunity!

I am working on a circuit that uses an Arduino Mini to read values from certain points of a boost/buck converter circuit to determine things like input state, output state, overheat and so on. The circuit is working all right, and the only part left to do is to connect the digital pins of the Arduino to the different points in the boost/buck regulator.

The problem is however that I need to read from a range of voltages between 1 and 31 volts with the Arduino, which isn't possible, because not only will it damage the controller if the voltage exceeds 5V, but values below 3V will be regarded as false.

I thought of putting some potential dividers, which would obviously not do the trick, and I also thought of using a WS78L05 voltage regulator per input pin (because each pin might have a different voltage from the rest) but that isn't dealing with voltages <=5V and 31V exceeds its rating as well.

Lastly I thought of using transistors, which seemed like a good idea, but I would require 2 transistors per input wired as follows:

simulate this circuit – Schematic created using CircuitLab

But it is impractical to do for 4 inputs and there is limited space available on the PCB too :(

Is there any IC that encapsulates the circuit above, or is there any other way to achieve what I want to do?

Thanks very much :)

Using a simple voltage divider (51K / 10K as you have worked out already) fed directly into an ADC input will give you a reading of 32 on the ADC at 1V input. That should be enough to give a reliable threshold detection.

If you want to have higher sensitivity at lower voltages you can increase the output of your voltage divider to more than 5V and then clip it with a zenner diode. For instance if you reduce the 51K to 33K you get 7.2V out of the voltage divider. A 5V zenner diode can then clip it to 5V. Your 1V input (which would be 0.233V on the output of the divider) would now read 47 on the ADC. Anything over 21V would then read 1023.

simulate this circuit – Schematic created using CircuitLab

Theoretically you could get away with not having the voltage divider at all and just using the zenner and one resistor to clip the incoming voltage to 5.1V. That would give you the greatest sensitivity, but also the greatest current flow through the zenner.

simulate this circuit

Size R1 to limit the current at your maximum voltage to within the rating of the zenner.


SIM800C, CPIN: NOT READY (ERROR CODE : +CME ERROR: 10) I'm using a SIM800C module, and usually it works fine, but lately it has started giving the error "+CPIN: NOT READY" with ERROR CODE : +CME ERROR: 10(SIM NOT INSERTED). As soon as I get this message, the voltage on SIM_VDD drops to 0V. The problem is intermittent (i.e. it happens only sometimes).

I have read all related posts on here. Here is some info on my setup:
-Schematics is designed according to SIM800C documentation.
-I use 6-pin SIM connector.
-Adding decoupling caps on SIM_VDD, on input power, and on VBAT (for SIM900) does not help.
-Signal strength is fine (about CSQ=20).
-I tried reinserting different SIM cards, nothing helped

The "+CPIN: NOT READY" is sent at different times, however, often quite soon after power on.After removing battery & attaching it again, starts working again. why this issue is occuring..?

The antenna is too close to the module. You probably used the spiral antenna. Try using the PCB antenna with long (10cm) cable.
Had the same problem, solved with the antenna.


String and heap confusion I hope you all well.

Recently after view unknown crashes I decided it can be related with me messing with "heap"

After reading few sources on heaps and how it works it kind of confusing. Some sources mention that you can F() everything and it will be fine and others mention reserving space for strings with "reserve()"

I am looking for suggestions how possibly eliminate or or control?

I will post snapshot of code below where the evil "String" is used few times.

////////sending data
    senddata(String(temp), String(hum), String(dis), String(flood), String(heaterstatus), String(humidifierstatus));
    //////////sending data

void senddata(String temp1, String hum1, String dis1, String flood1, String heater1, String humid1) {   /////sending all field values in one go
  //////////sending data
  String getData = "GET /update?api_key=" + API + "&field1=" + temp1 + "&field2=" + hum1 + "&field3=" + dis1 + "&field4=" + flood1 + "&field5=" + heater1 + "&field6=" + humid1;
  sendCommand("AT+CIPMUX=1", 5, "OK");
  sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
  sendCommand("AT+CIPSEND=0," + String(getData.length() + 4), 4, ">");
  esp8266.println(getData); delay(1500); countTrueCommand++;
  sendCommand("AT+CIPCLOSE=0", 5, "OK");
}

Yes, you could make a global String for getData and reserve space and reuse it every time the function is called. But what with String(getData.length())?

And the parameters? You create a new String for every parameter. And the function senddata doesn't take a reference to the String (String&), but it makes a new copy of each String parameter. So you create 12 small Strings with every call to this function. This is the evil of String. It does everything no matter at what cost.

And your sendCommand takes String too. That is why you can do "AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT and "AT+CIPSEND=0," + String(getData.length() + 4) as parameter to it. So every call to sendCommand creates two small Strings. That is 8. And every + on String can trigger a reallocation on heap.

Use C strings

void senddata(int temp1, int hum1, int dis1, int flood1, int heater1, int humid1) {
  char getData[256];
  snprintf(getData, sizeof(getData), "GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d",
      API, temp1, hum1, dis1, flood1, heater1, humid1);
  sendCommand("AT+CIPMUX=1", 5, "OK");
  char buff[32];
  snprintf(buff, sizeof(buff), "AT+CIPSTART=0,\"TCP\",\"%s\",%d" , HOST, PORT);
  sendCommand(buff, 15, "OK");
  snprintf(buff, sizeof(buff), "AT+CIPSEND=0,%d" , strlen(getData) + 4);
  sendCommand(buff, 4, ">");
}

void sendCommand(const char* command, const int timeout, const char* find) {

F macro optimizes memory use, by using data stored in flash memory. The snprintf_P function is a version of snprintf for format string from flash.

snprintf_P(getData, sizeof(getData), (const char*) F("GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d"),
  API, temp1, hum1, dis1, flood1, heater1, humid1);

One of the classes of my StreamLib is CStringBuilder. With it the code could be:

char getData[256];
CStringBuilder sb(getData, sizeof(getData));
sb.printf(F("GET /update?api_key=%s&field1=%d&field2=%d&field3=%d&field4=%s&field5=%s&field6=%d"),
    API, temp1, hum1, dis1, flood1, heater1, humid1);
sendCommand("AT+CIPMUX=1", 5, "OK");
char buff[32];
CStringBuilder sb2(buff, sizeof(buff));
sb2.printf(F("AT+CIPSTART=0,\"TCP\",\"%s\",%d") , HOST, PORT);
sendCommand(buff, 15, "OK");
sb2.reset();
sb2.print(F("AT+CIPSEND=0,"));
sb2.print(sb.length() + 4);
sendCommand(buff, 4, ">");


Why sensor acts erratically? I am trying to connect an ADXL355 digital sensor to an Arduino. The wiring and the code I think are OK because the system returns the correct values sometimes and partly correct answers mostly. The code checks the device register, and the correct data is printed to serial most of the time. The code also checks for temperature but only returns the correct value occasionally. The values are polled every few seconds. The values are correct all of the time if they are correct the first time after restart but never if they are incorrect on restart. I thought it might help to unplug the sensor when uploading the program or powering up the Arduino through USB to the computer but there is no clear pattern.

It is not a defective sensor because I have 2 that behave the same way. What could be the problem? Is this a problem with the Arduino?

I only wire VDD, VDDIO, ground,chip select, sclk, MOSI and MISO.

code:

#include <SPI.h>

    const int ID = 0x00;
    const int FIFO = 0x11;
    const int TEMP = 0x06;
    const int TEMP1 = 0x07;
    const byte FIFO_WATERMARK = 0x29;
    const int chipSelectPin = 7;

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

        SPI.begin();

        pinMode(dataReadyPin, INPUT);
        pinMode(chipSelectPin, OUTPUT);

        // writing 0 to to enable sensor
        writeRegister(0x2D, 0x00);

        delay(100);

        Serial.println(readRegister(ID));
        Serial.println(readRegister(FIFO_WATERMARK));
    }

    void loop() {
        int temp = (readRegister(TEMP)); // << 8) | (readRegister(TEMP1))) ;
        temp = (temp<<8)|(readRegister(TEMP1));
        Serial.println(((1852 - temp)/9.05) + 19.21);
        Serial.println(readRegister(ID));

        delay(1000);
    }

    byte readRegister (byte thisRegister){
        byte inByte = 0 ;
        SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer((thisRegister << 1) | 1);
        inByte = SPI.transfer(0x00);
        digitalWrite(chipSelectPin, HIGH);
        return inByte;
    }
    void writeRegister (byte thisRegister, byte value){
        SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer(thisRegister << 1);
        SPI.transfer(value);
        digitalWrite(chipSelectPin, HIGH);
    }

Some one suggested it might be signal bounce on the SPI and the clock rate was set to 500kHz but it didn't work.

Update:
Not long ago, the correct device ID would be read consistently (173 for 0xAD); now that returns 0. The temperature would either return 0 from the register or changing values between -1 and -5 that may have been wrongly calibrated temperature. But sometimes the correct temperature would return. Now it also only returns 0 from the registers.

This is a poor product, look at this: that describes exactly the problems you (and me) are experiencing. Correct me if you've found any solutions so far.
edit
Try looking at description of regster 0x2f in datasheet and to this question.
I think that the first problem you describe can be solved this way, the second behaviour sounds like you fried the device.


Why is there a third connection to the host in this 3 wire current output sensor diagram? I've got a 3 wire 4-20mA current output sensor, externally powered by 12V, which I want to read from an Arduino Uno (5V). The sensor connection diagram is below, but I don't understand why it says to connect the sensor power out (12V) to the host as well?

Below that is how I think I should connect it (i.e. with the power out from the sensor simply connected back to itself). Will this work? Could I damage my board or, far worse, the sensor itself this way?

Thanks alot!

The connection diagram is showing the sensor being powered by a host that runs at 12v. Normally the host would provide the power. However, you provide the power yourself from another source. So you don't need power from the host, so you do not connect the 12v to the host.

All you need is the signal and the ground (along with a load resistance to convert the current into a voltage, and maybe some over voltage protection on the signal in case the load resistance becomes disconnected or fails in some other way).

simulate this circuit – Schematic created using CircuitLab

In that example RL is the "Load" resistor and is calculated as the nearest common resistance value that gives, with 20mA (assuming a standard 4-20mA sensor) through it, close to 5V across it without going over. In this case, 4.4V, which is good.  RP is a "protection" resistor to prevent damage to the sensor should the load resistor fail, which would give 12V (though limited in current) across the zener diode D1. It just limits the current that can flow through D1 and be pulled by an effective short circuit across the sensor's output when D1 fails over (if it ever does).  D1 is there to prevent the ADC from ever seeing any more than 5.1V in the event of a problem.


Using Arduino and Motor Shield I am a beginner in Arduino.I want to connect 2 motors to Arduino.
Do I require a motor shield?And if yes please tell why?
Also can i use an amplifier to increase the voltage for the motors?

And one last important question, I have just seen the motor shield's pic. Does it restrict arduino's pin usage? I mean we can't use the arduino pins if we use the motor shield right?

PS: I am talking about this model: SLAEX039 L293D Motor Shield

Thank a lot

Yes. To use standard D.C. motors, you must use a motor shield or the L239D chip. This is mainly due to motor noise, and control to run the motor at different speeds and directions. Also you get very easy to use libraries!


Not clear code procedure in Arduino wire library The application code of sparkFun, has the following line which is difficult to understand.

It's requested 6, because it's requesting 6 bytes for HMC5883L module.

Wire.requestFrom(address, 6);
if(6<=Wire.available())

Where:

int TwoWire::available(void)
{
  return rxBufferLength - rxBufferIndex;
}

So, the available function should return return rxBufferLength - rxBufferIndex; where rxBufferIndex is modified in read function:

int TwoWire::read(void)
{
  int value = -1;

  // get each successive byte on each call
  if(rxBufferIndex < rxBufferLength){
    value = rxBuffer[rxBufferIndex];
    ++rxBufferIndex;
  }

  return value;
}

But, my current question is why decrementing return rxBufferLength - rxBufferIndex; where rxBufferIndex is initialized to 0 all the time, and there's no chance the returned value would be less than 6, because that would terminate the if statement?

rxBufferLength is the number of bytes that have been received. rxBufferIndex is the byte you would next be handed with a read() function call.

So if you have received 6 bytes from the slave (which you will, since that is how many you requested) but not read any the available would be 6. Ergo, 6 <= 6. I.e., you asked for 6, it collected 6, and you are checking that it got at least 6 (it can never be >6 since you only asked for 6, so why they look for at least 6 I don't know).

rxBufferIndex is never decremented. It is incremented when you read a byte, up until rxBufferLength == rxBufferIndex at which point there is 0 bytes available.

  But, my current question is why decrementing return rxBufferLength - rxBufferIndex; where  rxBufferIndex is initialized to 0 all the time, and there's no chance the returned value would be less than 6, because that would terminate the if statement?

The way that Wire.h works is that available() will always return the number of bytes you requested if the call to requestFrom() succeeded until you first read some of that data. If you request 6 and the call worked then you have 6. The if could just as well be written as:

if (Wire.available()) {...

since it will always be 6 immediately after a successful call. However, that makes assumptions about how the Wire API works and could be subject to change in the future or operate differently on different platforms.

So it checks that, right after the call to requestFrom() for 6 bytes it actually got at least 6 bytes. Without seeing what is inside the conditional if, all I can do is make assumptions, but I would assume that it is then reading those 6 bytes, and so it wouldn't care if there happened to be more for some reason. But it doesn't want there to be 5 or fewer bytes available when it is reading 6 of them.

An if statement doesn't "terminate" if its condition becomes false once it has been executed. It's not like a while that keeps running until it's false - it's a single decision made at a single point in time. If anything changes in the future that would have caused a difference decision to be made (e.g., you read() a byte, so available() would now return 5), the decision that has been made still stands.

An analogy for you:

You want to go out for a good healthy walk - but only if it's not raining.

if (!raining) {
    walk_to_shop();
    walk_to_cafe();
    drink_coffee();
    walk_to_shop();
    walk_home();
}

You go out for your walk to the shops, get a coffee, do some more shopping, and then walk home - but you only start doing that if it's not raining. If it starts raining while you're out you don't suddenly teleport back home.  You could make the decision, when you come out of the cafe and see it's raining, to cut your shopping trip short, but you have to actively make that decision. Just because raining becomes true doesn't affect the fact that you are outside and walking.


How does code typed in Arduino IDE runs on a nodemcu? I actually have a series of questions regarding Nodemcu and esp8266.

How does code typed in Arduino IDE run on Nodemcu?
What firmware is present on the nodemcu?
How do I upload the above firmware on esp8266-01 module?
I want my esp8266-01 module to work with a Lilypad Arduino. So this is the way I want it to work: Lilypad Ardiuno has acquires some data using a sensor. It wants to post this data to a server on internet. So to do the job it uses a ESP8266-01. Will the configuration work?

how does code typed in Arduino IDE runs on Nodemcu

The IDE runs the compiler which turns the C into assembly and then machine code.  That is then uploaded to the ESP8266.

  what firmware is present on the nodemcu.

The code that you just wrote and uploaded.

  i want my esp8266-01 module to work with a Lilypad Arduino .So this is the way I want it to work Lilypad Ardiuno has acquires some data using a sensor it wants the post this data to a server on internet.So to do the job it uses a ESP8266-01.So will the configuration work?

Sure, if you program it to do that.  Two choices:

Use the AT firmware on the ESP-01 (installed by default)
Write custom firmware (as above) for the ESP-01 to do what you want.


ToF Laser Sensor (VL53L0X) not working I have this time of flight laser distance sensor: http://www.dx.com/de/p/cjmcu-vl53l0x-tof-laser-distance-measuring-sensor-module-purple-449081#.WSbn52jyi70

The example code of the VL53L0X-arduino library is not working; I always get the serial message

  65535 TIMEOUT

However, I guess that the problem is at the sensor. The communication is via I2C, so that the i2c scanner should find it's address, right?

This finder doesnot find any address - am I right, that then the problem is at the sensor?

I connected VCC to (nearly) 5V, GND to GND, SCL to A5 and SDA to A4 (Arduino Uno)

I had the same problem using this sensor. The solution was to connect

VCC -> 5V
GND -> GND
SCL -> A5 (SCL)
SDA -> A4 (SDA)
DNC -x Not connected
GN2 -> GND
XSH -> 5V
INT -x Not connected

And then to use the code mentioned here by Ted Meyers. I used Nano with ATmega328P and Arduino IDE 1.8.5.

CODE:

#include <Wire.h>

#define VL53L0X_REG_IDENTIFICATION_MODEL_ID         0xc0
#define VL53L0X_REG_IDENTIFICATION_REVISION_ID      0xc2
#define VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD   0x50
#define VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD 0x70
#define VL53L0X_REG_SYSRANGE_START                  0x00
#define VL53L0X_REG_RESULT_INTERRUPT_STATUS         0x13
#define VL53L0X_REG_RESULT_RANGE_STATUS             0x14
#define address 0x29

byte gbuf[16];

void setup() {
  // put your setup code here, to run once:
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
  Serial.println("VLX53LOX test started.");
}

void loop() {
  Serial.println("----- START TEST ----");
  test();
  Serial.println("----- END TEST ----");
  Serial.println("");
  delay(4000);
}

void test() {
  byte val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_REVISION_ID);
  Serial.print("Revision ID: "); Serial.println(val1);

  val1 = read_byte_data_at(VL53L0X_REG_IDENTIFICATION_MODEL_ID);
  Serial.print("Device ID: "); Serial.println(val1);

  val1 = read_byte_data_at(VL53L0X_REG_PRE_RANGE_CONFIG_VCSEL_PERIOD);
  Serial.print("PRE_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
  Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

  val1 = read_byte_data_at(VL53L0X_REG_FINAL_RANGE_CONFIG_VCSEL_PERIOD);
  Serial.print("FINAL_RANGE_CONFIG_VCSEL_PERIOD="); Serial.println(val1);
  Serial.print(" decode: "); Serial.println(VL53L0X_decode_vcsel_period(val1));

  write_byte_data_at(VL53L0X_REG_SYSRANGE_START, 0x01);

  byte val = 0;
  int cnt = 0;
  while (cnt < 100) { // 1 second waiting time max
    delay(10);
    val = read_byte_data_at(VL53L0X_REG_RESULT_RANGE_STATUS);
    if (val & 0x01) break;
    cnt++;
  }
  if (val & 0x01) Serial.println("ready"); else Serial.println("not ready");

  read_block_data_at(0x14, 12);
  uint16_t acnt = makeuint16(gbuf[7], gbuf[6]);
  uint16_t scnt = makeuint16(gbuf[9], gbuf[8]);
  uint16_t dist = makeuint16(gbuf[11], gbuf[10]);
  byte DeviceRangeStatusInternal = ((gbuf[0] & 0x78) >> 3);

  Serial.print("ambient count: "); Serial.println(acnt);
  Serial.print("signal count: ");  Serial.println(scnt);
  Serial.print("distance ");       Serial.println(dist);
  Serial.print("status: ");        Serial.println(DeviceRangeStatusInternal);
}

uint16_t bswap(byte b[]) {
  // Big Endian unsigned short to little endian unsigned short
  uint16_t val = ((b[0] << 8) & b[1]);
  return val;
}

uint16_t makeuint16(int lsb, int msb) {
    return ((msb & 0xFF) << 8) | (lsb & 0xFF);
}

void write_byte_data(byte data) {
  Wire.beginTransmission(address);
  Wire.write(data);
  Wire.endTransmission();
}

void write_byte_data_at(byte reg, byte data) {
  // write data word at address and register
  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.write(data);
  Wire.endTransmission();
}

void write_word_data_at(byte reg, uint16_t data) {
  // write data word at address and register
  byte b0 = (data &0xFF);
  byte b1 = ((data >> 8) && 0xFF);

  Wire.beginTransmission(address);
  Wire.write(reg);
  Wire.write(b0);
  Wire.write(b1);
  Wire.endTransmission();
}

byte read_byte_data() {
  Wire.requestFrom(address, 1);
  while (Wire.available() < 1) delay(1);
  byte b = Wire.read();
  return b;
}

byte read_byte_data_at(byte reg) {
  //write_byte_data((byte)0x00);
  write_byte_data(reg);
  Wire.requestFrom(address, 1);
  while (Wire.available() < 1) delay(1);
  byte b = Wire.read();
  return b;
}

uint16_t read_word_data_at(byte reg) {
  write_byte_data(reg);
  Wire.requestFrom(address, 2);
  while (Wire.available() < 2) delay(1);
  gbuf[0] = Wire.read();
  gbuf[1] = Wire.read();
  return bswap(gbuf);
}

void read_block_data_at(byte reg, int sz) {
  int i = 0;
  write_byte_data(reg);
  Wire.requestFrom(address, sz);
  for (i=0; i<sz; i++) {
    while (Wire.available() < 1) delay(1);
    gbuf[i] = Wire.read();
  }
}

uint16_t VL53L0X_decode_vcsel_period(short vcsel_period_reg) {
  // Converts the encoded VCSEL period register value into the real
  // period in PLL clocks
  uint16_t vcsel_period_pclks = (vcsel_period_reg + 1) << 1;
  return vcsel_period_pclks;
}


ESP8266 unstable connection I try to flash an ESP12E microcontroller through an FTDI serial converter. It seems like the UART connection is a bit unstable, because when I try to flash it via esptool it often throws "Timed out waiting for packet header" error. Also when I thy to get the flash_id the same error occures at around 50% of the time. The simplier commands like get_mac and chip_id are working well.

I'm using an ESP module with wires soldered to its pads. It is put into a breadboard and it's connected to a USB-UART converter via jumper wires.

What could be the problem?

Power supply...

I designed a pcb for the ESP module, it works like a charm since then. Used a TC1262 regulator, a 100n ceramic and a 1000u electrolyte capacitor (maybe 100u would have been enough) very close to the Vcc and GND pins.

Seems like the ESP is really sensitive to the power supply stability.


I am looking into putting sound files onto an Arduino Nano without a microSD card I figured out how to install the sound onto the card from this site
https://github.com/charliegerard/dev-notes/blob/master/arduino/wavFilesWithoutSdCard.md
It says I need to use pin 11 on the Uno but would pin 11 on the nano work or not? I am getting these boards.
https://www.amazon.com/gp/product/B0713XK923/ref=ox_sc_act_title_3?smid=A2WWHQ25ENKVJ1&psc=1
Also, does anyone have good speaker suggestions, I'm going with these right now(https://www.amazon.com/CQRobot-JST-PH2-0-Interface-Electronic-Projects/dp/B0738NLFTG/ref=sr_1_6?dchild=1&keywords=speakers+arduino%5D%5C&qid=1607285501&sr=8-6)
I'm not sure if I'm giving enough information so just tell me if I need to provide you with more information.

Uno and Nano uses the same Atmel MCU, so pin 11 is the same on both.
And a for the speakers, Arduino CAN'T driver 8ohms load! You need a amplifier.


Serial.println won't format DEC This is weirding me out. So I wrote to the EEPROM and I would like to read from the address and format it in Base 10, err... Decimal. The normal number thingy that's not ASCII. But it keeps returning ASCII values when I write:
Serial.println(EEPROM.read(address), DEC).
Wait for the weird part, when I format in other bases like, say BIN, or OCT, it outputs in the correct base. Please help. Here's the full snippet of the tiny program.
#include <EEPROM.h>
int addr = 0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0){
    int rc = Serial.read();
    EEPROM.write(addr, rc);
    Serial.println(EEPROM.read(addr), DEC);
  }

}

I finally figured it out. Apparently, when I call Serial.read() and assign it to "int rc", It sort of converts the actual ASCII values into integer. So reading the number 3 from the Serial monitor and assigning it to rc stores 51 in rc. So the trick I found to that was to use
int rc = Serial.read()-'0'

That way, I am storing 51-48 which is, 3 (Since 48 is the ASCII value for 0).
Thanks.


Problem up loading to board I'm a newbee to Arduino programming and hoping someone can help me with this. These are the errors when uploading the proceeding sketch. Thanks in advance!

avrdude: stk500_rcv() : programmer is not
responding

avrdude: stk500_getsync() attempt 10 of 10:not in sync:

Problem uploading to board.

//www.RobotLinking.com
//2015.5.7
/************************************************/
#include <Servo.h>
/************************************************/
Servo myservo;//create servo object to control a servo
/************************************************/
void setup()
{
  myservo.attach(9);//attachs the servo on pin 9 to servo object
  myservo.write(0);//back to 0 degrees
  delay(1000);//wait for a second
}
/*************************************************/
void loop()
{
  myservo.write(15);//goes to 15 degrees
  delay(1000);//wait for a second
  myservo.write(30);//goes to 30 degrees
  delay(1000);//wait for a second.33
  myservo.write(45);//goes to 45 degrees
  delay(1000);//wait for a second.33
  myservo.write(60);//goes to 60 degrees
  delay(1000);//wait for a second.33
  myservo.write(75);//goes to 75 degrees
  delay(1000);//wait for a second.33
  myservo.write(90);//goes to 90 degrees
  delay(1000);//wait for a second
  myservo.write(75);//back to 75 degrees
  delay(1000);//wait for a second.33
  myservo.write(60);//back to 60 degrees
  delay(1000);//wait for a second.33
  myservo.write(45);//back to 45 degrees
  delay(1000);//wait for a second.33
  myservo.write(30);//back to 30 degrees
  delay(1000);//wait for a second.33
  myservo.write(15);//back to 15 degrees
  delay(1000);//wait for a second
  myservo.write(0);//back to 0 degrees
  delay(1000);//wait for a second
}
/**************************************************/

One of the first things to know about Arduinos is that that there are a lot of them – and a lot of tools for programming them. For your problem this means that the most likely reason for the problem you are having is a mismatch between the board your are using and the board your tools are set to upload to. Since you've said you're new to the Arduino I'm assuming that you're using the "official" IDE.

So, here are some things to try:

From the IDE main menu, choose Tools > Board and select your board, then
Choose Tools > Programmer and select an appropriate programmer for your board. Without knowing what board you're using and how you're connecting to it I can't offer more specific advice. However, if you Google for something like "beginner tutorial " you're likely to find an answer. Or more likely three answers. You'll need to look at the one that matches the OS you're using on your development machine.
You may also need to select the port that the Arduino is connected to.

If you've gotten this far and haven't solved the problem, here's what I'd do next:

Do a search on the exact error message you're getting – copy it out of the IDE and the paste it into your favorite search engine. Put quotes around the message so that you don't get a bunch of unrelated hits for your search.
Search for tutorials on the board and/or IDE vendor site.
Work through a tutorial from a good beginner's site. I like the materials the Adafruit folks have developed, but there are lots of good resources out there.
Post a question. When you do be sure to:

Describe your environment: the board you're using, the IDE you're using, the OS you're working on, how the board is connected to the development machine, and the basic settings of the IDE.
Explain what you've tried.
Describe, or better, include a screen shot or the actual text of the problem that you're seeing (like you did here).
For some problems it will also be useful to include the code. If you include the complete code then it is possible that somebody could try to actually reproduce your problem.


Modifying Arduino IMU library to rely on DSSCircuit's I2C Master Library For an Arduino project I am working on, I am trying to modify the SparkFun 6 Degrees of Freedom IMU Digital Combo Board - ITG3200/ADXL345 to support DSSCircuit's I2C Master Library (https://github.com/DSSCircuits/I2C-Master-Library). This is to combat the known issue of the Arduino Wire library to often get hung up while trying to run the EndTransmission function.

I'm new to this and do not understand how the terms 'slave address' and 'register address' and 'bytes you want to send' are different, if they are. I also do not understand how buffering works in the base IMU library. Any information on those would be appreciated, but is not the focus of my question.

I use the example code of the IMU unit...

#include <FreeSixIMU.h>
#include <FIMU_ADXL345.h>
#include <FIMU_ITG3200.h>
#include <Wire.h>
#include <I2C.h>

int raw[6]; // x y z yaw pitch roll

// Set the FreeSixIMU object
FreeSixIMU sixDOF = FreeSixIMU();

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

  delay(100);
  sixDOF.init(); //begin the IMU
  delay(100);
}

void loop() {
  sixDOF.getRawValues(raw);
  Serial.print(raw[0]);
  Serial.print(" x | ");
  Serial.print(raw[1]);
  Serial.print(" y | ");
  Serial.print(raw[2]);
  Serial.println(" z");
  delay(100);
}

And I changed the selected IMU library functions as follows:

// Writes val to address register on device
void ADXL345::writeTo(byte address, byte val) {
  I2c.write(address, val);
  // send register address
}

// Reads num bytes starting from address register on device in to _buff array
void ADXL345::readFrom(byte address, int num, byte _buff[]) {
  I2c.read(address, (byte) num);
  // sends address to read from
}

void ITG3200::writemem(uint8_t _addr, uint8_t _val) {
  I2c.write(_addr, _val);   // start transmission to device
}

void ITG3200::readmem(uint8_t _addr, uint8_t _nbytes, uint8_t __buff[]) {
  I2c.read(_addr, _addr, _nbytes);   // start transmission to device
}

And added the #include <I2C.h> statements to the headers files where applicable.

When running the example code, the serial output will not change values based on how I move the accelerometer, which makes me think I used the wrong slave address to read data from, or some other issue.

Can someone help me modify the IMU library to include DSSCircuit's Master I2C Library?

Thank you Stack Exchange Community!
John

EDIT:

Please see PersonAGem's edit below. Using the wire library is known to have arbitrary hangups, and in this example PersonAGem lists the edits I should make to the other libraries I am using as well as gives me the code I should use in my .ino.

I ask a new question about this topic here.

You are missing the rest of the code in reading operations. You are just requesting the data, no actually reading it from the device:

the original code of adlx345::read

void ADXL345::readFrom(byte address, int num, byte _buff[]) {
  Wire.beginTransmission(_dev_address); // start transmission to device
  Wire.write(address);             // sends address to read from
  Wire.endTransmission();         // end transmission

  Wire.beginTransmission(_dev_address); // start transmission to device
  Wire.requestFrom(_dev_address, num);    // request 6 bytes from device

  int i = 0;
  while(Wire.available())         // device may send less than requested (abnormal)
  {
    _buff[i] = Wire.read();    // receive a byte
    i++;
  }
  if(i != num){
    status = ADXL345_ERROR;
    error_code = ADXL345_READ_ERROR;
  }
  Wire.endTransmission();         // end transmission
}

would change to (if no mistakes made):

void ADXL345::readFrom(byte address, int num, byte _buff[]) {
  I2c.read(_dev_address, address, num) // request 6 bytes from device
  if(I2c.available() != num){  // device may send less than requested (abnormal)
    status = ADXL345_ERROR;
    error_code = ADXL345_READ_ERROR;
  }

  int i = 0;
  while(I2c.available())
  {
    _buff[i] = I2c.receive();    // receive a byte
    i++;
  }
}

you may need to force cast parameters between functions.

If for some reason you don't want the actual code and want to use another library, I'll suggest I2Cdev site with a well documented classes for adlx345 and ITG3200.

Edit:

This caused me no problem. That is the only 2 functions I changed:

// Writes val to address register on device
void ADXL345::writeTo(byte address, byte val) {
  I2c.write((uint8_t) _dev_address, (uint8_t) address, (uint8_t) val);
}

// Reads num bytes starting from address register on device in to _buff array
void ADXL345::readFrom(byte address, int num, byte _buff[]) {
  I2c.read((uint8_t) _dev_address, (uint8_t) address, (uint8_t) num);  // request 6 bytes from device
  if(I2c.available() != num){  // device may send less than requested (abnormal)
    status = ADXL345_ERROR;
    error_code = ADXL345_READ_ERROR;
  }

  int i = 0;
  while(I2c.available())
  {
    _buff[i] = I2c.receive();    // receive a byte
    i++;
  }
}

Arduino code used:

#include <I2C.h>
#include "FIMU_ADXL345.h"

ADXL345 acc = ADXL345();
int x=0,  y=0, z=0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  I2c.begin();
  delay(100);
  acc.init(ADXL345_ADDR_ALT_LOW);
  delay(100);
  Serial.print("Is ACC OK?: ");
  Serial.println(acc.status);
  Serial.print("Any Error code?: ");
  Serial.println(acc.error_code);
  Serial.println("********Print all register current values********");
  acc.printAllRegister();
  Serial.println("********END register print******");
  Serial.println(acc.getRate());
}

void loop() {
  // put your main code here, to run repeatedly:
  acc.readAccel(&x,&y,&z);
  Serial.print(x);
  Serial.print('\t');
  Serial.print(y);
  Serial.print('\t');
  Serial.println(z);
  delay(500);
}

Output given:

Is ACC OK?: 1
Any Error code?: 0
********Print all register current values********
0x00: B11100101
0x1D: B00000000
0x1E: B00000000
0x1F: B00000000
0x20: B00000000
0x21: B00000000
0x22: B00000000
0x23: B00000000
0x24: B00000000
0x25: B00000000
0x26: B00000000
0x27: B00000000
0x28: B00000000
0x29: B00000000
0x2A: B00000000
0x2B: B00000000
0x2C: B00001010
0x2D: B00001000
0x2E: B00000000
0x2F: B00000000
0x30: B10000011
0x31: B00000000
0x32: B11110101
0x33: B11111111
0x34: B00000011
0x35: B00000000
0x36: B11100101
0x37: B00000000
0x38: B00000000
0x39: B00000000
********END register print******
100.00
-12 4   230
-10 2   231
-11 3   231
-12 3   228
-10 3   230
-11 2   231
-12 2   229
-11 3   229
-10 3   231
-11 3   229
-10 2   230
-12 4   230
-12 3   229
-10 2   229
-13 4   230
-11 3   230
-10 3   230
-11 2   230
-11 4   229
-11 3   230
-11 3   230
-11 3   229
-12 3   229
-10 2   229
-11 3   230
-11 3   231
-11 3   230
-15 14  227
34  104 210
138 95  191
243 18  88
323 -15 74
280 -8  -2
263 -2  37
212 10  163
16  39  233
28  114 195
29  161 170
33  124 211
5   49  244
7   22  224
-10 3   229
-11 2   230
-12 2   230
-11 3   231
-12 4   228


What is the difference between declaring a variable outside of loop and declaring static inside loop? These are two ways I can hold a variable outside of loop (or any function).

First, I can declare it with global scope outside of loop:

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

int count = 0;

void loop()
{
    Serial.println(count);
    count++;

    delay(250);
}

I can also declare it static inside the loop:

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

void loop()
{
    static int count = 0;

    Serial.println(count);
    count++;

    delay(250);
}

What difference, if any, will this make?

The most basic difference is of scope.

In the first case, you are declaring a global variable. It is a variable that is accessible in every scope after its definition.

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

void inc();
int count = 0;

void loop()
{
    Serial.println(count);
    count++;

    inc();

    delay(500);
}

void inc() //Can edit the value of count
{
  count=count+1;
};

In the second case, you are declaring a static variable with local scope. The variable will persist for the entire program run similar to global variables, but will be accessible only in the code block it is declared in. This is the same example, with only one change. count is now declared as a static variable inside loop.

void inc();

void loop()
{
    static int count = 0;
    Serial.println(count);
    count++;

    inc();

    delay(500);
}

This will not compile as the function inc() does not have access to count.

Global variables, however seemingly useful, come with some pitfalls. These can even cause damage when it comes to writing programs that can interact with the physical surroundings. This a very basic example of something that is quite likely to happen, as soon as programs start getting larger. A function may inadvertently change the state of a global variable.

void setup()
{
    Serial.begin(9600);
}
void another_function();
int state=0;

void loop()
{
    //Keep toggling the state
    Serial.println(state);
    delay(250);
    state=state?0:1;

    //Some unrelated function call
    another_function();
}

void another_function()
{
  //Inadvertently changes state
  state=1;

}

Such cases are very hard to debug. This type of problem however, can easily be detected, by simply using a static variable.

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

void loop()
{
    static int state=0;

    //Keep toggling the state
    Serial.println(state);
    delay(250);
    state=state?0:1;

    //Some unrelated function call
    another_function();
}

void another_function()
{
  //Results in a compile time error. Saves time.
  state=1;

}


DC motor fan speed control with Temperature Sensor I used this circuit schematic for the project however, when DC Motor starts to work, temperature value is increasing abnormally high. How can I solve this problem? It shows abnormal high values like 70, 85 ,101 etc.

#define TEMPERATURE A0
#define fan 3
void setup(){
Serial.begin(9600);
pinMode(fan, OUTPUT);
}

void loop(){
float temp = analogRead(TEMPERATURE);    //Read the analog pin
temp = temp * 0.48828125;   // convert output (mv) to readable celcius

Serial.print(temp);
//print the temperature status
Serial.print('\n');
delay(1000);

 if (temp<=24){
  analogWrite(fan, 51);

  delay(1000);

}
else if (temp<=26 && temp>24){
  analogWrite(fan,122);

  delay(1000);

}
 else if (temp<=30 && temp>26){
  analogWrite(fan,223);

  delay(1000);

}
else if (temp>30){
  analogWrite(fan,255);

  delay(2000);

}
}

I am assuming that whatever temperature you are measuring is not rising when the motor is on.
I see that you are sharing the power/ground between your temperature sensor IC and the motor.  Motors are extremely noisy from an electrical viewpoint and it's almost certainly causing your temperature sensor to malfunction.
It would be best to separate the temp sensor power/ground connections from the motor power/ground connections completely.  Power the motor from an external supply instead of sourcing it from the Arduino.
Another thing that might help is to add some bypass capacitors as close as possible to the motor and to the temperature IC across the Vcc and GND lines.  This will help to smooth out the power in spite of the noise that the motor itself generates.  Generally you want at least one of two types, an electrolytic capacitor and a ceramic capacitor.  These are both inexpensive if you don't already have some on hand.  I'll suggest a 10 uF electrolytic and a 0.1 uF ceramic capacitor near both the motor and the temp sensor.


Use an ethernet shield and RFID rc522 together on a mega? I am using an Arduino Mega and I would like to connect a rc52 RFID reader and a network shield.  My problem is that both are set to use the same set of pins: 50 - 53.  Can I redefine the pins used so that I can use both at the same time?

Yes, I do think so. according to my Question with RFID and display it turned out that those pins are for serial communiacation. So I think it should work.
I can verify
 that it will work if you do use the ICSP headers MOSI/MISO/SCLK pins. Connecting those three with the RC552 as well as GND and 3V3. Also connect two other pins to SS and RST. This pins can be adjusted in the sketch on the Arduino.


Arduino UNO, using 5V and 3.3V I am newbie in Arduino (using UNO) and as I have 2 components that I wish to connected that one needs 5V and the other need the 3.3V, is it safe to connected them together next to each other?

If a component needs 5V it must be connected to 5V. If it needs 3.3V it must be connected to 3.3V.  Connecting a 3.3V component to a 5V supply is a sure fire way of destroying it.

Furthermore, since the Arduino's main chip is a 5V device, if you want to connect it to a 3.3V device you must use some form of level translation so that the 5V signals from the Arduino don't damage the 3.3V device. Also it may (though not always) be necessary to convert the signals from the 3.3V device to a level that the Arduino can understand (5V).


How can I make pinMode calls faster? I'm trying to use 3 pins as capacitive pins along side the Mozzi.

I had several attempts and so far the closest I had was using code from the ADCTouch library straight into the main code, but with the current implementation (removing averaging and taking less samples to speed things up) it's only fast enough to process 1 pin and I'd like to use 3.

Here is my implementation so far:

/*  Based on the Gain Example changing the gain of a sinewave,
    using Mozzi sonification library.

    Demonstrates the use of a control variable to influence an
    audio signal.

    Circuit: Audio output on digital pin 9 on a Uno or similar, or
    DAC/A14 on Teensy 3.0/3.1, or
    check the README or http://sensorium.github.com/Mozzi/

    Mozzi help/discussion/announcements:
    https://groups.google.com/forum/#!forum/mozzi-users

    Tim Barrass 2012, CC by-nc-sa.
*/

#include <MozziGuts.h>
#include <Oscil.h> // oscillator template
#include <tables/sin2048_int8.h> // sine table for oscillator

// use: Oscil <table_size, update_rate> oscilName (wavetable), look in .h file of table #included above
Oscil <SIN2048_NUM_CELLS, AUDIO_RATE> aSin(SIN2048_DATA);

// control variable, use the smallest data size you can for anything used in audio
byte gain = 255;

//ADC Touch setup
int sampleCount[3] = {0};
int values[3] = {0};

void setup(){
  startMozzi(); // start with default control rate of 64
  aSin.setFreq(4200); // set the frequency
}

void updateControl(){
  if(gain > 3){
    gain = gain - 3 ;
  }else{
    gain = 0;
  }
  //begin ADCTouch
  pinMode(A4, INPUT_PULLUP);

  ADMUX |=   0b11111;
  ADCSRA |= (1<<ADSC); //start conversion
  ADCSRA |= (1<<ADIF); //reset the flag

  pinMode(A4, INPUT);

  values[0] = mozziAnalogRead(A4);
  sampleCount[0]++;
  //end ADCTouch

  if(sampleCount[0] == 64){//wait for 64 samples
    if(values[0] > 500) {//did we get a touch with all these samples ?
      gain = 255;//amp it up
    }
    sampleCount[0] = 0;//reset count
  }

}

int updateAudio(){
  return (aSin.next()* gain)>>8; // shift back to STANDARD audio range, like /256 but faster
}

void loop(){
  audioHook(); // required here
}

The issue is as soon as do the pinMode calls for the second pin I'd like to use (A5) so I'm guessing pinMode needs to work faster. To use pinMode(INPUT_PULLUP) and pinMode(INPUT) calls for pins A4,A5 and digital 10, now can I write this using direct port manipulation ?

(I'm new to avr/arduino internals and slowly getting the grips with this).

First, figure out which port and pin you're using. Then, manipulate them.

DDRC &= ~_BV(PC5);
PORTC |= _BV(PC5);

...

DDRF &= ~_BV(PF5);
PORTF |= _BV(PF5);

...

DDRF &= ~_BV(PF0);
PORTF |= _BV(PF0);


Program arduino via USB while using a Bluetooth module (HC-06) I have my Arduino Nano connected to the HC-06 module (with the RX/TX pins).

My issue is that when I try to upload new code to my Arduino (via the Arduino IDE, through the USB connection) the Arduino IDE doesn't succeed.

I get this error:

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

I believe that it is just trying to upload the code to the HC-06 (instead of the Arduino). Is there a way to overcome this issue?.

Thanks.

Note: I found this entry https://stackoverflow.com/questions/27175937/arduino-program-upload-while-btooth-module-connected-avrdude-stk500-getsync indicating that it wasn't possible (that I need to unplug the module). I am trying to confirm it.

The link in question was correct... you do need to unplug it.

The Arduino's serial chip uses pins 0 and 1 to communicate with the ATmega 328 PU chip onboard, thus you have two independent devices connected to the same wires and both the Arduino main chip and the Bluetooth module are trying to communicate at the same time (rendering all data unreadable by the computer).


How to share/Reassign analog pin for two Adafruit libraries for two adafruit hardware I'm attempting to use the Adafruit BMP180 and Adafruit 16x2 RGB LCD Display together on the same Arduino Uno R1. Both the pieces of hardware and their libraries use Analog Pin 4 and 5. Is there any way to reassign the pins for one of the libraries so I can use both of the parts together?

Here are the libraries I am using:

Adafruit BMP180/BMP085:
https://github.com/adafruit/Adafruit_BMP085_Unified and https://github.com/adafruit/Adafruit-BMP085-Library

Adafruit 16x2 RGB LCD Display:
https://github.com/adafruit/Adafruit-RGB-LCD-Shield-Library

If they are using I2C (which i think they are), then it doesn't matter, because I2C is just a transfer protocol. In theory, you could have hundreds of devices using those pins, and have everything working fine. Just try using both, and tell me if anything doesn't work.


nodemcu pins + sensors reading values what are the SDA & SCL pins in NodeMCU? (Pins 20 & 21 in Arduino MEGA2560) I already implemented a simple project to read 2 accelerometers values from Arduino and send them through wifi to firebase database. I used Arduino Mega before for the same project and the sensors gave me readings between approximately -300 to 300. Now when I moved to NodeMCU the sensors became very sensitive and are getting values up to 65500+. And with a very small angle change the axis reading drop down to 20 or less.

I used pins D1 and D2 for SCL and SDA. Are the pins correct? And What about the reading values how to fix that?

The ESP8266 doesn't have a hardware Two Wire Interface. I²C is done in software, so you can use any 2 pins, as long as you specify them in your code using Wire.begin(SDA, SCL).

My guess would be that there's another problem. 65500+ sounds like an integer overflow, for example. ((uint16_t) -1 == 65535)


Building projects on the command line using the Bare-Arduino-Project template I'm trying to program an Adafruit Trinket using avr-gcc et. al. with the Makefile from the Bare-Arduino-Project on macOS Catalina.

I can build projects for standard boards like the Uno, but not for the Trinket. Everything works as expected using the "official" Arduino IDE (1.18.10). In the Bare-Arduino-Project Makefile I'm specifying the Trinket as:

BOARD_TAG         = trinket5
BOARD_SUB         = attiny85

I get an error from avr-gcc that mmcu is not defined. I assume this is because the command line tools aren't finding the Adafruit equivalent of boards.txt. When I look in the Arduino IDE package I don't find the Adafruit boards in boards.txt or anything that looks like the definitions for the Adafruit boards (despite having added them in the IDE).

Any ideas about how to set up support for the Trinket (or other third party boards) when using command line tools?

You  probably look at the wrong boards.txt:

# Trinket 5V Configuration
trinket5.name=Adafruit Trinket (ATtiny85 @ 16MHz)

this can be found in the boards.txt in the main directory

C:\Users\YOUR_USER_NAME\AppData\Local\Arduino15\packages\arduino\hardware

in the sub directory

\adafruit\avr

in the same main directory should  also be a folder named 1.8.2 (for ArduinioIDE 1.8.12) for the core files

if added via board-manager using this line in preferences/additional bord manager urls

https://adafruit.github.io/arduino-board-index/package_adafruit_index.json

If you did a manual installation check with this guide for pit traps.Details on using trinket with the avrdude command line can be found here


Two ports on Uno with ethernet shield I am making an Arduino mod-bus device and I want to make a webpage as well that will allow me to reset the unit if there is any issues remotely. To do this I would need the mod-bus to operate on port 502 and the webpage to operate on port 80. is it possible for the Arduino to support two ports? I am using an Uno with a Ethernet shield and the standard ehternet.h file with a Modbus library. Any suggestions or ideas?

 #include SPI.h
 #include VL53L0X.h
 #include Ethernet.h
 #include Modbus.h
 #include ModbusIP.h
 #include VL53L0X.h
 #include Wire.h

VL53L0X sensor;
EthernetServer server(80);

//Modbus Registers Offsets (0-9999)
const int SENSOR_Hreg0 = 100;

//ModbusIP object
ModbusIP mb;

short ts;

void setup() {
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  byte ip[] = { 192, 168, 1, 177 };

  Wire.begin();
  mb.config(mac, ip);

  // Add SENSOR_Ireg register - Use addIreg() for analog Inputs
  mb.addHreg(SENSOR_Hreg0);

  ts = millis();

  //Sensor setup
  sensor.init();
  sensor.setTimeout(500);
  sensor.startContinuous();

  //remote reset
    pinMode(13, INPUT);
    digitalWrite(13, LOW);

   // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Ethernet WebServer Example");

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  // start the server
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

}

void loop() {

  mb.task();

    //Webpage
    // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    bool currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          // output the value of each analog input pin

            client.print("Distance Measures ");
            client.print(sensor.readRangeContinuousMillimeters());
            client.print("mm");
            client.println("
");
            client.print("Filter Count:");
            client.print(-2.2*sensor.readRangeContinuousMillimeters()+404);
            client.println("
");
          }
          client.println("");
          break;
        }

      }

  //Modbus
  if (millis() > ts + 100) {
    ts = millis();

     mb.Hreg(SENSOR_Hreg0, sensor.readRangeContinuousMillimeters() );

     }
}}

Edit:
Note: The issue seems to lie somewhere in with the sensor, because when I run it with out have the sensor code in there is no problem but when I add it the issue starts again.

move the modbus refresh out of the if (client) condition
mb.begin() calls Ethernet.begin(). Do not repeat it in setup()
move client.println("</html>"); break; inside the if block before it
copy the rest of the detection of empty line from the WebServer example
stop() the client after response
change type of ts to unsigned long


How to use ITG-3500 evb I am trying to make motion capture and someone gave me these boards.

I think it's a test board for MPU 9500. I tried to google but I only found datasheets. What boards are these?

"ITG-3500 evb" is written on the back of the green board.
I think this is datasheet of green board maybe

"EV_ARM_XXAXA_D" is written on the back of the blue board.

The green board is an ITG-3500 (3 axis gyroscope) evaluation board of some form.

The blue board is some form of microcontroller evaluation board. It probably has one of the Atmel SAM chips on it since it mentions ARM.

That's about all you'll get from us I'm afraid, unless there is the highly unlikely situation that someone here happens to have the exact same boards as you.


Code is not running, servo does not even spin I am trying to run a program which works as follows:
An LDR is integrated in a box. A block is placed on top. This box is able to be rotated by a servo. The program is supposed to make the box turn until the block slides and lifts off from the LDR.
At that point the servo angle is stored and used to calculate the friction coefficient. Finally the answer to this calculation is printed on an lcd and the program repeats by first returning the box to the original state. The entire programs runs on Arduino and an Arduino Lotus. Why doesn't the servo rotate?
//servo
#include <Servo.h>

Servo myservo;
int previous_angle = 0;
int angle = 0;

//lightsensor
int lightsensor = 0;
int LIGHT = 800;
int DARK = 940;

//LED screen
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

void setup() {
  Serial.begin(9600);
  myservo.attach(6);

  pinMode(lightsensor, INPUT);

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  delay(100);
}

void loop() {
  int i = previous_angle;
  int lightStatus = analogRead(lightsensor);

  if (lightStatus >= DARK) {
    delay(300);

    while (int i = previous_angle) {
      i<=90;
      i = i+1;
      myservo.write(i);
      delay(45);
    };
  } else if (lightStatus < DARK) {
    for (int i = previous_angle; i>0;) {
      delay(300);
      int angle = tan(i);
      display.clearDisplay();
      display.setTextSize(1.5);
      display.setTextColor(WHITE);
      display.setCursor(0,0);
      display.println(angle);
      display.display();
      delay(300);

      myservo.write(0);
      delay(45);
    };
  }
}

For starters: this bit is a strange mixture of for and while syntax:
while (int i = previous_angle) {
  i <= 90;
  i = i + 1;
  myservo.write(i);
  delay(45);
};

It will compile, but probably not do what you want it to do. It should probably be:
for (int i=previous_angle; i<=90; i=i+1) {
  myservo.write(i);
  delay(45);
}

Also, previous_angle is never changed in your code after initialisation; it is always 0.
That also means that the for loop below will not do what you want (and that loop also doesn't increment i anywhere):
for (int i = previous_angle; i>0;)

There may be more; make the suggested changes first and see what happens.


How do I clear sim800L buffer? Let's say that I've tried sending an SMS directly from serial monitor or any kind of terminal. For whatever reason (syntax error, etc), my attempt fails. Now, I try sending it again, but this time by code (as seen on this site):
#include <SoftwareSerial.h>

//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 8

//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7

//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup() {
  //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(9600);
  delay(1000);

  Serial.println("Setup Complete!");
  Serial.println("Sending SMS...");

  //Set SMS format to ASCII
  serialSIM800.write("AT+CMGF=1\r\n");
  delay(1000);

  //Send new SMS command and message number
  serialSIM800.write("AT+CMGS=\"07194XXXXX\"\r\n");
  delay(1000);

  //Send SMS content
  serialSIM800.write("TEST");
  delay(1000);

  //Send Ctrl+Z / ESC to denote SMS message is complete
  serialSIM800.write((char)26);
  delay(1000);

  Serial.println("SMS Sent!");
}

void loop() {
}

The code sends not only the SMS within the code ("TEST"), but also the unwanted junk / remains of the previously unsuccessful sending attempt.
Is there a way to clear the module's buffer before sending a new message?
I guess I could restart the module before sending messages, but I was wondering whether there's a cleaner solution.
P.S. I apologize for the slightly misleading and irrelevant tags, but I can not use the nonexistent sim800L, which would be better suited for my question.

According to the SIM800 AT Command Set you can terminate the sending of an SMS part way through by sending ESC (character 27).

So you can begin your sketch by first sending a number of ESC to ensure that any pre-existing text input for an earlier SMS is abandoned.

serialSIM800.write(27);
serialSIM800.write(27);
serialSIM800.write(27);

Only one should be needed, but it is best to repeat it a couple of times in case the first one isn't taken. You should then do a CR/LF to make sure it's ready for the next command.

serialSIM800.print("\r\n");

However, your method of controlling the modem is crude at best and not particularly reliable. The modem sends back responses from all the commands you send it. You should be reading in those responses and checking that the commands you sent actually worked. That way you can know if a command hasn't been accepted because it is in SMS reading mode (no response within 1 second, say), and you can force an escape.


Decide on baud rate for a project using Arduino Uno R3 I am using an Arduino Uno R3 with the MPU 6050 to get motion data. Different example codes use different baud rates, without any proper explanation as to why.

So how do I know which baud rate is perfect for my project?

I most cases it doesn't matter!

In some cases the highest possible is preferred, as it prevents delays. That is when the buffer is full (when sending large amounts of data through the serial connection). As Serial.write will block until there is room in the buffer. In most cases this won't be an issue.

When running your arduino at slower speeds, you have to select a lower baudrate, or the micro-controller can't keep up.

When connection to other devices (e.g. GSM shield) using serial, that device may require a specific baudrate.


How can I run HC-05 on 8MHz Pro Mini? I run an Arduino Pro Mini on ATMega328 3.3V 8MHz, and I am unable to send data over HC-05 breakout board on this frequency, and on 5V 16Mhz, it has no issues.

The Arduino code is down below:

#include <SoftwareSerial.h>
#include <Wire.h>
SoftwareSerial BT(10, 11);
byte value;
unsigned long pmillis_bt = 0;

void setup() {
  Serial.begin(19200);
  BT.begin(9600);
}
///////////////////main///////////////////

void loop () {
  if (millis() - pmillis_bt >= 100) {
    byte Data[3];
    byte cmmd[20];
    int insize;
    char str[256];
    int i = analogRead(A0);
    value = BT.read();
    Data[0] = 'a';
    Data[1] = i / 256;
    Data[2] = i % 256;
    sprintf(str, "%d", i, Data[0], Data[1], Data[2]);
    Serial.println(str);
    if (value == 49) {
      for (int j = 0; j < 3; j++)
        BT.write(Data[j]);
      value = 0;
    }
    pmillis_bt = millis();
  }
}

Basically Arduino Uno Is working On 5v Voltage Level so you can Directly connect the HC-05 Bluetooth module to it using it 4 lines VCC,TX,RX,GND.

But in Pro mini 3.3 V level due to you need to Generic 3.3V To 5V 2 Channel Logic Level Converter Bi-Directional Module

using this you can easily convert the vlotage level.

if you have to make using simple component also using

SparkFun Logic Level Converter - Bi-Directional


Which interrupts are enabled when programming an ATTiny85 with Arduino IDE? I have programmed a tiny85 using the Arduino IDE. I am using the pulseIn() function. Wrapping it in noInterrupts()/interrupts(); appears to make the function more consistent. This would imply that interrupts are running.

Which interrupts are running? Can I disable them?

I am using the analogWrite() function to pins that have PWM support. Disabling the interrupts for a "long" time does not seam to effect these, this implies the PWMs are producing the analogue signal in hardware and so interrupts are not required.

(I know I can improve the code by not using pulseIn and using interrupts, however the question I have at the moment is which interrupts are running when I am not explicitly enabling any.)

The only interrupt that is always running is the one which generates the count for millis() and micros(). Disabling interrupts disables your ability to keep track of time and use delay().

Timer interrupts are also used by the tone() function and for sending / receiving serial data if the chip has a UART.

Disabling interrupts would also affect the use of external interrupts and pin change interrupts should you be using them.

It sounds, from your brief description, that you would only be effecting the use of millis() and delay() since you aren't using the other systems that use interrupts at all.


Where is CLKPR located on Ubuntu 16.04 with Arduino 1.8.3 I would like to see the definition of CLKPR. I guess that similarly to PORTB and other registers, it should be defined by the toolchain? (see Where is PORTB defined? )

Am I right?
Where should I look for this toolchain on Ubuntu 16.04? I tried locate and find commands in terminal with various strings relating to the toolchain expected path / files, but could not find it (tips and tricks on how I may look for such paths in the future would be welcome ;) ).

grep is the command you want:

foo@bar:~/arduino-1.8.2$ grep -r CLKPR .
Binary file ./hardware/tools/avr/avr/lib/avr35/crtattiny167.o matches
Binary file ./hardware/tools/avr/avr/lib/avr35/crtat90usb82.o matches
Binary file ./hardware/tools/avr/avr/lib/avr35/crtatmega8u2.o matches
...
Binary file ./hardware/tools/avr/avr/lib/avr5/crtat90pwm161.o matches
Binary file ./hardware/tools/avr/avr/lib/avr5/crtatmega649p.o matches
Binary file ./hardware/tools/avr/avr/lib/avr5/crtatmega168pa.o matches
./hardware/tools/avr/avr/include/avr/io90pwm216.h:#define CLKPR   _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/iom329.h:#define CLKPR   _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/iom165p.h:#define CLKPR   _SFR_MEM8(0x61)
...
./hardware/tools/avr/avr/include/avr/iom48p.h:#define CLKPR _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/iom644pa.h:#define CLKPR _SFR_MEM8(0x61)
./hardware/tools/avr/avr/include/avr/ioa6289.h:#define CLKPR _SFR_IO8(0x3C)
./hardware/arduino/avr/bootloaders/caterina-Arduino_Robot/Caterina.h:       #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
./hardware/arduino/avr/bootloaders/caterina-LilyPadUSB/Caterina.h:      #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
./hardware/arduino/avr/bootloaders/caterina/Caterina.h:     #define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))

So it's defined in the IO header for the chip you are using (hardware/tools/avr/avr/include/avr/io[chip].h). So for the '328p that's hardware/tools/avr/avr/include/avr/iom328p.h.


Simulate 9 pin joystick output I have built this little setup, which is supposed to record and replay input from a classic 9 pin Joystick. I connected the 9 pin connectors with the Arduino, read the input on the left side from the Joystick and then pass it to the right side by setting the corresponding pins to high.

It does work and I can play games on the Commodore 64.
However, I noticed that with this setup, current is passed to the Commodore 64, which is very likely harming the machine a lot (I stopped immediately after noticing).

So my question is: how do I need to modify this setup so that no current is going from the Arduino to the Commodore 64 anymore?

Picture of the setup

Any advice is greatly appreciated, thanks in advance.

I would isolate the two devices using opto-isolators.

simulate this circuit – Schematic created using CircuitLab

Turning the output ON will illuminate the infra-red LED in the opto-isolator which turns on the photo-transistor connecting the input to GND. Both devices are then completely galvanically isolated (unless of course you take power from the C64 for the Arduino).

Another option, if you don't care about galvanic isolation, is to just use a simple transistor (small signal NPN or logic level N-channel MOSFET) to make an Open Drain output:

simulate this circuit

Again, set the output HIGH and the transistor will turn on connecting the C64 input to ground.


How to program AVR in Mac OS X? In our college we are using a module developed by IIT Bombay (called FIREBIRD V[ver 5]). It has ATmega2560 and ATmega8 microcontrollers (master and slave) with bootloader.

The staff uses AVR Studio for programming. But since AVR Studio is supported only on Windows (and I have a Mac), I was looking for AVR programming in Mac. I downloaded Crosspack AVR. But I don't know how to proceed after this point. Also I downloaded TextWrangler (because I was told auto-suggestion is not available in TextEdit).

Also I have downloaded the Arduino IDE, and I don't know what is required or how to configure it to program AVR microcontrollers.

I searched on the web and nothing is clear (mostly they all depend on something to do with terminal and the command line).

I don't have Xcode installed in my Mac (I saw a relatively easy tutorial on how to set up Xcode for this purpose) and the file is 4GB. I am trying to work around using Xcode, but if it's the only nice way do let me know!

Pertinent suggestions would be helpful.

If you don't want to use the Terminal and the command line, the Arduino IDE is your best option. Get yourself an AVR programmer (or an Arduino Uno to serve as programmer, with the ArduinoISP sketch uploaded), and code on it.

Then connect your Arduino to your module via SPI. Select the correct processor and port.

You can now upload the sketch:


What are some "must-have" sensors or shields for an Arduino robot or motor? I am starting to learn Arduino and wanna make some projects.which components will  I have to buy?please help me.

It largely depends on your interests but since you've mentioned robotics, a motor shield, motor power supply, and one or a couple of hobby servos or DC motors will get you started on learning about controlling mechanical motion. You may be able salvage a DC motor from something else, like the vibrator motor from a dead cell phone.

If you want to start inexpensively, a few LEDs and a ~200 Ohm resistor for each one, and a couple of light or temperature sensors will give you plenty to play with. It's amazing how much real-world data you can collect and infer from a couple of well placed temperature sensors.

LM34 and LM35 are inexpensive and easy to use analog thermo-sensors that read directly in 0.01 Volts / degree (Fahrenheit and Celsius respectively), so only minimal arithmetic conversion is required (because along the way, you'll learn about Analog to Digital conversion, too).

Get some experience with those simple parts, and the coding to make them useful, and you'll have a much better idea of what you want to do next and what you'll need to acquire to do it.