How do I make a motor spin every 10 minutes? I am new to Arduino, please don't be harsh. I want to make a motor spin at every x amount of time (Lets say 10 minutes). Once the program is started, I want it to start the motor (stop after 10 seconds), and every 10 minutes, it continues the process. Is it possible to make it?,

The simplest option is to use delay() to implement the waits:
void loop() {
    turn_motor_on();
    delay(10000);  // 10 seconds
    turn_motor_off();
    delay(600000);  // 10 minutes
}

Since these long numbers may be difficult to read, you can make them
more readable by defining some units:
const unsigned long second = 1000;
const unsigned long minute = 60000;

Then you can for example delay(10 * minute);
Beware there is a trap if you try to do arithmetics with integer
literals. The following:
delay(10 * 60 * 1000);  // BUG!

will not work on most Arduinos, as the multiplications will be
performed on the int data type, which can only hold numbers up to
32,767. It is safer to use either explicitly typed constants (unsigned long is the appropriate type for delays) or integer literals typed with
the suffix UL (which stands for “unsigned long”).
Note that the Arduino will do no useful work while delaying. If you want
to do any kind of work during the delay, see the “Blink Without Delay”
Arduino example.


"EVERY_N_MILLISECONDS" One of the FastLED examples that I've seen was using code that looks like this:

  EVERY_N_MILLISECONDS( 300 ) { transition_step(); }

I've copied it and successfully used it in the same context - but I have no idea what it is or how it works.

A Google search finds no reference anywhere at all.

I'm still a beginner with C but this looks like a Define to me - all being in uppercase - is it defined somewhere in the FastLED library?

Yes, it is defined in the FastLED library.  It is a preprocessor macro which is replaced by a block of code when compiled:

It is a very convoluted bit of preprocessing code that is difficult (even for me) to follow through with lots of concatenations and multiple layers of definition, so my advice is to just not worry about it and just use it.

If you want to try and decypher it all it's in the file lib8tion.h in the FastLED library.


Multiple external power sources and one Arduino really noob question..
I am thinking of using a 12v power source and a 5v power source as an external power supply for my 5v relay (and some other stuff that I might add up to my project that will need 5V) and the 12v is for my 12V solenoids.
Is it right to connect all ground wires to the ground of the Arduino?
I am really sorry that I have to ask this question cause all tutorials I see online are only connecting one external power supply to their Arduino.
Any form of correction is highly appreciated. Thank you so much

Besides connecting all the grounds, a "good idea" whenever working with solenoids or magnetic (as opposed to solid state) relays is to add protection against inductive kickback, which can create really high voltages (hundreds of volts) when the current through an inductor changes suddenly. (The voltage is the product of the inductance and the rate-of-change of the current.)  The protection is simple:  Put a rectifier diode across each coil, with the arrow pointing to positive (reverse-biased).  The rectifier has to handle a big spike of current as well as the high voltage, so use something like 1N4004.
This protection will reduce the likelihood of spikes causing mysterious state changes in your circuits.


SSID was not declared in this scope so I am new to arduino and coding in general, I am trying to use the arduino to remotely survey plants, I am using this guide: https://create.arduino.cc/projecthub/arduino/plant-communicator-7ea06f. The entire code is:

#include <WiFi101.h>
#include<WiFiSSLClient.h>
const char* ssid = SKY1C9D0;    //  your network SSID (name)
const char* password = SYDTSTQR;  // your network password
String httpsRequest = https://hooks.zapier.com/hooks/catch/2821422/84ehn1/;
// your Zapier URL
   const char* host = "hooks.zapier.com";
WiFiSSLClient client;
void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(2000);
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  while (WiFi.begin(ssid, password) != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.println("WiFi connected");
}
void loop() {
  float temperature = 22;
  int moisture = 150;
  int light = 40;
  String warning = "This is a warning message";
  warning.replace(" ", "%20");
  send_email(temperature, moistue, light, warning );
  delay(20000)
}
void send_email(float temperature, int moisture, int light, String warning)     {
  // convert values to String
  String _temperature = String(temperature);
  String _moisture = String(moisture);
  String _light = String(light);
  String _warning = warning;
  if (client.connect(host, 443)) {
    client.println("POST " + httpsRequest + "temperature=" + _temperature +                 "&moisture=" + _moisture + "&light=" + _light + "&warning=" + _warning + "     HTTP/1.1");
    client.println("Host: " + String(host));
    client.println("Connection: close");
    client.println();
    delay(1000);
    while (client.available()) { // Print on the console the answer of the server
      char c = client.read();
      Serial.write(c);
    }
    client.stop();  // Disconnect from the server
  }
  else {
    Serial.println("Failed to connect to client");
 }
}

The error is specifically highlighted here:
    const char* ssid = SECRET_SSID;    //  your network SSID (name). The error is that the ssid has not been declared.
I am unsure of what to do to fix this and any other possible errors that have gone unnoticed. I would highly appreciate any help or guidance.
Thank you

A problem in the include file on the line previous could cause the following line to be misinterpreted. To test that try moving the ssid after the password and see if the error changes. Obviously make sure all strings are properly quoted.

#include <WiFi101.h>
#include <WiFiSSLClient.h>

const char* password = "SYDTSTQR";  // your network password
const char* ssid = "SKY1C9D0";    //  your network SSID (name)
String httpsRequest = "https://hooks.zapier.com/hooks/catch/2821422/84ehn1/";


Anything wrong with this code? Sorry for any grammar mistakes. It's my second language.

I had a little test with my Arduino Uno R3 I connected 2 buttons to power , GND using 10k resistors and pins 2 and 4.
I connected piezo to power and ground.

When you pressed a button1 then you should hear 'c' tone,
but when I pressed the second button nothing happend and I don't understand why?

Here is my code below:

const int buttonPin2 = 4;
const int buttonPin1 = 2;
const int piezopin =  6;

int buttonState1 = 0;
int buttonState2 = 0;

void setup() {

  pinMode(piezopin, OUTPUT);
  pinMode(buttonPin2,INPUT);
  pinMode(buttonPin1, INPUT);
}

void loop() {

  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);

  if (buttonState1 == HIGH) {
    tone(6,261.63,500);

  } else {

  }
  if (buttonState2 == HIGH) {
    tone(6,392.00,500);
  } else {

  }

Try calling noTone() after the tone is played. This is a kind of "reset" for the pin.

Also, you forgot a } at the end of your code.

If these didn't solve your code, then it most probably is an electric problem.


Cannot read modbus data repetitively I try to communicate with 2 RS485 sensors (pH and EC), but I have some troubles with my code. First, I tried to get data from just one:

The function in charge of request sending:

String GET_probe(String probe){

if(probe == "pH"){
Serial.println("Sending request pH...");
digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
byte  RTUrequest[] = {0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x85, 0xDB};
RS485Serial.write(RTUrequest, sizeof(RTUrequest));
}

if(probe == "EC"){
Serial.println("Sending request EC...");

digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
byte  RTUrequest[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
RS485Serial.write(RTUrequest, sizeof(RTUrequest));
}

RS485Serial.flush();
RS485Serial.listen();
}

The function in charge of reading sensor's answer:

void ReadRx() {
     digitalWrite(modbusModuleRE, RS485Receive);
     digitalWrite(modbusModuleDE, RS485Receive);
     if(RS485Serial.available()) {
     Serial.print("Answer: ");
      for(int i=0; i<7; i++){
          String myByte = String(RS485Serial.read(), HEX);// Read the byte

          if (myByte.length() == 1)
          {
            myByte = "0"+myByte;
          }
          modbusHexBuffer[i] = myByte;

          Serial.print(myByte);
          Serial.print(" ");
      }
      Serial.println();
    }
   }

And the loop, sending the request each 5s:

void loop(){

  static uint32_t ts = millis();

  if (millis() - ts >= 5000) {
      ts = millis();
      GET_probe("pH");
  }

ReadRx();
}

The loop runs fine once and fails the second time, as shown in terminal. Can you tell me why and help me to fix it?

Sending request pH...
Answer: 00 03 02 05 78 86 f6
Sending request pH...

I have found why !!!

1st: buf[8] instead buf[7] in declaration
2nd: reinit byte buf[8] before EC request part.

So the code who works fine is:

byte buf[8];
void loop(){

      Serial.print("pH: ");
      digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
      digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
      byte  pHrequest[] = {0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x85, 0xDB};
      RS485Serial.write(pHrequest, sizeof(pHrequest));
      RS485Serial.flush();
      digitalWrite(modbusModuleRE, RS485Receive);
      digitalWrite(modbusModuleDE, RS485Receive);
      RS485Serial.readBytes(buf, 8);
     Serial.print(buf[3], HEX);Serial.println(buf[4], HEX);

byte buf[8];

      Serial.print("EC: ");
      digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
      digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
      byte  ECrequest[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
      RS485Serial.write(ECrequest, sizeof(ECrequest));
      RS485Serial.flush();
      digitalWrite(modbusModuleRE, RS485Receive);
      digitalWrite(modbusModuleDE, RS485Receive);
      RS485Serial.readBytes(buf, 8);
      Serial.print(buf[3], HEX);Serial.print(buf[4], HEX);Serial.print(buf[5], HEX);Serial.println(buf[6], HEX);

Serial.println();

}


5V 10A 4 channel relay to 2 lights15W light in series in 220V AC supply I am trying to setup my first relay module with live environment. I have attached the relay module image below.

Which I am using to control 4 devices in my switch board as follows:

Fan (working fine),
6w celling LED panel (2 connected in series) (Working fine)
15w celling LED panel (2 connected in series) (Sometimes work sometimes don't)
Spotlights 3 lights in series and some LED strips connected to it (Sometimes works sometimes don't.).

I have cut one wire which is connected to main normal mechanical switch WHICH IS NOT A HOT WIRE its just the another wire connected to the button.

But I am not sure why its not working? Do I need to connect neutral to the another end of the relay. As I have only 2 wires connected to the relay for each of the switches. Here is a screenshot of specifications 15watt LED panel which is connected to my house, if this can help to understand better.

If I connect Neutral on the first pin of relay and when I close the relay switch, do the current will go into the neutral wire as well?

If I keep my 3w spotlights ON or more then 3-4 hours and try to close the relay on connected to it. The relay LED light for that connected relay goes OFF but the light don't. Seems like the mechanical relay is not getting enough power to move the mechanical relay off.

I want to know why this is happening? And how can I solve this issue? Attaching a neutral (earth) wire will help to reduce this? But if connect neutral to first (off side of relay) pin, then will get the current?

Any suggestions will be helpful. Also I added 3.3v from NodeMCU to VCC (instead of jumper) pin. But that is also not helpful.

You need to connect Vin from NodeMCU (Raw 5V from USB) to Vcc on the relay board.

And as stated in the comments, the relay need 5V for operating reliable.

In has the same problem, two LEDs and a resistor. To enhance it would be to replace the indicator LED (DS1-4) with a wire.

2 x LEDS á ~1.8V and a resistor á ~1.4V = 5 Volt.

1 x LED á ~1.8V and a resistor á ~1.4V = 3.2 Volt.


Is there any way I can connect the RAM of a computer to Arduino? I was thinking about a way to reuse the RAM of my old computer on my Arduino board. I was thinking about some peojects using neural networks, and more RAM would let the Arduino use more neurons.

So that's my question, how could I do that? Maybe soldering some cables to Tx/Rx pins and creating and interface between the board and the memory?

No, you can't connect your normal desktop computer memory to your Arduino. For a number of reasons:

Computer memory (at least for the past 20 years) is DDR SDRAM. That's Synchronous Dynamic RAM. It requires very strict timing and synchronous (clock based) data transfers with clocks measured in the hundreds of MHz - something the Arduino cannot do.
You need lots and lots of I/O pins to interface with SDRAM. I mean, just look at all those pins - how would you connect all those up to a little Arduino?
Being DRAM you need to use quite a complex process to keep the data refreshed and stop the capacitance of each cell from draining away. Yes, that side of things is do-able, but not child's play.

The only way you will be able to interface DDR SDRAM with an Arduino is through some intermediate interfacing system that can do all the above for you. Your best candidate is to design an SPI to DDR conversion chip using an FPGA and Verilog or VHDL. That way you can communicate with the FPGA using SPI (or you could choose I2C if you like, or a simple 8-bit parallel protocol) and the FPGA then does all the grunt work that the Arduino isn't capable of.

However, while you're at it, you may as well put a CPU core in the FPGA (e.g., NIOS II or something) and do away with the Arduino altogether...


How can I dim a 10w LED? I'm trying to dim a 10w LED via Arduino PWM.

This is the LED that I have: http://www.banggood.com/10W-Warm-Pure-White-High-Brightest-Save-Power-LED-Light-Lamp-p-88169.html

Without knowing much about this stuff, I bought this (namely because it had LED, DIM, and PWM in its name): http://www.ebay.com.au/itm/121437119430?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

I can't get the eBay dimmer to work for love or money.  When I connect it to ground directly on the battery terminal, it goes off, which means the dimmer circuit is working.  I don't even know where to start with MOSFET dimming solution, but I think that the IRFZ44N MOSFETs are the wrong ones because they won't turn on with 5v power (they need 10v or something, but those are the ones I have on hand).

I can't seem to find any good guides on how to do this after stacks of googling, and to be honest, I don't even know if those LED's can be dimmed in the first place.

What do I need to make this happen?

Well, it appears that your driver should do that for you. Since you already have the MBI6651 driver, read its datasheet and so you can get a guess on how it should work:

attach a 9-35V supply to the Vin-GND terminals. I suggest to use at least 12V
attach the LED to the terminals LED+ and LED- (remember the polarity!)
attach a transistor to pull down the pin DIM
send a PWM signal (frequency between 100Hz and 1000Hz) to the transistor and you should see the LED light up and then dim

If it works then you can try to send to DIM directly th PWM signal, but personally I don't recommend so (unless the board already have the transistor)

EDIT:

How to attach an nMOS to the DIM pin. Since the pin is internally pulled up, you don't need any pullup. So you just need an nMOS. I suggest you to use a SOT-23 logic level nMOS connected this way:

no external components (as long as the nMOS supports 5V on the gate, but every discrete mosfet should). As for the nMOS, I prefer the SMD case because it is easy to solder also on perfboards (just use three pads forming an L shape and you'll see that you can easily solder it). Just choose any n-channel mosfet with a maximum threshold voltage of 2V or less and you are done


Do we really need to upload Arduino bootloader for new Atmega IC I am using Atmega328p in my circuit. I will be programming this IC using Arduino. But because this is a PCB, so I will programming using USBasp programmer. So before uploading code as upload using programmer, I will select my arduino board in board select menu and then I will select USBasp as my programmer. But I want to know that is it really necessary to burn bootloader on a new Atmega328p IC. On some page, they say you do not require it. But some say, its necessary because you will be using Arduino functions like Serial.Begin() etc.

So I want to know what does this bootloader contains. Do I really need it. Can I directly upload my code using programmer. Can anyone please explain this to me.?

No, you do not need the bootloader for your chip to function.  The bootloader is merely a convenience.

If you are programming through USBasp you don't even need it on a "normal" Arduino board.

All it does is allow you to program through the UART interface (or USB interface in the case of ATMega32U4 boards). If you don't want to do that then you don't need the bootloader.

If you do not provide a UART interface to the user that can be connected to then the bootloader would be pointless anyway since you cannot communicate with it.


Reading from software serial with an interrupt I want to perform a serial read using software serial with Arduino. I am looping for my normal tasks, but whenever something is received on the software serial pins I want to perform a read operation and based on the character received, I want to run a function in the loop.
I think this is possible with interrupts only. But I can not see any documentation or help on how to perform this.
How to write an ISR for this task?

You can't do it directly with an interrupt. SoftwareSerial already uses an interrupt to do the actual reception - the received byte being placed in a circular buffer.

The only thing you could do would be to modify the source code for SoftwareSerial so that instead of storing the byte in the buffer it calls your custom code instead.

Ok, so you're NOT using SoftwareSerial, you're using (something which I have never heard of) "NeoSWSerial". That has the ability to attach an interrupt (by adding it to the reception interrupt ISR), and the README.md file with that library gives you an example of how to use it:

#include <NeoSWSerial.h>
NeoSWSerial ss( 4, 3 );

volatile uint32_t newlines = 0UL;

static void handleRxChar( uint8_t c )
{
  if (c == '\n')
    newlines++;
}

void setup()
{
  ss.attachInterrupt( handleRxChar );
  ss.begin( 9600 );
}

So just read the character in there, set a flag to say you have a new "mode" arrived, and in your loop react to that flag and run the right function for that mode.

If you want to terminate a mode early you will have to program your modes to also react to the "new mode" flag and terminate. The interrupt cannot do that for you.


Serial.write displaying repeating output from Xbee communication I want to use xbee's to communicate between two different arduinos.  I'm using this tutorial as a guide to setup my xbee's. I've already used XCTU to setup one xbee as a router and another as a coordinator (both in ZIGBEE AT mode).  I used XCTU's terminal feature to verify that info was being sent and received properly.

Basically, I have both arduinos connected to the same PC via USB cables, but the communication is taking place through the Xbee's.  I also made sure to disconnect the TX & RX wires when uploading the sketches to avoid an AVRDUDE error.

I wanted to test the communication by sending a "hello world" message once every five seconds, from the router to the coordinator.  To do this, I wrote the following code:

//Code for Arduino attached to Xbee in Router AT mode
void setup(){
 Serial.begin(9600);
}

void loop(){
  Serial.println("Hello World!");
  delay(5000);
}

and

//Code for Arduino attached to Xbee in Coordinator AT mode
void setup(){
  Serial.begin(9600);
}

void loop(){
  if (Serial.available()>0){
    Serial.write(Serial.read());
  }
}

I checked the serial monitor for the arduino connected to the router, and it does exactly what I expected to see:  a new Hello World message once every 5 seconds.  However, the serial monitor on the arduino connected to the coordinator does not produce the desired effect:  the "hello world" message instantly displays the message over a hundred times per second and repeats without end, each time on a separate, new line.  Sometimes, when I turn the serial monitor on, the message instantly appears with a few repetitions before displaying some strange characters and stopping altogether.

I'm not sure if the problem is with the serial monitor or with the xbee.  Any help with this problem would be greatly appreciated.

Code is correct and it does what it is asked to. The receiver code reads the RX pin of arduino which is connected to the Xbee. The same pin is used by the FT232 interface IC to send data to your computer through USB.

The "hello world" you send is received by the Xbee and is send to microcontroller and FT232 at same time as that pin is shared between them. Thus the "hello world" will be seen in serial monitor, first time from Xbee and second time, from Serial.write(Serial.read()) of the program.

Also check whether the settings are correct from this tutorial, as Xbee will not be configured as P2P.


Can I use Serial.println() in a class? I'm trying to convert a class header file from another c++ project to arduino, which in my mind involves replacing cout with Serial.println.

When I try to recomplile with all of these changes, I get this error from the compiler:

error: 'Serial' was not declared in this scope
     Serial.print(p[i]);

Can someone explain this to me?

You have to #include <Arduino.h>, or compile with the -include Arduino.h flag. The Arduino IDE normally does that for you, but you have to do it yourself if you are working outside the IDE.

There are a couple of Arduino Makefiles floating around the Web which, just like the IDE, take care of this for you.


How to access 315mhz signals from household devices, with an arduino 315mhz kit? Background:

I am looking into automation and I have realized that many of the devices I have around my house transmit 315mhz to their specific controllers.  I know this from reading the labels on the back that say 315mhz

Question:

Is there a way I can use a 315mhz receiver with an arduino to view the signals and log the data based on what happens and mimic certain actions with the transmitter?  In other words can I program the reciever to display every bit passed through 315mhz that is in range?

I know the virtual wire library parses the data before I receive it, but I don't know to what extent?  If I just dedicate the arduino to watch that pin and print results will that tell me what is being sent?

Thanks Very Much,

Joel

The Short Answer:

In theory it is possible to do what you are asking.
There are examples of using an Arduino to send and receive messages at 315 MHz. Such as this example.

Although these devices might not even be compatible with the ones you are using. They may be modulating their signal differently or framing their data differently or at different baud rates or encoding bits differently or a number of other fundamental differences that would make them incompatible.

The Long Not Quite An Answer:

There is more to the problem than just being able to get bits at 315 MHz.

For one you would need to know how the bits are encoded. See some of the answers on this post.

Even if it was a simple high low stream of even width bits. You also need to know what baud rate the bits are being transmitted at so you can sync with it. (Consider 4800 vs 9600 baud, slow I know but just an example. You just got a bit stream, was it 1010 at 4800 baud or 11001100 sent at twice the speed of 9600.)

Not to mention that the lowest level of data is probably not just a stream of bits, but is probably framed in some way and grouped into a byte/bytes. Or has a leader to help lock onto the signal.

Even once you are getting reliable data you would need to know the data structure. Is the data arranged in packets? Do they have a packet header? Does the header contain these packet destination address? Where in the header is this data? How is  the data apart from the header structured? What does it mean?.

Knowing the answers to these questions defines, or is defined by, the protocol that is being used by the transmitter (as others are saying in comments.) But these are only a few simple questions that start to define a protocol. Often this information is difficult to come by. Often in the case of proprietary protocols it is very very difficult.


How do I pull chip select pin up and down, when I have CAN shield and Newhaven Display 4.3CTP-SHIELD-N share the same chip select pin(10)? I am currently working on an Arduino project, which must be able to listen to the data going through CAN bus and display it on the Touchscreen LCD Newhaven Display 4.3CTP-SHIELD-N.

Problem is that Sparkfun CAN shield and the LCD shield share the same chip select (CS/SS) pin 10. I've tried changing the chip select of the CAN shield by changing values in library headers, but it did not work and now I think that I should pull pin 10 low, when executing CAN code, then pull it up for the CAN shield. Afterwards, do the same for the LCD shield, but I do not know how to write the code for that. Is this the right way to think about the problem or am I missing something?

At this point, I am very confused because some people say that, if two shields have same chip select pin, it's impossible to stack them. Others claim that they succeeded in stacking two shields like that.

What other methods are there for stacking two shields with the same chip select pin?

I am using this CAN library: https://github.com/sandeepmistry/arduino-CAN/blob/master/API.md

This LCD library: https://github.com/NewhavenDisplay/FTDI_FT801

You will have to use a different chip select pin for one of the shields.  You should do it to the display shield since that goes on top.

Change the code to use a different chip select pin for the display shield
Break or cut off pin 10 from the display shield, and solder a wire from where pin 10 was to your newly chosen chip select pin.


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

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

here is the code--

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

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

void loop()

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

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

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

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

  }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


What are the environmental requirements of an Arduino? I'd like to use an Arduino Yún in a somewhat outdoor environment (in a metal box on a truck).  I think I've seen that the temperature requirements of the Uno are -40 °C to +85 °C, but I can't find that information about the Yún.  It would be nice to know where to find information about the temperature and humidity safe working requirements for every Arduino model.

The AtMega32u4 (the chip that drives the Arduino Yun) has an operating requirement of -40 to +85, so if you go outside that range, you will definitely void warranty (which is not to say it will break, of course!). See datasheet at http://www.atmel.com/devices/atmega32u4.aspx

A datasheet for the AR9331 seems to say that it only works down to 0°C ( http://www.eeboard.com/wp-content/uploads/downloads/2013/08/AR9331.pdf page 305, "Commercial Case Temperature") - this seems awfully high for a minimum temperature.

While that does not mean that, inside that range, you are safe, I would GUESS that you probably are - I would guess that the AtMega32u4 or AR9331 is going to be the most delicate part in there.

Of course, to get a definitive answer, you (or someone) would have to check the specs on each part.


433MHz transmitter and receiver pair doesnt work I have a pair of 433 MHz transmitter and receiver:

Transmitter is connected to Arduino pro mini, receiver to Arduino Uno R3.

Output of receiver on serial looks like that (it doesn't change much):

Basicly I am getting either 75x or zero regardless of transmitter is on or off.

in > upper
756
in > upper
758
0
0
 0
in > upper
758
0
in > upper
757
in > upper

Transmitter code:

#define rfTransmitPin 4
#define ledPin 6

void setup()
{
    pinMode(rfTransmitPin, OUTPUT);
    pinMode(ledPin, OUTPUT);
}

void loop()
{
    for(;;)
    {
         digitalWrite(rfTransmitPin, HIGH);     //Transmit a HIGH signal
         analogWrite(ledPin, 255);              //Turn the LED on
         delay(500);                            //Wait for 1 second

         digitalWrite(rfTransmitPin,LOW);       //Transmit a LOW signal
         analogWrite(ledPin, 0);                //Turn the LED off
         delay(500);                            //Variable delay
    }
}

Receiver code:

const unsigned int upperThreshold = 70;  //upper threshold value
const unsigned int lowerThreshold = 0;  //lower threshold value
const int ledPin = 13;

#define ReceiverPin  A0

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

    pinMode(ledPin, OUTPUT);

    DiodeTest();
}

void loop()
{
   int data = analogRead(ReceiverPin);
   delay(50);

   if(data>upperThreshold)
   {
       digitalWrite(ledPin, LOW);   //If a LOW signal is received, turn LED OFF
       Serial.println("in > upper");
   }

   if(data<lowerThreshold)
   {
       digitalWrite(ledPin, HIGH);   //If a HIGH signal is received, turn LED ON
       Serial.println("in < lower" );
   }

   Serial.println(data);
}

These types of receivers are AC coupled so you will not be able to do what you are doing as you need to have regular transitions in the signal and not stay in one state for too long.

They are also limited in the speed at which they will work, I expect 19200 bps is too fast.

You need to use a modulation technique such as Manchester Encoding or other technique that guarantees a suitable density of transitions, can synchronize the data and perform error checking.

One popular software library that does this is VirtualWire Arduino Library that is designed for Arduino and the type of transmitters and receivers you are using.


Error: Cannot find module 'serialport'. node.js, Arduino Yun I carefully followed Andy Sigler's tutorial on how to setup node.js on Arduino Yun. But I'm getting this error "Cannot find module 'serialport'". my node.js file is in mnt/sda1/arduino/node folder. and I have installed node-serialport successfully through ssh. Kindly helpc

I solved the problem by following these steps:

Make a folder node_modules in mnt/sda1/

cd /mnt/sda1

wget http://wiki.linino.org/lib/exe/fetch.php?media=wiki:serialport-1.6.1_mips-25-ubuntu.tar.gz -O serialport-1.6.1_mips-25-ubuntu.tar.gz

run $ tar xvf serialport-1.6.1_mips-25-ubuntu.tar.gz -C /mnt/sda1/node_modules


What are exactly XTAL1 and XTAL2 pins in Arduino Uno/Nano? I know that the blow red encircled component is the 16MHz Crystal Oscillator (XTAL):

But PB6 and PB7 pins are called XTAL1 and XTAL2 pins which are not accessible by the Arduino board.

Are these pins where the 16MHz crystal oscillator is connected. But if so why are they two of them? I searched net but couldn't find explicit information about these.

How many clocks in total this board have?

The Crystal in Red is for the Atmega16U2 that manages the USB interface with its high speed connection to the PC (12 MHz for USB2 I think).

The Resonator in Yellow is for the Atmega328P.  It is less precise than the crystal oscillator.

PB6 and PB7 are dedicated to the external crystal or resonator by the fuse settings used for Arduino.

You can read more about the XTAL1, XTAL2 pins and the fuses from the device datasheet

https://www.microchip.com/wwwproducts/en/ATMEGA328P

You can connect a crystal to the pins, but you will also need 22pF caps to connect from the pins to Gnd. And remove the resonator.  Current Uno layout does not really support making those connections.


double to char* conversion. Weird results from dtostrf Here’s the code:

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

    double lat = 1111.11;
    double lon = 4444.44;

    const byte len{10};

    char sLat[len];
    char sLon[len];

    dtostrf(lat, len, 2, sLat);
    Serial.println(sLat);

    Serial.println("---");

    dtostrf(lon, len, 2, sLon);
    Serial.println(sLon);
    Serial.println(sLat); // <-- prints nothing!

    Serial.println("---");

    dtostrf(lat, len, 2, sLat);
    Serial.println(sLat);
    Serial.println(sLon); // <-- prints nothing!
}

void loop()
{
}

Here’s the output:

   1111.11
---
   4444.44

---
   1111.11
   4444.44   1111.11

As you see. Every next call for dtostrf ruins the previous results, in a weird way.

What’s the problem?

If len is the text array size, you need space there for the terminating '\0'.
So the second paramater to dtostrf has to be smaller than len.


Arduino board not recognized by Linux (dmesg, lsusb, etc.) I just received my first Arduino board which is essentially a Leonardo (ATmega32U4) customized to include a NFC reader (PN532).

When I plug it in, the PWR LED comes on steady, the D13 LED flashes a few times, and then the STA LED blinks once and only the PWR LED is left on. I can upload a basic sketch to the correct Serial Port, but the Serial Monitor is always empty.

I have noticed that, when uploading the sketch, the RX/TX LEDs stay off (which I thought was a sign of uploading/downloading data). I figured this was the root of my issue so I tried to look into it further. Running lsusb does not find the device and dmesg does not show any information when (un)plugging the device.

I also tried on a Windows install, but couldn't install the Leonardo drivers since Device Manager wouldn't register any unknown USB/Arduino devices.

Do you think my board is dead on arrival or am I doing something wrong?

Update:

I just uploaded the Blink tutorial sketch and it uploaded "successfully" but I noticed no differences. Please note that I don't have an external LED attached, but am looking at the board's LED on pin 13. This pin already flashes a few times (as mentioned above) on a reset, so I modified the delay times and still noticed no change.

I am uploading using board Leonardo, as recommended for my hardware, and the serial port /dev/ttyS0. I thought this was the right port because I remember not seeing it at first, but on second thought I had a permission issue at first (which is now resolved) causing me to not see the port.

So it looks like my board is not detected by my computer and I'm successfully uploading sketches to a meaningless port. Any troubleshooting options for me? I've tried different USB ports and am, as of recently, plugging my board into external power (9V). The only thing I can think of that on my end is that I'm using a Y-cable for my USB connection (I have a normal Mini-USB coming tomorrow via Amazon) since it is all I had. I can also confirm that this USB connection does power the board when plugged in.

So, to summarise the comments trail; the blinking lights at power-up are the normal boot sequence for the Leonardo,  indicating the processor is good, and that power is reaching the board; the device seen should be /dev/ttyACM0 or some other number; dmesg wasn't recording a plug-in event as the cable was not good.

We still don't quite know why the IDE thought it had sent a program to /dev/ttyS0, but presumably the level of interaction is much less (ie, none) via RS232 serial? Which explains why it said it had uploaded a test program when, in fact, it hadn't!

And replacing the USB cable has solved the problem - excellent news!


WiFiSSLClient will not connect to servers with LetsEncrypt certificates I'm trying to send data from an Arduino program to an app running on Google App Engine but WiFiSSLClient.connect() always returns false.

This is despite

the server being up and running;
the code working when the web app was on a different server.

The only possible explanation I can come up with is that the App Engine app uses a LetsEncrypt certificate while the other server was using one by another company.

WiFiSSLClient client;
if (client.connect(server, 443)){
    // Connected to server
} else {
    // Failed to connect
}

Does anyone have any solutions to this problem? I had a look at WiFiClientSecure; it has the ability to set the CA certificate in code but this seems like a bit of a pain.

The solution is to update the certificates the WIFI 101 Firmware Updater tool (in the Arduino IDE).

Install the FirmwareUpdater sketch, as described on the Arduino site.
Select Tools -> WiFi 101 Firmware Updater. Click on the Add domain button at the bottom, enter your domain and click Upload Certificates to WiFi module.

Upload the sketch to your Arduino. It should now connect to the server.


Arduino Mega - get mac adress I am new on Arduino, and I am trying to use the Ethernet shield...

but it need:

IP adress
MAC adress

IP adress is easy to get... but not MAC..

how can I get my arduino MAC adress?

A MAC address must be unique throughout the environment in which it operates, but apart from that is largely arbitrary.  Typically the problem is solved by selling 3-octet prefixes (called OUI's) to manufacturers, who then uniquely assign the remaining 3 octets to individual device units they manufacturer.

However, if you are unable to discovery a globally unique address assigned to your device by its manufacturer, and know that its traffic will be confined to a local network, you can use a privately assigned (ie, "made up") address with the Locally Administered bit set.   An address of the form

02-xx-xx-xx-xx-xx-xx

or any other with the 2's bit of the first octet set will satisfy this criteria as long as you guarantee that it is unique in your system.

Be especially careful not to set the 1's bit of the first octet - if you do so, traffic will be marked as broadcast and so given wider distribution/attention than needed, wasting network capacity and processor time of connected devices.


Power an arduino on a 12V circuit I am doing a simple circuit with a 12V power supply to power a 12V LED strip. I'd like to be able to switch ON/OFF the strip with a relay connected to my Arduino. I'd like to know if I can power my Arduino directly from the VIN pin using 12V source. I saw that the Arduino can support up to 12V.

Thank you in advance for the help.

As you have noted, many Arduino (and clones) are rated for supply voltage up to 12V. But note that if you use 12V power, the on-board regulator will get rather hot.  Providing decent ventilation and maybe even extra heat sink would be a good idea.


Which arduino will be suitable with bill acceptor I want to connect a bill acceptor (protocol ID003) and 3 switches and an Ethernet shield to Arduino. I am building a system that accepts bill and pass on the information to our software. Which Arduino will be the best choice, we need something which will have lot of code and also communication should be fast.

ARDUINO MEGA 2560 REV3
ARDUINO DUE
Arduino Uno REV3

--Edit--

This is I want to create:

A bill acceptor connected with arduino. Arduino has 3 buttons. (1. Play button, 2. redeem cash button. 3rd is not necessary).

When user login on machine, I get the details of user account through an API.

When user inserts money in bill acceptor, it enables the play button and add money in users account (If user already has money in account, button will be enabled). User can play until his account is not empty (i.e. if user has 200 in account, he can play 10 times). User can earn or lose money.

I have to send this transaction detail through an API.
If user press redeem button, it will print a slip of account details (Total money in account)

I am using Python.

I need to know which arduino is suitable for this, Ethernet shield compatible with that arduino (I think I am going to use ARDUINO MEGA 2560 REV3, but I don’t know Ethernet shield compatible with this model).

Also I need some Idea how can I make this. This is first time I am using arduino and bill acceptor.

Define 'lot of code', the Arduino Uno has 32 KB Flash, the Mega 256 KB.
Define 'fast', the Uno/Mega are 16 MHz, the Due 48 MHz
Three switches use 3 GPIO's, shouldn't be a problem on neither of them; the Mega has more GPIOs than the Uno, but both have plenty for your needs.
The Ethernet shield are available for all three
I don't know the 'bill acceptor', add a datasheet.

Conclusion: it depends on what is lot of code, and what is fast.


Arduino Micro just blinks, won't connect to PC Edit - Sorry it's a Micro not a Nano

I have a Micro board hooked up to an EasyDriver breakout using its 5V output to power the Micro.

Today I plugged it in and instead of booting up like normal the power LEDs on the wall plug, the easy driver, and the Arduino started flashing. The Micro became very hot, but not hot enough to burn.

After that if I plug the Micro into the USB port it just rapidly blinks the pin 13 LED. The PC does not detect the device but it does receive power.

Holding or pushing the reset button doesn't seem to help at all. I've used different USB cables, and different ports on the PC as well to no effect.

Is this something it can recover from? Why did all the LEDs blink like that?

I have something similar happen a couple of times with some atmega328s (on arduino unos). I believe it was the bootloader that some how became corrupted and so no longer responded to the computer. The only way to fix this is to reflash the bootloader using an ISP programmer. Luckily the arduino can act as an ISP programmer so all you need is another working arduino.

See https://www.arduino.cc/en/Tutorial/ArduinoISP for how to do this on an uno. The same can be done with the micro/nano as they all use the same atmega328p chip its just a matter of wiring it up correctly.

If you cannot reflash the bootloader with this method then one of the chips is probably damaged and would need to be replaced. At this point it might be easier to replace the whole board.


How to use and retrieve data file from AT command in Arduino D1 Mini Wemos (With esp8266) I stumbled upon an AT command for the ESP8266 that I really need. The following command is "AT+CWLAP", but I have no idea how to use it. I can't seem to find any resource on how to implement it.

I need the SSID, RSSI, and MAC addresses of the AP and pretty much use those data internally. For example (not necessarily doing this but you get the point), depending on the signal strength, choose the best option and print the SSID of the AP.

Is it even possible?

The command is documented in the ESP8266 AT Command Reference, with a non-PDF option at https://room-15.github.io/blog/2015/03/26/esp8266-at-command-reference/#AT+CWLAP

The response from the AT+CWLAP is a series of lines listing available access points, and for each, you are given their encryption method, SSID, RSSI, MAC, and the channel (or frequency offset and a calibration value).

It would be up to the you to parse the resulting strings to obtain the APs, sort by signal strength, and decide what to do with that information.

EDIT:

Because you are using the Arduino environment/core to write code for the ESP8266, you won't be able to use the AT command set. The AT Commands are available when the ESP8266 has the EspressIF firmware loaded to it, and thus the ESP8266 module is intended to be a peripheral device to some other controller; contrast with your use, where the ESP8266 is the only controller, with the WiFi ability baked in.

In this case, you will need to examine the features of the Arduino ESP8266 core, especially the ESP8266WiFi library, which gives an example sketch for scanning the available WiFi networks.


Unexpected behavior of sprintf with i32/u32 I'm trying to build a string of characters from several elements given by the TinyGPS++ library with the use of sprintf().

This is my code making the string and printing it in the serial monitor.

char posmsg[100], lat[14+1], lon[14+1];

void sendString(){
  //- convert lat/lon
  dtostrf(gps.location.lat(), 10,6, lat);
  dtostrf(gps.location.lng(), 10,6, lon);

  //- sprintf the string
  sprintf(posmsg, "$%4d-%02d-%02d %02d:%02d:%02d,%s,%s,%i,%i,%i,%i,%i$",
          gps.date.year(),gps.date.month(),gps.date.day(),
          gps.time.hour(), gps.time.minute(), gps.time.second(),
          lat, lon,
          gps.speed.value(), gps.course.value(), gps.altitude.value(),
          gps.satellites.value(), gps.hdop.value()
        );

  Serial.println("--------------------");
  Serial.println(posmsg);
  Serial.println("--------------------");

  Serial.print("Speed:");
  Serial.println(gps.speed.value());
  Serial.print("Course:");Serial.println(gps.course.value());
  Serial.print("Height:");Serial.println(gps.altitude.value());
  Serial.print("Sats:");Serial.println(gps.satellites.value());
  Serial.print("HDOP:");Serial.println(gps.hdop.value());
  Serial.println("--------------------");
}

This is the result and what I expect... (spaces added for readability)

 Result:
 --------------------
 $2014-06-24 15:17:11,  51.xxxxxx,   5.xxxxxx, 2, 0, 4964, 0, 3660$
 --------------------
 Speed:2
 Course:4964
 Height:3660
 Sats:8
 HDOP:110
 --------------------

 Expected:
 --------------------
 $2014-06-24 15:17:11,  51.xxxxxx,   5.xxxxxx, 2, 4964, 3660, 8, 110$
 --------------------

So in the end of the string the numbers get displaced...

According to the documentation the type of the variables are all integers or unsigned integers, but the sprintf messes things up.

 gps.speed.value(); // Raw speed in 100ths of a knot (i32)
 gps.course.value(); // Raw course in 100ths of a degree (i32)
 gps.altitude.value(); // Raw altitude in centimeters (i32)
 gps.satellites.value(); // Number of satellites in use (u32)
 gps.hdop.value(); // Horizontal Dim. of Precision (100ths-i32)

What am I doing wrong?

Ints and unsigned ints are 16 bits on AVR ATmegas.
So while the argument passed is a 32-bit value, sprintf() is expecting a 16 bit value.  The stack is packed with twice as much data as needed.

From the "2,0,4964" bit, it looks like it taking part of the previous/next parameter during processing, which makes me think this even more.

You need to use long types, e.g.: %ld or %li and %lu


Interacting with a video game - Keyboard & LUFA I have an Uno and Leonardo that I am trying to have it interact with the GTA V video game. Using the Keyboard library, it works within the OS. But it ocassionally works within the GTA V process. It seems that the transfer speed may be too slow, as the game sometimes registers the key press and does the assigned command.
For instance, I can have a pushbutton that when pressed, it activates Keyboard.Write('J'). While in GTA V, I can rapidly press the pushbutton for 3 seconds and the game will only detect one J within that time frame and do the assigned game command.
Yet, if I rearrange the code to be momentary to where the pushbutton is active, it'll constantly send Keyboard.Write('J'), this will work for commands that are momentary ingame, like the vehicle horn.
Below is the code I used for my Uno. It works fine within programs.

/*
  Keyboard Message test

  For the Arduino Leonardo and Micro.

  Sends a text string when a button is pressed.

  The circuit:
  - pushbutton attached from pin 4 to +5V
  - 10 kilohm resistor attached from pin 4 to ground

  created 24 Oct 2011
  modified 27 Mar 2012
  by Tom Igoe
  modified 11 Nov 2013
  by Scott Fitzgerald

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/KeyboardMessage
*/

#include "Keyboard.h"

const int buttonPin = 4;          // input pin for pushbutton
int previousButtonState = HIGH;   // for checking the state of a pushButton
int counter = 0;                  // button push counter

void setup() {
  // make the pushButton pin an input:
  pinMode(buttonPin, INPUT);
  // initialize control over the keyboard:
  Keyboard.begin();
}

void loop() {
  // read the pushbutton:
  int buttonState = digitalRead(buttonPin);
  // if the button state has changed,
  if ((buttonState != previousButtonState)
      // and it's currently pressed:
      && (buttonState == HIGH)) {
    // increment the button counter
    counter++;
    // type out a message
    Keyboard.write('J');
    //Keyboard.print("You pressed the button ");
    //Keyboard.print(counter);
    //Keyboard.println(" times.");
  }
  // save the current button state for comparison next time:
  previousButtonState = buttonState;
}

I also tried this same test using LUFA but the same issues were encountered.
I believe it has to do with the game, not my code.
Does anyone have a clue of why this might be?

It is quite common for games to be quite slow at reading the keyboard.

The Leonardo's Keyboard.write() command is quite rapid. The OS can pick it up with its interrupt driven buffering, but games tend not to use that buffering so they can get more realtime key control.

The trick here is actually to slow down the Leonardo's sending, by not using Keyboard.write(). Instead you need to press the key, wait a moment, then release the key:

Keyboard.press('j');
delay(1);
Keyboard.release('j');

Increase the delay until it becomes reliable. It's hard to say what the delay should be.


Water valve for food I am working on a project, where i need to control the flow of a liquid made from food.

For example: making chicken curry, I will separate all the liquid from the meat, and run that tough a pipe, where this control pipe is on.

But I have been unable to find a subtle valve for this, as the liquid on all of them will flow tough the mechanics of the valve, and this would not be optimal as it would make it impossible to clean, and it would diffidently get stuck.

Can one of you suggest a valve that would work for this case?

I would suggest, instead of a valve, a Peristaltic Pump.

In short, it comprises a set of rollers that squeeze a flexible tube and push the fluid along. It has good advantages for food use:

Very easy to clean - only the inside of the tube needs cleaning
Pumped fluid is not in physical contact with the pump mechanism so can't be contaminated.

They are used in many sterile environments - medical, industrial, etc., because they are so easy to keep clean and have no way of contaminating the pumped fluid. They are also good with viscous (sticky, gloopy) fluids like soups and sauces.

They can also deliver precisely measured amounts very easily.


Blank project gives errors while uploading Arduino Leonardo on Linux Manjaro I'm on Linux Manjaro. I plugged my Arduino Leonardo clone (that I know works correctly). And tried to flash a blank project on it:
(My IDE version is 1.8.12)

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

}

void loop() {
  // put your main code here, to run repeatedly:

}

It gives me this error:

Sketch uses 3410 bytes (11%) of program storage space. Maximum is 28672 bytes.
Global variables use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
    at processing.app.SketchController.upload(SketchController.java:732)
    at processing.app.SketchController.exportApplet(SketchController.java:703)
    at processing.app.Editor$UploadHandler.run(Editor.java:2047)
    at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: processing.app.SerialException: Error touching serial port '/dev/ttyACM1'.
    at processing.app.Serial.touchForCDCReset(Serial.java:107)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - /dev/ttyACM1; Method name - openPort(); Exception type - Permission denied.
    at jssc.SerialPort.openPort(SerialPort.java:170)
    at processing.app.Serial.touchForCDCReset(Serial.java:101)
    ... 6 more

Okay I found a way to do this.
Open Terminal and type:

ls -l /dev/ttyACM*

you will get something like:

crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is dialout (is the group owner of the file).

Now we just need to add our user to the group:

sudo usermod -a -G dialout <username>

So for me that would be:

sudo usermod -a -G dialout john

BUT it seems to work with dialout on ubuntu/debian based distros. I am on Manjaro and instead of dialout I had to use uucp (and in general on Arch based distros) so:

sudo usermod -a -G uucp john

You will need to log out and log in again for this change to take effect.

This is the procedure to access the serial port from the Arduino Software (IDE) if you get an error

After this procedure, you should be able to proceed normally and upload the sketch to your board or use the Serial Monitor.

Although for me that wasn't over. After doing this the only error I got was Arduino IDe simply saying that it doesn't have permission to write to that port. So I had to start Arduino IDE by:

sudo arduino

in the terminal. After that everything works just fine.

I found help at those links:

https://www.arduino.cc/en/Guide/Linux#toc6
https://forum.manjaro.org/t/how-to-enable-putty-usb-serial-converter-access-without-sudo/82736


Why does timer ISR not execute? This is my code which I have written as a library

#include "avr/interrupt.h"
#include "Arduino.h"
#include "AllTimer.h"

AllTimer::AllTimer()
{}

void AllTimer::dofun(void)
{
     //TIFR1 |= _BV(OCF1A);

    TCCR1B = 0X00;
    //TIFR1 = 0X01;
    digitalWrite(13,!digitalRead(13));
    Serial.print("I printed");
    TCNT1 = 0X0000;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    //sei();
}

 void AllTimer::setTimer(void)
 {
    TCNT1 = 0x0000;
    TCCR1A = 0x00;
    TCCR1B = 0x00;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    TIMSK1 |= (1<<TOIE1);
    sei();
 }

ISR (TIMER1_OVF_vect)
{
     AllTimer::dofun();
}

Code in Arduino IDE:

 #include <AllTimer.h>

 AllTimer mytimer;

 void setup()
 {
     pinMode(13,OUTPUT);
     Serial.begin(9600);
 }

 void loop()
 {
     mytimer.setTimer();
    //delay(200);
  }

But I am not getting anything on the serial monitor. What is the error I have made?

The Arduino main() calls loop() continuously, in a tight loop. Thus
your AllTimer::setTimer() is called continuously, and each time it
resets the counter (TCNT1 = 0x0000;). Thus the counter can never
overflow.


USB mouse/keyboard passthrough feasible? I'm looking to achieve the following:

USB HID Mouse (or Keyboard) -> [ Arduino device ] -> PC
                                       |
                                        `-> Internet

Basically, I want to connect a keyboard or mouse to an Arduino device, do some processing, send some data over the internet and then pass-through the USB data to the PC as if the Arduino wasn't even there.

My question is twofold: what hardware should I use? Right now I'm looking at the following peripherals:

Arduino Uno R3 SMD
Arduino Ethernet Shield
SparkFun USB Host Shield

Since I'm a complete neophyte when it comes to Arduino, I wanted to double-check and make sure my parts will fit together as well as work towards my goal. I was also contemplating the Arduino Leonardo (since it seems to provide mouse/keyboard out-of-the-box without reflashing the firmware), but I'm not sure I understand what that decision might entail.

Which brings me to my second question: is this feasible software-wise? I found this blog which has some information about pass-through connections, but the mouse library seems to be unfinished. I'd hate to invest 150+ dollars into a project that is doomed from the start.

Thank you!

To connect an external USB device to AVR you need USB Host supported on AVR side. Overhelming majority of AVR chips supports USB device only. There is e.g. AT90USB1287 chip exception. It even exists an AVR USB Key 2 device which can be used instead of normal Arduino unless you want make own PCBs.

Arduino UNO Mouse HID emulates USB mouse internally in Arduino. Implementing is easy when you have USB device AVR chip using LUFA library. But it's not case using external mouse. On the other side you can use legacy serial mouse or PS/2 keyboard as workaround.


Confuse about PROGMEM and R"====()====" I saw the following code from https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/ but I could not understand it thoroughly...
I looked at the documentation of PROGMEM from this https://www.arduino.cc/reference/en/language/variables/utilities/progmem/ but could not understand the importance in the code on why you should put your variables in flash memory instead of SRAM (the usual memory?)?
const char MAIN_page[] PROGMEM = R"=====(
  <!DOCTYPE html>

If you click on me, I will disappear.

Click me away!

Click me too!

  circuits4you.com

)=====";

Also, I could not understand the definition of R"====()====", what is meant by this in arduino?

why you should put your variables in flash memory instead of SRAM

Because the Arduino has only a very small amount of memory. If you have data that will never change it's better to store it in flash (of which there is much more) so as to leave the SRAM free for data that does change.

Also, I could not understand the definition of R"====()====", what is meant by this in arduino?

The R means "Treat everything between these delimiters as a raw string".  That is, everything between "=====( and )=====". It's not an Arduino thing, but a general C++ thing (see here). The ===== can be anything you like (within certain bounds) as long as it's the same at both the start and end of the string.  So you could use R"-=(This is "text")=-" which would assign the string This is "text". It's a great way of working with long strings that may want to contain " as otherwise you would have to escape each and every " as \". So the string I showed just now would otherwise have to be written as: "This is \"text\"", which can get very messy if there are lots of " in there.  The important thing to remember is that )===== mustn't appear in your text anywhere, so make sure it's something really obscure.


Multiple .ino files in the same sketch Yeah yeah, I know people ask this type of thing a lot, but I couldn't find an answer anywhere.

I understand that you can have multiple .ino files in one sketch, but I don't just want functions and variables separated, I want functionality.

I am writing a Braille program for the NodeMCU -- It takes a message from a served website and moves servos to emulate the appropriate Braille. I want to have 2 files: one to serve the website and get input from it (website.ino), and the other one to manipulate the servos(braille.ino). The only problem is, I can't figure out where to declare/attach the servos.

I plan to have a list of servos in braille.ino that will be looped over with each servo being set to a different value. If I declare them  in website.ino (my "main" file, ie, with a setup and loop), I will have to pass them to my braille function every time. On the other hand, if I choose to declare them as globals in my braille.ino, where would I attach them? Can I have another setup in braille.ino?

What isn't obvious is that with Arduino, you can have normal C and C++ files in the same directory as the .ino file. These can have functions and variables inside them, and Arduino will link them into the main program too. You only need one .ino file - all the rest can be in modules with a .c or .cpp (for C++) extension.

That way, you can group "helper" functions in different files by category - for example, a BrailleServo.c file. These contain the functions and variables for just that category.

If you haven't programmed native C/C++:

Put the functions and variables in the BrailleServo.c file, and then repeat the functions' header in the BrailleServo.h file.
Inside the BrailleServo.c file, at the top, put the following line:

#include "BrailleServo.h"

Note the quotes (" "), not angle brackets (< >)
Inside the .ino file, put the same #include line. That tells the module that "there are other functions elsewhere, and these are their definitions".

The only problem? Getting the silly Arduino environment to let you add .c and .h files to that directory. You could just use Notepad, but there's a trick (if you're using Windows):

Choose File|Open…
Right-click the pane with the files in it, and choose New >|Text Document
Give it a complete name, and make sure you replace the .txt part of the name too with .c or .h. You may get the "If you change the extension, the file may be unusable" warning - just click OK.
Select the new (blank) file in the file pane, and a new tab will appear.

  Note that 3. above assumes that you've told Windows File Explorer to NOT hide the extensions of known file types. I always do that - if you haven't, you'll need to. With:

  Windows 10:
  In any folder's View tab, tick the File name extensions checkbox;
  Windows 7:
  In Control Panel | Appearance and Personalization | Folder Options' View tab, untick Hide extensions for known file types

Here are three examples:

BrailleServo.h

//
// BrailleServo.h
//

// Call this function once in setup()
void BrailleInit();

// This function activates the six servos to form the passed-in pattern.
void BrailleShow(byte pattern);

BrailleServo.c

//
// BrailleServo.c
//

#include "BrailleServo.h"

// The number of servos
const byte NumServos = 6;

// These are the pins for the six servos
const byte servo[NumServos] = { 3, 4, 6, 7, 9, 10 };

// This initialises the six servos
void BrailleInit() {
   for (byte i=0; i<NumServos; ++i) {
      pinMode(servo[i], OUTPUT);
      // Do what else you need to do with servo[i]
   } // for
} // BrailleInit()

// This is how to use the six servos to form the passed-in pattern
void BrailleShow(byte pattern) {
   // … Complicated code here …
} // BrailleShow(pattern)

Main.ino

//
// Main.ino
//

#include "BrailleServo.h"

void setup() {
   BrailleInit();
   // Other stuff
} // setup()

void loop() {
   BrailleShow('A');
   delay(1000);
   BrailleShow('B');
   delay(1000);
} // loop()

Incidentally, for ideas you may want to check out my answer to a more generic Braille question.


Problem with ESP8266, wrong voltage? I recently bought a new ESP8266 because I'm pretty sure I used 5V instead of 3.3V on my old one.
But it seems the new one behaves the same as the old one.

I'm using the sketch:

https://i.imgur.com/CY6YF4E.jpg

When I open up the serial monitor and type [b]AT [/b]I get not response (on the 115200 baud).
If I boot up the power supply while the device is connected I get this in the serial monitor:

load 0x40100000, len 1856, room 16
tail 0
chksum 0x63
load 0x3ffe8000, len 776, room 8
tail 0
chksum 0x02
load 0x3ffe8310, len 552, room 8
tail 0
chksum 0x79
csum 0x79

2nd boot version : 1.5
  SPI Speed      : 40MHz
  SPI Mode       : DOUT
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

Fatal exception 0(IllegalInstructionCause):
epc1=0x40215021, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000

When I googled the log it seems to be related to the voltage. Could it be the same problem again? If so, what did I do wrong?

The ESP8266 has a relatively high peak current requirement compared to general microcontrollers. This is rarely fully understood. There is a lot of information on the Internet that says the current requirements is about 70mA. But that is a long term operational average. The peak current requirements can be as high as 1/2 an Amp.

When the ESP8266 starts one of the first things it does is an analog calibration. This is where it draws more current. If the power supply can not maintain the minimum required voltage at that current the voltage dip will cause a failure. The duration of this dip can be very short. A digital scope needed to see the fault.

I tend to recommend the use of ESP8266 modules that have an onboard regulator. Modules like the Wemos and Nodemcu type boards.

Using modules like the ESP-01 or the ESP-12 type modules (no regulators) are a lot more touchy. What you need to do is keep the 3.3v regulator as close as possible to those modules, and short solid connections. It also helps to have some additional capacitance across the 3.3v connections at the module.

Breadboards are convenient to use but they also can be the source of poor connections.

Consider what I have wrote here, how it applies to your setup. You may also want to solder an additional capacitor on the module. Vcc to ground. Something like 200-470uF, right onto the top of the module.


MCP23017 and stepper motors I am new to Arduino and programming and I am muddling along with some tutorials, I have a little project I am working on. It's basically an LCD screen with 5 buttons, a simple menu system that will control some stepper motors.

Now I have been able to both program and run the LCD from the Arduino and program and run the stepper motors. This was pretty straightforward due to the abundance of information. Now due to the small number of inputs on the Uno I knew I would need to expand on these so I bought some MCP23017 I/O expander chips.

Setting up the LCD on the MCP23017 was easy enough again due to the lots of tutorials and libraries, but I just cannot figure out how to work a stepper motor via the MCP23017. I am using 28BYJ-48 stepper motors and ULN2003 stepper driver boards. Yes I know cheap and nasty but they are fine for my task.

So I am basically looking for a little help on how to run stepper motors through the MCP23017 chips. I have the wiring and connections set up, just need some help on the programming.

I couldn't understand what the problem is, since you already managed to connect an LCD to it... Anyway...

To run a stepper motor you have to first define the control technique. AFAIK there are a few, but the ones I know are

full step
rotated full step
half step
microstep

Your motor is a unipolar motor. You have to connect the common wire to +5V, the other ones to one transistor of the ULN2003, and each transistor should be directly controlled by one pin. These are called phases (and let's call these PH1, PH2, PH3 and PH4).

Now for the explanation I'll use some tables. In these tables, each row is a step, each column a pin, and if there is a X the transistor should be on during that step.

Now, the full step technique is the simplest one. It consists of four phases:

Step PH1 PH2 PH3 PH4
  1   X
  2       X
  3           X
  4               X

As you can see, you just have to power each phase through each step. Cycling the steps as 1-2-3-4-1-2-3... will rotate in one sense, 4-3-2-1-4-3-2... in the other.

The rotated full step technique powers two phases at each step:

Step PH1 PH2 PH3 PH4
  1   X   X
  2       X   X
  3           X   X
  4   X           X

This usually gives a higher current consumption, but also higher torque.

The half step is a mix of the two:

Step PH1 PH2 PH3 PH4
  1   X
  2   X   X
  3       X
  4       X   X
  5           X
  6           X   X
  7               X
  8   X           X

As you can see, the number of steps per cycle is twice as much. This means that you can increase the accuracy (since a 32 steps/rev motor will now require 64 steps to perform a complete revolution).

The microstepping technique requires a different hardware, since it better controls the current in the phases to further divide each step in different steps.

Anyway, a basic implementation using the MCP23017 and the full step technique can be this one. I used Adafruit's library, but you can change using whatever library you chose or the direct calls you used for the LCD.

#include <Wire.h>
#include "Adafruit_MCP23017.h"
Adafruit_MCP23017 mcp1;

const byte PH1 = 0, PH2 = 1, PH2 = 3, PH3 = 4;

const byte phasesTable[][] = {
    { HIGH, LOW,  LOW,  LOW  },
    { LOW,  HIGH, LOW,  LOW  },
    { LOW,  LOW,  HIGH, LOW  },
    { LOW,  LOW,  LOW,  HIGH }
    };

int currentPosition, targetPosition;
unsigned long previousMillis;
const int StepDelayMs = 100; // delay between steps

void setup()
{
    mcp1.begin(0);
    mcp1.pinMode(PH1, OUTPUT);
    mcp1.pinMode(PH2, OUTPUT);
    mcp1.pinMode(PH3, OUTPUT);
    mcp1.pinMode(PH4, OUTPUT);
    currentPosition = -1; // force first update
    targetPosition = 0;
}

void loop()
{
    void updatePosition(); // function prototype
    updatePosition(); // execute the update

    // ----------------------
    // Functional part
    // ----------------------
    // Edit this code according to your application
    // changing the targetPosition variable (DON'T CHANGE
    // the currentPosition variable

    if (currentPosition == targetPosition)
    {
        if (targetPosition == 50)
            targetPosition = 0;
        else
            targetPosition = 50;
    }
}

void updatePosition()
{
    if ((millis() - previousMillis) > StepDelayMs)
    {
        previousMillis += StepDelayMs;

        if (targetPosition != currentPosition)
        {
            if (targetPosition < currentPosition)
                currentPosition--;
            else
                currentPosition++;

            byte phIdx = currentPosition % (sizeof(phasesTable) / sizeof(phasesTable[0]));

            mcp1.digitalWrite(PH1, phasesTable[phIdx][0]);
            mcp1.digitalWrite(PH2, phasesTable[phIdx][1]);
            mcp1.digitalWrite(PH3, phasesTable[phIdx][2]);
            mcp1.digitalWrite(PH4, phasesTable[phIdx][3]);
        }
    }
}

NOTE: I did not test this code, but I'm pretty confident it should work. Maybe there are some bugs left, however, but you should be able to correct them yourself.

The program behaves this way: every 100ms (you can go a bit faster, but sometimes you can lose steps, so you have to test it) it checks if the motor has reached the final position he needs to reach (targetPosition). If it has, the program does nothing. Otherwise it moves one step towards the target. All this is managed in the updatePosition function.

You have to call this in the loop (and make a NON BLOCKING loop, otherwise also the motor will block). In the loop, modify the target position that you need to reach (the part I called Functional part). In the example, the program moves the motor 50 steps back and forth (so 50 steps in one direction, then back to the origin, then to 50 and so on).

The control technique used is the full step. If you want to use another, change the phasesTable constant variable.

If you need more functionalities, there are a lot of libraries for the steppers. Just use the proper commands to edit the pins on the MCP rather than the ones on the board.


RGB LED blinks when analogWrite is low I have set up an LED who's brightness is controlled by a sonar sensor.  The sonar works well and I can see the values coming from it through the serial monitor.  The LED fades until about 700 using analogWrite

#include <NewPing.h>

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 5000

int LED_PIN = 3;

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
    pinMode(LED_PIN, OUTPUT);
    Serial.begin(9600);
}

void loop() {
    delay(50);
    int uS = sonar.ping();
    long int max_uS = 8000;
    float brightness = (1-(((float)uS/(float)max_uS)))*1024;
    if(brightness < 0){
        brightness = 0;
    }
    Serial.print("Distance: ");
    Serial.print(uS / US_ROUNDTRIP_IN);
    Serial.print("\" ");
    Serial.print(uS);
    Serial.print(" ");
    Serial.println(brightness, 5);

    analogWrite(LED_PIN, brightness);
}

When I view the serial monitor, I've made it output a line that looks like this:

Distance: 10" 1500 830.00000

830 is the number I'm using for my analogWrite.  I can move my hand farther and closer to the distance sensor and when I do, the light fades, but after 13" (which is brightness = 774) the LED looks like it turns back on high.

Between 1"-13" it fades very smoothly, except at 13" the light is almost out, then at about 14" it turns on again almost at full brightness and is very hit or miss from there.  Even though the numbers in the serial monitor are holding steady.

Any reason for this?

The maximum value you can pass to analogWrite() is 255. Anything higher than that will wrap around back to 0.

You should scale your value to fit into 0-255 instead of 0-1024.


Understanding arduino shield schematics I am researching the schematic of the arduino GSM shield.
Link is this:
https://www.sparkfun.com/datasheets/DevTools/Arduino/cellular%20shield-v12.pdf

What i do not understand is the upper right part, wich says ARDUINO_SHIELDNOHOLES.

What i want to do is understand which pins are used for Rx and which for Tx.

But there are four usable pins on the arduino side and six(?) pins on the other side which says jumper, where are six pins on seeminly two jumpers...

Can anyone understand what is going on here?

"ARDUINO_SHIELDNOHOLES" is a connector in the SparkFun EAGLE libraries which is basically, well, an Arduino shield. It provides the schematic symbol as well as the PCB landing pattern for such.

The pins on the top right of the schematic are two sets of 3, which should have jumpers connecting either 1 and 2, or 2 and 3. To use hardware serial to connect the Arduino to the SM5100B you connect 2 and 3 of the "top" one and 1 and 2 of the bottom one. This connects D0 (RX) and D1 (TX) of the Arduino to TXD0 and RXD0 of the SM5100B. If you want to use software serial instead, connect the other pairs. D2 will then be connected to TXD0 (and will become the software RX), and D3 will be connected to RXD0 (and will become the software TX).

As for "TXD0" and "RXD0" themselves, those are net names, and all wires with the same net name, such as those and the ones connected to pins 19 and 20 of the SM5100B, are considered to be the same wire even if they aren't connected in the schematic.


Connecting (SD or HD) TV screen to Arduino I had a thought about making myself an arcade cabinet. I found a nice cheap and sturdy 8 directional arcade joystick online, and now I'm thinking about the possible ways of displaying graphics.

I would like to know how can I send graphical data to a large screen using Arduino. When I was researching this I saw "TV Text" library that allows sending PAL and SECAM signals, but that's not the "modern" way. Is there a way of using DisplayPort or HDMI to simply use a cheap used PC monitor? Maybe there are other protocols that I can use? I'm looking for a "cheap" way to create a display that's physically as large as screen of arcades from "the good old days".

I'm just going to post things that I found thanks to comment by Juraj.

"TV Text" library - PAL, SECAM, NTSC
"VGAX" library - VGA

And with large dedication to everyone who wrote that "it's impossible" I give you a blog post of someone who actually did create he's own NTSC console and a game from scratch (called "The Box") using ATmega328P with external 16Mhz crystal. And he did it in 2013.

http://petenpaja.blogspot.com/2013/11/toorums-quest-ii-retro-video-game.html

Original sources were deleted, but I think they can be found when looking for Toorum Quest 2

I think I'll try analyzing the VGAX. It looks promising.

EDIT:

There actually is HDMI shield for Arduino!

https://github.com/techtoys/HDMI-Shield/tree/master/Ra8876_Lite

And a nice and very easy VGA tutorial here:

http://www.pyroelectro.com/tutorials/arduino_basic_vga/


No SPIFFS only OTA in NodeMCU ESP8266 I have a NodeMCU ESP8266  ESP-12E and I tried uploading a file thru the SPIFFS.  I am not sure why I see OTA instead of the SPIFFS?

Is there a configuration that I missed?

SPIFFS (SPI Flash File System)  is also know as FS(File system) . so What you are seeing as FS is basically SPIFFS .The OTA partition on esp8266 is compulsory so you cant get rid of it .
Hope this helps


Powering Adafruit motor shield Making sure not to blow anything up before testing.

I have an adafruit motor shield and an arduino Uno. The arduino uno has a power input and I was hoping to use it to power the motor shield, a nema-17 motor, and an I2C connection. Currently I'm using the power connection on the  motor shield to power the nema-17 motor and a serial connection to power the arduino.

Can I just connect a power supply to the input port on the ardiuno uno and power the motor shield and nema-17 step motor?

You should not power the motor shield (and thus the motor itself) through the Arduino. The motor draws a high current (depending on the exact product - there are many versions of the nema-17 - I found current in the range of 1 - 2A) and the voltage regulator (or the diode in the path) are not rated for this much current (for the Uno the absolute maximum is 200mA, including the Uno itself). You will fry these components, if you try to draw more than the rated current.

But you can use the same power supply and provide the power to Arduino and motor shield in parallel. This way the current for the motor does not have to pass through the Arduino.


Since double and float represent the same data type (usually), which is preferable? It looks like on ATMega based boards, float and double are equivalent 32-bit (4-byte) data types.

However, on the Arduino Due, doubles are 64-bit (8-byte) where floats are 32-bit (4-byte), same as the ATMega boards.

I also saw one source on avr-gcc that listed double as non-standard.

So, when writing code for ATMega based boards are floats preferable to using doubles, since that would make the code equivalent for Due boards? Or are doubles preferable for any reason?

See avr-gcc

  Deviations from the Standard

  double

  double is only 32 bits wide and implemented in the same way as float

  when writing code for ATMega based boards ...

They are the same, therefore.

(Edited to add)

  When writing code, is it then preferable to using one over the other?

I don't really understand your question. You asked about writing code for the ATMega based boards. Do you really mean, if you are writing code for the Due? The quick answer would be, on the Due, double takes twice the RAM, however it is over twice as precise - around 7.2 decimal digits for float compared to 15.9 for double. (I'm not sure about the speed, probably double would be slower, unless it is implemented in floating-point hardware - however I cannot see any reference to that on the AT91SAM3X8E datasheet).

See: https://en.wikipedia.org/wiki/Floating_point

If you want more precision (however slower and taking more RAM) then you could use double - which won't make any difference on the ATmega based boards, but will on the Due.

As Edgar Bonet said:

  I would use float so that anyone reading my code, who may not know about the non-standard AVR double, knows what precision to expect.

That makes quite a bit of sense.

I warn you though that "preferable" is subjective. It is close to asking "what is best"? To which the reply is: "best for what?"


Simple ModBus Master function 15 I have a simple setup with arduino Nano as slave and a arduino Mega as master
Can anyone explain how the function 15
FORCE_MULTIPLE_COILS
Works
i have been running some test on this
and cant figure out how to use the
local_start_address
is this the data to read from
or
is it a pointer to another File
modbus_construct(&packets[PACKET1], 1, 15, 1, 8, 1021);
dec 8 = (no_of_registers = packet->data)  // number of coils
so frame 6 = 1 (frame[6] = no_of_bytes;) // number of bytes more
dec 1021 = (packet->local_start_address)
the dec 1021 and 65565 seams to work ????
but makes no sense to me in binary format ?
Here is
part of CPP file:
enter code here

unsigned char construct_F15()
{
   // function 15 coil information is packed LSB first until the first 16 bits are completed
  // It is received the same way..
  unsigned char no_of_registers = packet->data / 16;
  unsigned char no_of_bytes = no_of_registers * 2;

  // if the number of points dont fit in even 2byte amounts (one register) then use another register and pad
  if (packet->data % 16 > 0)
  {
    no_of_registers++;
    no_of_bytes++;
  }

  frame[6] = no_of_bytes;
  unsigned char bytes_processed = 0;
  unsigned char index = 7; // user data starts at index 7
   unsigned int temp;

  for (unsigned char i = 0; i < no_of_registers; i++)
  {
    temp = register_array[packet->local_start_address + i]; // get the data

frame[index] = temp & 0xFF;

    bytes_processed++;

    if (bytes_processed < no_of_bytes)
    {
      frame[index + 1] = temp >> 8;
      bytes_processed++;
      index += 2;
    }
  }
   unsigned char frameSize = (9 + no_of_bytes); // first 7 bytes of the array + 2 bytes CRC + noOfBytes
   return frameSize;
}

i found it
it is the
temp = register_array[packet->local_start_address + i]; // get the data
in the ccp file
register_array[packet->local_start_address + i]
its pointing to the wrong location... register_array??
supersized no one has noticed this as long as the simple modbus master for adruino
has been used ?
or i have a bad CPP file ?
i have temp corrected this by replacing with
unsigned char construct_F15()
{
    // function 15 coil information is packed LSB first until the first 8 bits are completed
    unsigned char frameSize = 10;
    unsigned char temp;
    frame[6] = 1;
    frame[7] = packet->local_start_address ^ 0XFFFF;
    return frameSize;
}

works (0 = off / 255 = on)
modbus_construct(&packets[PACKET1], 1, 15, 1, 8, 0); // 1 thru 8 = off
modbus_construct(&packets[PACKET2], 1, 15, 1, 8, 255); // 1 thru 8 = on


ILI9163C screen not working properly I've just tried out my new TFT_ILI9163C display with TFT_ILI9163C library but I'm having an issue with it. The graphics has moved down (the "hello world" should be in the top left) and the leftover space looks like there was no signal. Can be seen in the photo.
What could be wrong?

I had the same board and problem as you, what fixed is was changing the board setting to black even though it is phyiscally red.

Inside

Arduino\libraries\TFT_ILI9163C\_settings\TFT_ILI9163C_settings.h

Change

//  ---> SELECT HERE <----
#define __144_RED_PCB__//128x128
//#define __144_BLACK_PCB__//128x128
//#define __22_RED_PCB__//240x320

to

//  ---> SELECT HERE <----
//#define __144_RED_PCB__//128x128
#define __144_BLACK_PCB__//128x128
//#define __22_RED_PCB__//240x320


blink led 5 times with for loop Is it possible to let a led blink, for example 5 times with Arduino?
Should I use a For loop?
Something like this works within the setup loop, but it will run continuesly in the void loop. So my led keeps blinking.
  for (int i = 0; i <= 5; i++) {
    led HIGH
    delay(500);
    led LOW
    delay(500);
  }

Also the blink sequence has to be triggered, and have a reset after it is done.
The complete code is to big to share, but it runs a bit like the following:
There is a "bankValue", it is filled by a user, and counts back to zero.
If it's zero, then blink 5 times.
After the blink, the leds are off.
The sketch is waiting for a new user, who will fill the bankValue again and the ledblink should again be initiated.

Its really heavy to give a correct answer, if you don't show us the context where the for loop is used. But I'll try:
There should be a part in the void loop method where you detect that the "bankValue" is down to zero. Like:
if (bankValue == 0)
{

}

First you must be sure that, the for loop is called within this block.
if (bankValue == 0)
{
  // I corrected the loop to run exact 5 times (<= -> <)
  for (int i = 0; i < 5; i++)
  {
    led HIGH
    delay(500);
    led LOW
    delay(500);
  }
}

Then you need a flag int blinkingDone = 0;  to indicate that the for loop has executed. This flag must be initialize with a falsy value, set to trueish after the loop is done and reset if the user "fills" the bankValue again.
Then you could use it as a guard to enter the for loop. Like:
int blinkingDone = 0;
int bankValue = 0;

..... somewhere else

if ( coin inserted or so )
{
  // fill bankValue
  blinkingDone = 0;
}

..... somewhere else

if (bankValue == 0 && ! blinkingDone)
{
  // I corrected the loop to run exact 5 times (<= -> <)
  for (int i = 0; i < 5; i++)
  {
    // led HIGH
    delay(500);
    // led LOW
    delay(500);
  }
  blinkingDone = 1;
}

There are potential better ways to do it. But I don't know your code. So this is the simplest way I can imagine.


Problem with connecting ESP8266 to arduino I have:

Arduino Uno
ESP8266

Problem:
I see SoftAP and can connect to it. But I can't send AT-commands to ESP8266 from Arduino.
I use Arduino app v.1.6.5 for send command to ESP8266 via Arduino. But I don't get answer. And ESP8266 doesn't blinking.

I use this scheme:

Please, help me. I'm trying to fix this is very time consuming.

I had the same problem. I used SoftwareSerial library, so you should set baud rate as 115200 for communication with esp8266. It might look like this:

#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3);

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

It helped in my case.


Does restarting Yún configuration mess up Arduino or its SD card? I noticed something odd recently - a Yún, that was working previously, wouldn't connect.

After logging in to the web setup, setting the access point and password (which hadn't changed), and save & restart, it connected. Unfortunately, it still doesn't work, and after ssh into it, I find I cannot ls /mnt/sd/ or sda1. It just sits there, requiring Ctrl+C, and gives no output.

Did I reset the Arduino or Linux somehow by setting up access point again, or could my SD card be broken after months of heavy logging?

It sounds like your SD card has likely failed. Try connecting it to a computer with an SD card reader. If it works at all, back it up immediately if you have files you wish to keep. Then try reading and writing files on it. Also if you have a spare SD card, try to use that in the Yun after setting it up appropriately. That should help narrow down the cause to either the Yun or the SD card.


Is it possible to move a servo without knowing it's current position? My Servo has already been built into my project, and I can't remove it without damaging many other things. During the process of inserting it, it was turned by hand. So I don't know at what position it is in. It turns a potentiometer that doesn't rotate fully. So I'm worried that if I just set a degree it could turn too far and damage the potentiometer or the servo.

What should I do to find the current position? Is it even possible?

A normal servo is an absolute positioning device. The position of the servo is directly proportional to the length in time of the sync pulse.  This means if you tell the servo to be in a given position, it will seek that position with out regard to the initial position.  It will simply figure out which way to go on it's own and stop when it gets there.

I should add, that in all likely hood, when you manually moved the servo you moved the positioning potentiometer inside the servo.  So it is expected that if the servo is told to go to a particular angle, it will still go to the same angle as it did before you manually moved it.


Could I use metal buttons as a capacitive button for my arduino project? Could I use something like this as a capacitive button for my arduino project?

http://www.banggood.com/10pcs-25mm-Vintage-Round-Metal-Buttons-Craft-Scrapbooking-Sewing-Suit-Shirt-Button-p-1011485.html

If I connect it into something like this... http://www.banggood.com/MPR121-Capacitive-Touch-Sensor-Module-For-Raspberry-Pi-Arduino-p-969002.html

Would that make that button a capacitive button? Or am I totally barking up the wrong tree here?

Thanks :)

Yes, that would work.

The only thing to watch out for is that the buttons might be plastic with a thin layer of metal on top (Chemical vapor deposition).


UNO Timer 1 CTC mode not resetting TCNT1 I'm trying to set up timer 1 to run an isr in CTC mode. no matter what i set OCR1A to it always executes at the same frequency and if i print out TCNT1 I get values higher than OCR1A.

here is my Code

    void timer1_init()
    {
    // set up timer with prescaler = 8 and CTC mode
    TCCR1B |= (1 << WGM12)|(0 << CS12)|(1 << CS11)|(0 << CS10);

    // initialize counter
    TCNT1 = 0;

    // initialize compare value
    OCR1A = 100;

    // enable compare interrupt
    TIMSK1 |= (1 << OCIE1A);

      // enable global interrupts
        sei();
    }

ISR(TIMER1_COMPA_vect){
    SET(MOTOR_PORT,LEFT_MOTOR_STEP); //set the pin high
    delayMicroseconds(3); //keep high for a bit
    CLR(MOTOR_PORT,LEFT_MOTOR_STEP); //set it low
}

I'm using this to drive a stepper motor so using PWM mode wont work.

It sounds as though timer 1 has not in fact been set to wavegen mode 4. You can ensure that it is by also clearing the other bits of WGM1:

TCCR1A &= ~(_BV(WGM10) | _BV(WGM11));
TCCR1B &= ~_BV(WGM13);


Interleave Assembly and Source for avr-objdump Trying to get avr-objdump to generate a listing that interleaves the assembly with the source code. I've tried a bunch of debugging arguments in different configurations but I can't seem to get it. The best I could do was getting it to interleave the object with line numbers from the assembly (avr-objdump -lS spi.o)

Original Makefile

Here's my current Makefile:

PREFIX=avr-
CC=${PREFIX}gcc
OBJCOPY=${PREFIX}objcopy

BIN=knightrider
MCU=attiny85
OBJS=../src/tinySPI.o src/knightrider.o

PROG?=atmelice_isp
PORT?=usb

CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

${BIN}.hex: ${BIN}.elf
    @mkdir -p bin
    ${OBJCOPY} -O ihex -R .eeprom build/$< bin/$@

${BIN}.elf: ${OBJS}
    @mkdir -p build
    ${CC} ${LDFLAGS} -o build/$@ $?

install: ${BIN}.hex
    avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U flash:w:${BIN}.hex:i -qq

clean:
    rm -f build/*
    rm -f bin/*

fuses:
    avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U lfuse:w:0x62:m -U hfuse:w:0xDF:m -U efuse:w:0xFF:i -qq

What would I need to change in order to run avr-objdump and get an interleaved listing of an .o and its corresponding .c (e.g. spi.o and spi.c)?

First make sure you add -g to all your compilation commands.

Then you can run avr-objdump -S build/spi.elf (for instance).

Also I see you're missing the MCU definition in your link command. Without that it won't link in the proper C startup routines and your program will most probably not run.

Here is a makefile I use:

PREFIX=avr-
CC=${PREFIX}gcc
CXX=${PREFIX}g++
LD=${PREFIX}ld
AS=${PREFIX}as
OBJCOPY=${PREFIX}objcopy
OBJDUMP=${PREFIX}objdump

BIN=blink
MCU=atmega328p
OBJS=blink.o

CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
CXXFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections -fno-exceptions
LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

${BIN}.hex: ${BIN}.elf
    ${OBJCOPY} -O ihex -R .eeprom $< $@

${BIN}.elf: ${OBJS}
    ${CC} ${LDFLAGS} -o $@ $?
    ${OBJDUMP} -S $@ > ${BIN}.dis

install: ${BIN}.hex
    avrdude -C ./avrdude.conf -c usbasp -p ${MCU} -U flash:w:${BIN}.hex
 -qq

clean:
    rm -f *.o *.elf *.hex

fuses:
    avrdude  -c usbasp -p ${MCU} -C avrdude.conf -U lfuse:w:0xff:m -U h
fuse:w:0xd6:m -U efuse:w:0x05:m -qq